PackageManagerService.java revision 1809ccc62e6c3649b3024a099dccccb3b773cf49
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        synchronized (mPackages) {
1718            for (String permission : pkg.requestedPermissions) {
1719                BasePermission bp = mSettings.mPermissions.get(permission);
1720                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1721                        && (grantedPermissions == null
1722                               || ArrayUtils.contains(grantedPermissions, permission))
1723                        && (getPermissionFlags(permission, pkg.packageName, userId)
1724                                & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) == 0) {
1725                    grantRuntimePermission(pkg.packageName, permission, userId);
1726                }
1727            }
1728        }
1729    }
1730
1731    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1732        Bundle extras = null;
1733        switch (res.returnCode) {
1734            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1735                extras = new Bundle();
1736                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1737                        res.origPermission);
1738                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1739                        res.origPackage);
1740                break;
1741            }
1742            case PackageManager.INSTALL_SUCCEEDED: {
1743                extras = new Bundle();
1744                extras.putBoolean(Intent.EXTRA_REPLACING,
1745                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1746                break;
1747            }
1748        }
1749        return extras;
1750    }
1751
1752    void scheduleWriteSettingsLocked() {
1753        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1754            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1755        }
1756    }
1757
1758    void scheduleWritePackageRestrictionsLocked(int userId) {
1759        if (!sUserManager.exists(userId)) return;
1760        mDirtyUsers.add(userId);
1761        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1762            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1763        }
1764    }
1765
1766    public static PackageManagerService main(Context context, Installer installer,
1767            boolean factoryTest, boolean onlyCore) {
1768        PackageManagerService m = new PackageManagerService(context, installer,
1769                factoryTest, onlyCore);
1770        ServiceManager.addService("package", m);
1771        return m;
1772    }
1773
1774    static String[] splitString(String str, char sep) {
1775        int count = 1;
1776        int i = 0;
1777        while ((i=str.indexOf(sep, i)) >= 0) {
1778            count++;
1779            i++;
1780        }
1781
1782        String[] res = new String[count];
1783        i=0;
1784        count = 0;
1785        int lastI=0;
1786        while ((i=str.indexOf(sep, i)) >= 0) {
1787            res[count] = str.substring(lastI, i);
1788            count++;
1789            i++;
1790            lastI = i;
1791        }
1792        res[count] = str.substring(lastI, str.length());
1793        return res;
1794    }
1795
1796    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1797        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1798                Context.DISPLAY_SERVICE);
1799        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1800    }
1801
1802    public PackageManagerService(Context context, Installer installer,
1803            boolean factoryTest, boolean onlyCore) {
1804        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1805                SystemClock.uptimeMillis());
1806
1807        if (mSdkVersion <= 0) {
1808            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1809        }
1810
1811        mContext = context;
1812        mFactoryTest = factoryTest;
1813        mOnlyCore = onlyCore;
1814        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1815        mMetrics = new DisplayMetrics();
1816        mSettings = new Settings(mPackages);
1817        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1818                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1819        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1820                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1821        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1822                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1823        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1824                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1825        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1826                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1827        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1828                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1829
1830        // TODO: add a property to control this?
1831        long dexOptLRUThresholdInMinutes;
1832        if (mLazyDexOpt) {
1833            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1834        } else {
1835            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1836        }
1837        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1838
1839        String separateProcesses = SystemProperties.get("debug.separate_processes");
1840        if (separateProcesses != null && separateProcesses.length() > 0) {
1841            if ("*".equals(separateProcesses)) {
1842                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1843                mSeparateProcesses = null;
1844                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1845            } else {
1846                mDefParseFlags = 0;
1847                mSeparateProcesses = separateProcesses.split(",");
1848                Slog.w(TAG, "Running with debug.separate_processes: "
1849                        + separateProcesses);
1850            }
1851        } else {
1852            mDefParseFlags = 0;
1853            mSeparateProcesses = null;
1854        }
1855
1856        mInstaller = installer;
1857        mPackageDexOptimizer = new PackageDexOptimizer(this);
1858        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1859
1860        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1861                FgThread.get().getLooper());
1862
1863        getDefaultDisplayMetrics(context, mMetrics);
1864
1865        SystemConfig systemConfig = SystemConfig.getInstance();
1866        mGlobalGids = systemConfig.getGlobalGids();
1867        mSystemPermissions = systemConfig.getSystemPermissions();
1868        mAvailableFeatures = systemConfig.getAvailableFeatures();
1869
1870        synchronized (mInstallLock) {
1871        // writer
1872        synchronized (mPackages) {
1873            mHandlerThread = new ServiceThread(TAG,
1874                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1875            mHandlerThread.start();
1876            mHandler = new PackageHandler(mHandlerThread.getLooper());
1877            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1878
1879            File dataDir = Environment.getDataDirectory();
1880            mAppDataDir = new File(dataDir, "data");
1881            mAppInstallDir = new File(dataDir, "app");
1882            mAppLib32InstallDir = new File(dataDir, "app-lib");
1883            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1884            mUserAppDataDir = new File(dataDir, "user");
1885            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1886
1887            sUserManager = new UserManagerService(context, this,
1888                    mInstallLock, mPackages);
1889
1890            // Propagate permission configuration in to package manager.
1891            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1892                    = systemConfig.getPermissions();
1893            for (int i=0; i<permConfig.size(); i++) {
1894                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1895                BasePermission bp = mSettings.mPermissions.get(perm.name);
1896                if (bp == null) {
1897                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1898                    mSettings.mPermissions.put(perm.name, bp);
1899                }
1900                if (perm.gids != null) {
1901                    bp.setGids(perm.gids, perm.perUser);
1902                }
1903            }
1904
1905            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1906            for (int i=0; i<libConfig.size(); i++) {
1907                mSharedLibraries.put(libConfig.keyAt(i),
1908                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1909            }
1910
1911            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1912
1913            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1914                    mSdkVersion, mOnlyCore);
1915
1916            String customResolverActivity = Resources.getSystem().getString(
1917                    R.string.config_customResolverActivity);
1918            if (TextUtils.isEmpty(customResolverActivity)) {
1919                customResolverActivity = null;
1920            } else {
1921                mCustomResolverComponentName = ComponentName.unflattenFromString(
1922                        customResolverActivity);
1923            }
1924
1925            long startTime = SystemClock.uptimeMillis();
1926
1927            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1928                    startTime);
1929
1930            // Set flag to monitor and not change apk file paths when
1931            // scanning install directories.
1932            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1933
1934            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1935
1936            /**
1937             * Add everything in the in the boot class path to the
1938             * list of process files because dexopt will have been run
1939             * if necessary during zygote startup.
1940             */
1941            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1942            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1943
1944            if (bootClassPath != null) {
1945                String[] bootClassPathElements = splitString(bootClassPath, ':');
1946                for (String element : bootClassPathElements) {
1947                    alreadyDexOpted.add(element);
1948                }
1949            } else {
1950                Slog.w(TAG, "No BOOTCLASSPATH found!");
1951            }
1952
1953            if (systemServerClassPath != null) {
1954                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1955                for (String element : systemServerClassPathElements) {
1956                    alreadyDexOpted.add(element);
1957                }
1958            } else {
1959                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1960            }
1961
1962            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1963            final String[] dexCodeInstructionSets =
1964                    getDexCodeInstructionSets(
1965                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1966
1967            /**
1968             * Ensure all external libraries have had dexopt run on them.
1969             */
1970            if (mSharedLibraries.size() > 0) {
1971                // NOTE: For now, we're compiling these system "shared libraries"
1972                // (and framework jars) into all available architectures. It's possible
1973                // to compile them only when we come across an app that uses them (there's
1974                // already logic for that in scanPackageLI) but that adds some complexity.
1975                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1976                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1977                        final String lib = libEntry.path;
1978                        if (lib == null) {
1979                            continue;
1980                        }
1981
1982                        try {
1983                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1984                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1985                                alreadyDexOpted.add(lib);
1986                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
1987                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
1988                            }
1989                        } catch (FileNotFoundException e) {
1990                            Slog.w(TAG, "Library not found: " + lib);
1991                        } catch (IOException e) {
1992                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1993                                    + e.getMessage());
1994                        }
1995                    }
1996                }
1997            }
1998
1999            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2000
2001            // Gross hack for now: we know this file doesn't contain any
2002            // code, so don't dexopt it to avoid the resulting log spew.
2003            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
2004
2005            // Gross hack for now: we know this file is only part of
2006            // the boot class path for art, so don't dexopt it to
2007            // avoid the resulting log spew.
2008            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2009
2010            /**
2011             * There are a number of commands implemented in Java, which
2012             * we currently need to do the dexopt on so that they can be
2013             * run from a non-root shell.
2014             */
2015            String[] frameworkFiles = frameworkDir.list();
2016            if (frameworkFiles != null) {
2017                // TODO: We could compile these only for the most preferred ABI. We should
2018                // first double check that the dex files for these commands are not referenced
2019                // by other system apps.
2020                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2021                    for (int i=0; i<frameworkFiles.length; i++) {
2022                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2023                        String path = libPath.getPath();
2024                        // Skip the file if we already did it.
2025                        if (alreadyDexOpted.contains(path)) {
2026                            continue;
2027                        }
2028                        // Skip the file if it is not a type we want to dexopt.
2029                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2030                            continue;
2031                        }
2032                        try {
2033                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2034                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2035                                mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet,
2036                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2037                            }
2038                        } catch (FileNotFoundException e) {
2039                            Slog.w(TAG, "Jar not found: " + path);
2040                        } catch (IOException e) {
2041                            Slog.w(TAG, "Exception reading jar: " + path, e);
2042                        }
2043                    }
2044                }
2045            }
2046
2047            final VersionInfo ver = mSettings.getInternalVersion();
2048            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2049            // when upgrading from pre-M, promote system app permissions from install to runtime
2050            mPromoteSystemApps =
2051                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2052
2053            // save off the names of pre-existing system packages prior to scanning; we don't
2054            // want to automatically grant runtime permissions for new system apps
2055            if (mPromoteSystemApps) {
2056                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2057                while (pkgSettingIter.hasNext()) {
2058                    PackageSetting ps = pkgSettingIter.next();
2059                    if (isSystemApp(ps)) {
2060                        mExistingSystemPackages.add(ps.name);
2061                    }
2062                }
2063            }
2064
2065            // Collect vendor overlay packages.
2066            // (Do this before scanning any apps.)
2067            // For security and version matching reason, only consider
2068            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2069            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2070            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2071                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2072
2073            // Find base frameworks (resource packages without code).
2074            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2075                    | PackageParser.PARSE_IS_SYSTEM_DIR
2076                    | PackageParser.PARSE_IS_PRIVILEGED,
2077                    scanFlags | SCAN_NO_DEX, 0);
2078
2079            // Collected privileged system packages.
2080            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2081            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2082                    | PackageParser.PARSE_IS_SYSTEM_DIR
2083                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2084
2085            // Collect ordinary system packages.
2086            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2087            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2088                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2089
2090            // Collect all vendor packages.
2091            File vendorAppDir = new File("/vendor/app");
2092            try {
2093                vendorAppDir = vendorAppDir.getCanonicalFile();
2094            } catch (IOException e) {
2095                // failed to look up canonical path, continue with original one
2096            }
2097            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2098                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2099
2100            // Collect all OEM packages.
2101            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2102            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2103                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2104
2105            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2106            mInstaller.moveFiles();
2107
2108            // Prune any system packages that no longer exist.
2109            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2110            if (!mOnlyCore) {
2111                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2112                while (psit.hasNext()) {
2113                    PackageSetting ps = psit.next();
2114
2115                    /*
2116                     * If this is not a system app, it can't be a
2117                     * disable system app.
2118                     */
2119                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2120                        continue;
2121                    }
2122
2123                    /*
2124                     * If the package is scanned, it's not erased.
2125                     */
2126                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2127                    if (scannedPkg != null) {
2128                        /*
2129                         * If the system app is both scanned and in the
2130                         * disabled packages list, then it must have been
2131                         * added via OTA. Remove it from the currently
2132                         * scanned package so the previously user-installed
2133                         * application can be scanned.
2134                         */
2135                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2136                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2137                                    + ps.name + "; removing system app.  Last known codePath="
2138                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2139                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2140                                    + scannedPkg.mVersionCode);
2141                            removePackageLI(ps, true);
2142                            mExpectingBetter.put(ps.name, ps.codePath);
2143                        }
2144
2145                        continue;
2146                    }
2147
2148                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2149                        psit.remove();
2150                        logCriticalInfo(Log.WARN, "System package " + ps.name
2151                                + " no longer exists; wiping its data");
2152                        removeDataDirsLI(null, ps.name);
2153                    } else {
2154                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2155                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2156                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2157                        }
2158                    }
2159                }
2160            }
2161
2162            //look for any incomplete package installations
2163            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2164            //clean up list
2165            for(int i = 0; i < deletePkgsList.size(); i++) {
2166                //clean up here
2167                cleanupInstallFailedPackage(deletePkgsList.get(i));
2168            }
2169            //delete tmp files
2170            deleteTempPackageFiles();
2171
2172            // Remove any shared userIDs that have no associated packages
2173            mSettings.pruneSharedUsersLPw();
2174
2175            if (!mOnlyCore) {
2176                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2177                        SystemClock.uptimeMillis());
2178                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2179
2180                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2181                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2182
2183                /**
2184                 * Remove disable package settings for any updated system
2185                 * apps that were removed via an OTA. If they're not a
2186                 * previously-updated app, remove them completely.
2187                 * Otherwise, just revoke their system-level permissions.
2188                 */
2189                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2190                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2191                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2192
2193                    String msg;
2194                    if (deletedPkg == null) {
2195                        msg = "Updated system package " + deletedAppName
2196                                + " no longer exists; wiping its data";
2197                        removeDataDirsLI(null, deletedAppName);
2198                    } else {
2199                        msg = "Updated system app + " + deletedAppName
2200                                + " no longer present; removing system privileges for "
2201                                + deletedAppName;
2202
2203                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2204
2205                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2206                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2207                    }
2208                    logCriticalInfo(Log.WARN, msg);
2209                }
2210
2211                /**
2212                 * Make sure all system apps that we expected to appear on
2213                 * the userdata partition actually showed up. If they never
2214                 * appeared, crawl back and revive the system version.
2215                 */
2216                for (int i = 0; i < mExpectingBetter.size(); i++) {
2217                    final String packageName = mExpectingBetter.keyAt(i);
2218                    if (!mPackages.containsKey(packageName)) {
2219                        final File scanFile = mExpectingBetter.valueAt(i);
2220
2221                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2222                                + " but never showed up; reverting to system");
2223
2224                        final int reparseFlags;
2225                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2226                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2227                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2228                                    | PackageParser.PARSE_IS_PRIVILEGED;
2229                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2230                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2231                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2232                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2233                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2234                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2235                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2236                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2237                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2238                        } else {
2239                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2240                            continue;
2241                        }
2242
2243                        mSettings.enableSystemPackageLPw(packageName);
2244
2245                        try {
2246                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2247                        } catch (PackageManagerException e) {
2248                            Slog.e(TAG, "Failed to parse original system package: "
2249                                    + e.getMessage());
2250                        }
2251                    }
2252                }
2253            }
2254            mExpectingBetter.clear();
2255
2256            // Now that we know all of the shared libraries, update all clients to have
2257            // the correct library paths.
2258            updateAllSharedLibrariesLPw();
2259
2260            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2261                // NOTE: We ignore potential failures here during a system scan (like
2262                // the rest of the commands above) because there's precious little we
2263                // can do about it. A settings error is reported, though.
2264                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2265                        false /* force dexopt */, false /* defer dexopt */,
2266                        false /* boot complete */);
2267            }
2268
2269            // Now that we know all the packages we are keeping,
2270            // read and update their last usage times.
2271            mPackageUsage.readLP();
2272
2273            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2274                    SystemClock.uptimeMillis());
2275            Slog.i(TAG, "Time to scan packages: "
2276                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2277                    + " seconds");
2278
2279            // If the platform SDK has changed since the last time we booted,
2280            // we need to re-grant app permission to catch any new ones that
2281            // appear.  This is really a hack, and means that apps can in some
2282            // cases get permissions that the user didn't initially explicitly
2283            // allow...  it would be nice to have some better way to handle
2284            // this situation.
2285            int updateFlags = UPDATE_PERMISSIONS_ALL;
2286            if (ver.sdkVersion != mSdkVersion) {
2287                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2288                        + mSdkVersion + "; regranting permissions for internal storage");
2289                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2290            }
2291            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2292            ver.sdkVersion = mSdkVersion;
2293
2294            // If this is the first boot or an update from pre-M, and it is a normal
2295            // boot, then we need to initialize the default preferred apps across
2296            // all defined users.
2297            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2298                for (UserInfo user : sUserManager.getUsers(true)) {
2299                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2300                    applyFactoryDefaultBrowserLPw(user.id);
2301                    primeDomainVerificationsLPw(user.id);
2302                }
2303            }
2304
2305            // If this is first boot after an OTA, and a normal boot, then
2306            // we need to clear code cache directories.
2307            if (mIsUpgrade && !onlyCore) {
2308                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2309                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2310                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2311                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2312                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2313                    }
2314                }
2315                ver.fingerprint = Build.FINGERPRINT;
2316            }
2317
2318            checkDefaultBrowser();
2319
2320            // clear only after permissions and other defaults have been updated
2321            mExistingSystemPackages.clear();
2322            mPromoteSystemApps = false;
2323
2324            // All the changes are done during package scanning.
2325            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2326
2327            // can downgrade to reader
2328            mSettings.writeLPr();
2329
2330            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2331                    SystemClock.uptimeMillis());
2332
2333            mRequiredVerifierPackage = getRequiredVerifierLPr();
2334            mRequiredInstallerPackage = getRequiredInstallerLPr();
2335
2336            mInstallerService = new PackageInstallerService(context, this);
2337
2338            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2339            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2340                    mIntentFilterVerifierComponent);
2341
2342        } // synchronized (mPackages)
2343        } // synchronized (mInstallLock)
2344
2345        // Now after opening every single application zip, make sure they
2346        // are all flushed.  Not really needed, but keeps things nice and
2347        // tidy.
2348        Runtime.getRuntime().gc();
2349
2350        // Expose private service for system components to use.
2351        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2352    }
2353
2354    @Override
2355    public boolean isFirstBoot() {
2356        return !mRestoredSettings;
2357    }
2358
2359    @Override
2360    public boolean isOnlyCoreApps() {
2361        return mOnlyCore;
2362    }
2363
2364    @Override
2365    public boolean isUpgrade() {
2366        return mIsUpgrade;
2367    }
2368
2369    private String getRequiredVerifierLPr() {
2370        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2371        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2372                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2373
2374        String requiredVerifier = null;
2375
2376        final int N = receivers.size();
2377        for (int i = 0; i < N; i++) {
2378            final ResolveInfo info = receivers.get(i);
2379
2380            if (info.activityInfo == null) {
2381                continue;
2382            }
2383
2384            final String packageName = info.activityInfo.packageName;
2385
2386            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2387                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2388                continue;
2389            }
2390
2391            if (requiredVerifier != null) {
2392                throw new RuntimeException("There can be only one required verifier");
2393            }
2394
2395            requiredVerifier = packageName;
2396        }
2397
2398        return requiredVerifier;
2399    }
2400
2401    private String getRequiredInstallerLPr() {
2402        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2403        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2404        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2405
2406        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2407                PACKAGE_MIME_TYPE, 0, 0);
2408
2409        String requiredInstaller = null;
2410
2411        final int N = installers.size();
2412        for (int i = 0; i < N; i++) {
2413            final ResolveInfo info = installers.get(i);
2414            final String packageName = info.activityInfo.packageName;
2415
2416            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2417                continue;
2418            }
2419
2420            if (requiredInstaller != null) {
2421                throw new RuntimeException("There must be one required installer");
2422            }
2423
2424            requiredInstaller = packageName;
2425        }
2426
2427        if (requiredInstaller == null) {
2428            throw new RuntimeException("There must be one required installer");
2429        }
2430
2431        return requiredInstaller;
2432    }
2433
2434    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2435        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2436        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2437                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2438
2439        ComponentName verifierComponentName = null;
2440
2441        int priority = -1000;
2442        final int N = receivers.size();
2443        for (int i = 0; i < N; i++) {
2444            final ResolveInfo info = receivers.get(i);
2445
2446            if (info.activityInfo == null) {
2447                continue;
2448            }
2449
2450            final String packageName = info.activityInfo.packageName;
2451
2452            final PackageSetting ps = mSettings.mPackages.get(packageName);
2453            if (ps == null) {
2454                continue;
2455            }
2456
2457            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2458                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2459                continue;
2460            }
2461
2462            // Select the IntentFilterVerifier with the highest priority
2463            if (priority < info.priority) {
2464                priority = info.priority;
2465                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2466                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2467                        + verifierComponentName + " with priority: " + info.priority);
2468            }
2469        }
2470
2471        return verifierComponentName;
2472    }
2473
2474    private void primeDomainVerificationsLPw(int userId) {
2475        if (DEBUG_DOMAIN_VERIFICATION) {
2476            Slog.d(TAG, "Priming domain verifications in user " + userId);
2477        }
2478
2479        SystemConfig systemConfig = SystemConfig.getInstance();
2480        ArraySet<String> packages = systemConfig.getLinkedApps();
2481        ArraySet<String> domains = new ArraySet<String>();
2482
2483        for (String packageName : packages) {
2484            PackageParser.Package pkg = mPackages.get(packageName);
2485            if (pkg != null) {
2486                if (!pkg.isSystemApp()) {
2487                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2488                    continue;
2489                }
2490
2491                domains.clear();
2492                for (PackageParser.Activity a : pkg.activities) {
2493                    for (ActivityIntentInfo filter : a.intents) {
2494                        if (hasValidDomains(filter)) {
2495                            domains.addAll(filter.getHostsList());
2496                        }
2497                    }
2498                }
2499
2500                if (domains.size() > 0) {
2501                    if (DEBUG_DOMAIN_VERIFICATION) {
2502                        Slog.v(TAG, "      + " + packageName);
2503                    }
2504                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2505                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2506                    // and then 'always' in the per-user state actually used for intent resolution.
2507                    final IntentFilterVerificationInfo ivi;
2508                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2509                            new ArrayList<String>(domains));
2510                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2511                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2512                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2513                } else {
2514                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2515                            + "' does not handle web links");
2516                }
2517            } else {
2518                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2519            }
2520        }
2521
2522        scheduleWritePackageRestrictionsLocked(userId);
2523        scheduleWriteSettingsLocked();
2524    }
2525
2526    private void applyFactoryDefaultBrowserLPw(int userId) {
2527        // The default browser app's package name is stored in a string resource,
2528        // with a product-specific overlay used for vendor customization.
2529        String browserPkg = mContext.getResources().getString(
2530                com.android.internal.R.string.default_browser);
2531        if (!TextUtils.isEmpty(browserPkg)) {
2532            // non-empty string => required to be a known package
2533            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2534            if (ps == null) {
2535                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2536                browserPkg = null;
2537            } else {
2538                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2539            }
2540        }
2541
2542        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2543        // default.  If there's more than one, just leave everything alone.
2544        if (browserPkg == null) {
2545            calculateDefaultBrowserLPw(userId);
2546        }
2547    }
2548
2549    private void calculateDefaultBrowserLPw(int userId) {
2550        List<String> allBrowsers = resolveAllBrowserApps(userId);
2551        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2552        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2553    }
2554
2555    private List<String> resolveAllBrowserApps(int userId) {
2556        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2557        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2558                PackageManager.MATCH_ALL, userId);
2559
2560        final int count = list.size();
2561        List<String> result = new ArrayList<String>(count);
2562        for (int i=0; i<count; i++) {
2563            ResolveInfo info = list.get(i);
2564            if (info.activityInfo == null
2565                    || !info.handleAllWebDataURI
2566                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2567                    || result.contains(info.activityInfo.packageName)) {
2568                continue;
2569            }
2570            result.add(info.activityInfo.packageName);
2571        }
2572
2573        return result;
2574    }
2575
2576    private boolean packageIsBrowser(String packageName, int userId) {
2577        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2578                PackageManager.MATCH_ALL, userId);
2579        final int N = list.size();
2580        for (int i = 0; i < N; i++) {
2581            ResolveInfo info = list.get(i);
2582            if (packageName.equals(info.activityInfo.packageName)) {
2583                return true;
2584            }
2585        }
2586        return false;
2587    }
2588
2589    private void checkDefaultBrowser() {
2590        final int myUserId = UserHandle.myUserId();
2591        final String packageName = getDefaultBrowserPackageName(myUserId);
2592        if (packageName != null) {
2593            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2594            if (info == null) {
2595                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2596                synchronized (mPackages) {
2597                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2598                }
2599            }
2600        }
2601    }
2602
2603    @Override
2604    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2605            throws RemoteException {
2606        try {
2607            return super.onTransact(code, data, reply, flags);
2608        } catch (RuntimeException e) {
2609            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2610                Slog.wtf(TAG, "Package Manager Crash", e);
2611            }
2612            throw e;
2613        }
2614    }
2615
2616    void cleanupInstallFailedPackage(PackageSetting ps) {
2617        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2618
2619        removeDataDirsLI(ps.volumeUuid, ps.name);
2620        if (ps.codePath != null) {
2621            if (ps.codePath.isDirectory()) {
2622                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2623            } else {
2624                ps.codePath.delete();
2625            }
2626        }
2627        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2628            if (ps.resourcePath.isDirectory()) {
2629                FileUtils.deleteContents(ps.resourcePath);
2630            }
2631            ps.resourcePath.delete();
2632        }
2633        mSettings.removePackageLPw(ps.name);
2634    }
2635
2636    static int[] appendInts(int[] cur, int[] add) {
2637        if (add == null) return cur;
2638        if (cur == null) return add;
2639        final int N = add.length;
2640        for (int i=0; i<N; i++) {
2641            cur = appendInt(cur, add[i]);
2642        }
2643        return cur;
2644    }
2645
2646    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2647        if (!sUserManager.exists(userId)) return null;
2648        final PackageSetting ps = (PackageSetting) p.mExtras;
2649        if (ps == null) {
2650            return null;
2651        }
2652
2653        final PermissionsState permissionsState = ps.getPermissionsState();
2654
2655        final int[] gids = permissionsState.computeGids(userId);
2656        final Set<String> permissions = permissionsState.getPermissions(userId);
2657        final PackageUserState state = ps.readUserState(userId);
2658
2659        return PackageParser.generatePackageInfo(p, gids, flags,
2660                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2661    }
2662
2663    @Override
2664    public boolean isPackageFrozen(String packageName) {
2665        synchronized (mPackages) {
2666            final PackageSetting ps = mSettings.mPackages.get(packageName);
2667            if (ps != null) {
2668                return ps.frozen;
2669            }
2670        }
2671        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2672        return true;
2673    }
2674
2675    @Override
2676    public boolean isPackageAvailable(String packageName, int userId) {
2677        if (!sUserManager.exists(userId)) return false;
2678        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2679        synchronized (mPackages) {
2680            PackageParser.Package p = mPackages.get(packageName);
2681            if (p != null) {
2682                final PackageSetting ps = (PackageSetting) p.mExtras;
2683                if (ps != null) {
2684                    final PackageUserState state = ps.readUserState(userId);
2685                    if (state != null) {
2686                        return PackageParser.isAvailable(state);
2687                    }
2688                }
2689            }
2690        }
2691        return false;
2692    }
2693
2694    @Override
2695    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2696        if (!sUserManager.exists(userId)) return null;
2697        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2698        // reader
2699        synchronized (mPackages) {
2700            PackageParser.Package p = mPackages.get(packageName);
2701            if (DEBUG_PACKAGE_INFO)
2702                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2703            if (p != null) {
2704                return generatePackageInfo(p, flags, userId);
2705            }
2706            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2707                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2708            }
2709        }
2710        return null;
2711    }
2712
2713    @Override
2714    public String[] currentToCanonicalPackageNames(String[] names) {
2715        String[] out = new String[names.length];
2716        // reader
2717        synchronized (mPackages) {
2718            for (int i=names.length-1; i>=0; i--) {
2719                PackageSetting ps = mSettings.mPackages.get(names[i]);
2720                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2721            }
2722        }
2723        return out;
2724    }
2725
2726    @Override
2727    public String[] canonicalToCurrentPackageNames(String[] names) {
2728        String[] out = new String[names.length];
2729        // reader
2730        synchronized (mPackages) {
2731            for (int i=names.length-1; i>=0; i--) {
2732                String cur = mSettings.mRenamedPackages.get(names[i]);
2733                out[i] = cur != null ? cur : names[i];
2734            }
2735        }
2736        return out;
2737    }
2738
2739    @Override
2740    public int getPackageUid(String packageName, int userId) {
2741        return getPackageUidEtc(packageName, 0, userId);
2742    }
2743
2744    @Override
2745    public int getPackageUidEtc(String packageName, int flags, int userId) {
2746        if (!sUserManager.exists(userId)) return -1;
2747        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2748
2749        // reader
2750        synchronized (mPackages) {
2751            final PackageParser.Package p = mPackages.get(packageName);
2752            if (p != null) {
2753                return UserHandle.getUid(userId, p.applicationInfo.uid);
2754            }
2755            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2756                final PackageSetting ps = mSettings.mPackages.get(packageName);
2757                if (ps != null) {
2758                    return UserHandle.getUid(userId, ps.appId);
2759                }
2760            }
2761        }
2762
2763        return -1;
2764    }
2765
2766    @Override
2767    public int[] getPackageGids(String packageName, int userId) {
2768        return getPackageGidsEtc(packageName, 0, userId);
2769    }
2770
2771    @Override
2772    public int[] getPackageGidsEtc(String packageName, int flags, int userId) {
2773        if (!sUserManager.exists(userId)) {
2774            return null;
2775        }
2776
2777        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2778                "getPackageGids");
2779
2780        // reader
2781        synchronized (mPackages) {
2782            final PackageParser.Package p = mPackages.get(packageName);
2783            if (p != null) {
2784                PackageSetting ps = (PackageSetting) p.mExtras;
2785                return ps.getPermissionsState().computeGids(userId);
2786            }
2787            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2788                final PackageSetting ps = mSettings.mPackages.get(packageName);
2789                if (ps != null) {
2790                    return ps.getPermissionsState().computeGids(userId);
2791                }
2792            }
2793        }
2794
2795        return null;
2796    }
2797
2798    static PermissionInfo generatePermissionInfo(
2799            BasePermission bp, int flags) {
2800        if (bp.perm != null) {
2801            return PackageParser.generatePermissionInfo(bp.perm, flags);
2802        }
2803        PermissionInfo pi = new PermissionInfo();
2804        pi.name = bp.name;
2805        pi.packageName = bp.sourcePackage;
2806        pi.nonLocalizedLabel = bp.name;
2807        pi.protectionLevel = bp.protectionLevel;
2808        return pi;
2809    }
2810
2811    @Override
2812    public PermissionInfo getPermissionInfo(String name, int flags) {
2813        // reader
2814        synchronized (mPackages) {
2815            final BasePermission p = mSettings.mPermissions.get(name);
2816            if (p != null) {
2817                return generatePermissionInfo(p, flags);
2818            }
2819            return null;
2820        }
2821    }
2822
2823    @Override
2824    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2825        // reader
2826        synchronized (mPackages) {
2827            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2828            for (BasePermission p : mSettings.mPermissions.values()) {
2829                if (group == null) {
2830                    if (p.perm == null || p.perm.info.group == null) {
2831                        out.add(generatePermissionInfo(p, flags));
2832                    }
2833                } else {
2834                    if (p.perm != null && group.equals(p.perm.info.group)) {
2835                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2836                    }
2837                }
2838            }
2839
2840            if (out.size() > 0) {
2841                return out;
2842            }
2843            return mPermissionGroups.containsKey(group) ? out : null;
2844        }
2845    }
2846
2847    @Override
2848    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2849        // reader
2850        synchronized (mPackages) {
2851            return PackageParser.generatePermissionGroupInfo(
2852                    mPermissionGroups.get(name), flags);
2853        }
2854    }
2855
2856    @Override
2857    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2858        // reader
2859        synchronized (mPackages) {
2860            final int N = mPermissionGroups.size();
2861            ArrayList<PermissionGroupInfo> out
2862                    = new ArrayList<PermissionGroupInfo>(N);
2863            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2864                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2865            }
2866            return out;
2867        }
2868    }
2869
2870    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2871            int userId) {
2872        if (!sUserManager.exists(userId)) return null;
2873        PackageSetting ps = mSettings.mPackages.get(packageName);
2874        if (ps != null) {
2875            if (ps.pkg == null) {
2876                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2877                        flags, userId);
2878                if (pInfo != null) {
2879                    return pInfo.applicationInfo;
2880                }
2881                return null;
2882            }
2883            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2884                    ps.readUserState(userId), userId);
2885        }
2886        return null;
2887    }
2888
2889    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2890            int userId) {
2891        if (!sUserManager.exists(userId)) return null;
2892        PackageSetting ps = mSettings.mPackages.get(packageName);
2893        if (ps != null) {
2894            PackageParser.Package pkg = ps.pkg;
2895            if (pkg == null) {
2896                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2897                    return null;
2898                }
2899                // Only data remains, so we aren't worried about code paths
2900                pkg = new PackageParser.Package(packageName);
2901                pkg.applicationInfo.packageName = packageName;
2902                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2903                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2904                pkg.applicationInfo.dataDir = Environment
2905                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2906                        .getAbsolutePath();
2907                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2908                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2909            }
2910            return generatePackageInfo(pkg, flags, userId);
2911        }
2912        return null;
2913    }
2914
2915    @Override
2916    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2917        if (!sUserManager.exists(userId)) return null;
2918        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2919        // writer
2920        synchronized (mPackages) {
2921            PackageParser.Package p = mPackages.get(packageName);
2922            if (DEBUG_PACKAGE_INFO) Log.v(
2923                    TAG, "getApplicationInfo " + packageName
2924                    + ": " + p);
2925            if (p != null) {
2926                PackageSetting ps = mSettings.mPackages.get(packageName);
2927                if (ps == null) return null;
2928                // Note: isEnabledLP() does not apply here - always return info
2929                return PackageParser.generateApplicationInfo(
2930                        p, flags, ps.readUserState(userId), userId);
2931            }
2932            if ("android".equals(packageName)||"system".equals(packageName)) {
2933                return mAndroidApplication;
2934            }
2935            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2936                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2937            }
2938        }
2939        return null;
2940    }
2941
2942    @Override
2943    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2944            final IPackageDataObserver observer) {
2945        mContext.enforceCallingOrSelfPermission(
2946                android.Manifest.permission.CLEAR_APP_CACHE, null);
2947        // Queue up an async operation since clearing cache may take a little while.
2948        mHandler.post(new Runnable() {
2949            public void run() {
2950                mHandler.removeCallbacks(this);
2951                int retCode = -1;
2952                synchronized (mInstallLock) {
2953                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2954                    if (retCode < 0) {
2955                        Slog.w(TAG, "Couldn't clear application caches");
2956                    }
2957                }
2958                if (observer != null) {
2959                    try {
2960                        observer.onRemoveCompleted(null, (retCode >= 0));
2961                    } catch (RemoteException e) {
2962                        Slog.w(TAG, "RemoveException when invoking call back");
2963                    }
2964                }
2965            }
2966        });
2967    }
2968
2969    @Override
2970    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2971            final IntentSender pi) {
2972        mContext.enforceCallingOrSelfPermission(
2973                android.Manifest.permission.CLEAR_APP_CACHE, null);
2974        // Queue up an async operation since clearing cache may take a little while.
2975        mHandler.post(new Runnable() {
2976            public void run() {
2977                mHandler.removeCallbacks(this);
2978                int retCode = -1;
2979                synchronized (mInstallLock) {
2980                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2981                    if (retCode < 0) {
2982                        Slog.w(TAG, "Couldn't clear application caches");
2983                    }
2984                }
2985                if(pi != null) {
2986                    try {
2987                        // Callback via pending intent
2988                        int code = (retCode >= 0) ? 1 : 0;
2989                        pi.sendIntent(null, code, null,
2990                                null, null);
2991                    } catch (SendIntentException e1) {
2992                        Slog.i(TAG, "Failed to send pending intent");
2993                    }
2994                }
2995            }
2996        });
2997    }
2998
2999    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3000        synchronized (mInstallLock) {
3001            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3002                throw new IOException("Failed to free enough space");
3003            }
3004        }
3005    }
3006
3007    @Override
3008    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3009        if (!sUserManager.exists(userId)) return null;
3010        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3011        synchronized (mPackages) {
3012            PackageParser.Activity a = mActivities.mActivities.get(component);
3013
3014            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3015            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3016                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3017                if (ps == null) return null;
3018                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3019                        userId);
3020            }
3021            if (mResolveComponentName.equals(component)) {
3022                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3023                        new PackageUserState(), userId);
3024            }
3025        }
3026        return null;
3027    }
3028
3029    @Override
3030    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3031            String resolvedType) {
3032        synchronized (mPackages) {
3033            if (component.equals(mResolveComponentName)) {
3034                // The resolver supports EVERYTHING!
3035                return true;
3036            }
3037            PackageParser.Activity a = mActivities.mActivities.get(component);
3038            if (a == null) {
3039                return false;
3040            }
3041            for (int i=0; i<a.intents.size(); i++) {
3042                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3043                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3044                    return true;
3045                }
3046            }
3047            return false;
3048        }
3049    }
3050
3051    @Override
3052    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3053        if (!sUserManager.exists(userId)) return null;
3054        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3055        synchronized (mPackages) {
3056            PackageParser.Activity a = mReceivers.mActivities.get(component);
3057            if (DEBUG_PACKAGE_INFO) Log.v(
3058                TAG, "getReceiverInfo " + component + ": " + a);
3059            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3060                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3061                if (ps == null) return null;
3062                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3063                        userId);
3064            }
3065        }
3066        return null;
3067    }
3068
3069    @Override
3070    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3071        if (!sUserManager.exists(userId)) return null;
3072        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3073        synchronized (mPackages) {
3074            PackageParser.Service s = mServices.mServices.get(component);
3075            if (DEBUG_PACKAGE_INFO) Log.v(
3076                TAG, "getServiceInfo " + component + ": " + s);
3077            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3078                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3079                if (ps == null) return null;
3080                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3081                        userId);
3082            }
3083        }
3084        return null;
3085    }
3086
3087    @Override
3088    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3089        if (!sUserManager.exists(userId)) return null;
3090        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3091        synchronized (mPackages) {
3092            PackageParser.Provider p = mProviders.mProviders.get(component);
3093            if (DEBUG_PACKAGE_INFO) Log.v(
3094                TAG, "getProviderInfo " + component + ": " + p);
3095            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3096                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3097                if (ps == null) return null;
3098                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3099                        userId);
3100            }
3101        }
3102        return null;
3103    }
3104
3105    @Override
3106    public String[] getSystemSharedLibraryNames() {
3107        Set<String> libSet;
3108        synchronized (mPackages) {
3109            libSet = mSharedLibraries.keySet();
3110            int size = libSet.size();
3111            if (size > 0) {
3112                String[] libs = new String[size];
3113                libSet.toArray(libs);
3114                return libs;
3115            }
3116        }
3117        return null;
3118    }
3119
3120    /**
3121     * @hide
3122     */
3123    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3124        synchronized (mPackages) {
3125            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3126            if (lib != null && lib.apk != null) {
3127                return mPackages.get(lib.apk);
3128            }
3129        }
3130        return null;
3131    }
3132
3133    @Override
3134    public FeatureInfo[] getSystemAvailableFeatures() {
3135        Collection<FeatureInfo> featSet;
3136        synchronized (mPackages) {
3137            featSet = mAvailableFeatures.values();
3138            int size = featSet.size();
3139            if (size > 0) {
3140                FeatureInfo[] features = new FeatureInfo[size+1];
3141                featSet.toArray(features);
3142                FeatureInfo fi = new FeatureInfo();
3143                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3144                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3145                features[size] = fi;
3146                return features;
3147            }
3148        }
3149        return null;
3150    }
3151
3152    @Override
3153    public boolean hasSystemFeature(String name) {
3154        synchronized (mPackages) {
3155            return mAvailableFeatures.containsKey(name);
3156        }
3157    }
3158
3159    private void checkValidCaller(int uid, int userId) {
3160        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3161            return;
3162
3163        throw new SecurityException("Caller uid=" + uid
3164                + " is not privileged to communicate with user=" + userId);
3165    }
3166
3167    @Override
3168    public int checkPermission(String permName, String pkgName, int userId) {
3169        if (!sUserManager.exists(userId)) {
3170            return PackageManager.PERMISSION_DENIED;
3171        }
3172
3173        synchronized (mPackages) {
3174            final PackageParser.Package p = mPackages.get(pkgName);
3175            if (p != null && p.mExtras != null) {
3176                final PackageSetting ps = (PackageSetting) p.mExtras;
3177                final PermissionsState permissionsState = ps.getPermissionsState();
3178                if (permissionsState.hasPermission(permName, userId)) {
3179                    return PackageManager.PERMISSION_GRANTED;
3180                }
3181                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3182                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3183                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3184                    return PackageManager.PERMISSION_GRANTED;
3185                }
3186            }
3187        }
3188
3189        return PackageManager.PERMISSION_DENIED;
3190    }
3191
3192    @Override
3193    public int checkUidPermission(String permName, int uid) {
3194        final int userId = UserHandle.getUserId(uid);
3195
3196        if (!sUserManager.exists(userId)) {
3197            return PackageManager.PERMISSION_DENIED;
3198        }
3199
3200        synchronized (mPackages) {
3201            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3202            if (obj != null) {
3203                final SettingBase ps = (SettingBase) obj;
3204                final PermissionsState permissionsState = ps.getPermissionsState();
3205                if (permissionsState.hasPermission(permName, userId)) {
3206                    return PackageManager.PERMISSION_GRANTED;
3207                }
3208                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3209                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3210                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3211                    return PackageManager.PERMISSION_GRANTED;
3212                }
3213            } else {
3214                ArraySet<String> perms = mSystemPermissions.get(uid);
3215                if (perms != null) {
3216                    if (perms.contains(permName)) {
3217                        return PackageManager.PERMISSION_GRANTED;
3218                    }
3219                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3220                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3221                        return PackageManager.PERMISSION_GRANTED;
3222                    }
3223                }
3224            }
3225        }
3226
3227        return PackageManager.PERMISSION_DENIED;
3228    }
3229
3230    @Override
3231    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3232        if (UserHandle.getCallingUserId() != userId) {
3233            mContext.enforceCallingPermission(
3234                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3235                    "isPermissionRevokedByPolicy for user " + userId);
3236        }
3237
3238        if (checkPermission(permission, packageName, userId)
3239                == PackageManager.PERMISSION_GRANTED) {
3240            return false;
3241        }
3242
3243        final long identity = Binder.clearCallingIdentity();
3244        try {
3245            final int flags = getPermissionFlags(permission, packageName, userId);
3246            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3247        } finally {
3248            Binder.restoreCallingIdentity(identity);
3249        }
3250    }
3251
3252    @Override
3253    public String getPermissionControllerPackageName() {
3254        synchronized (mPackages) {
3255            return mRequiredInstallerPackage;
3256        }
3257    }
3258
3259    /**
3260     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3261     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3262     * @param checkShell TODO(yamasani):
3263     * @param message the message to log on security exception
3264     */
3265    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3266            boolean checkShell, String message) {
3267        if (userId < 0) {
3268            throw new IllegalArgumentException("Invalid userId " + userId);
3269        }
3270        if (checkShell) {
3271            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3272        }
3273        if (userId == UserHandle.getUserId(callingUid)) return;
3274        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3275            if (requireFullPermission) {
3276                mContext.enforceCallingOrSelfPermission(
3277                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3278            } else {
3279                try {
3280                    mContext.enforceCallingOrSelfPermission(
3281                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3282                } catch (SecurityException se) {
3283                    mContext.enforceCallingOrSelfPermission(
3284                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3285                }
3286            }
3287        }
3288    }
3289
3290    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3291        if (callingUid == Process.SHELL_UID) {
3292            if (userHandle >= 0
3293                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3294                throw new SecurityException("Shell does not have permission to access user "
3295                        + userHandle);
3296            } else if (userHandle < 0) {
3297                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3298                        + Debug.getCallers(3));
3299            }
3300        }
3301    }
3302
3303    private BasePermission findPermissionTreeLP(String permName) {
3304        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3305            if (permName.startsWith(bp.name) &&
3306                    permName.length() > bp.name.length() &&
3307                    permName.charAt(bp.name.length()) == '.') {
3308                return bp;
3309            }
3310        }
3311        return null;
3312    }
3313
3314    private BasePermission checkPermissionTreeLP(String permName) {
3315        if (permName != null) {
3316            BasePermission bp = findPermissionTreeLP(permName);
3317            if (bp != null) {
3318                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3319                    return bp;
3320                }
3321                throw new SecurityException("Calling uid "
3322                        + Binder.getCallingUid()
3323                        + " is not allowed to add to permission tree "
3324                        + bp.name + " owned by uid " + bp.uid);
3325            }
3326        }
3327        throw new SecurityException("No permission tree found for " + permName);
3328    }
3329
3330    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3331        if (s1 == null) {
3332            return s2 == null;
3333        }
3334        if (s2 == null) {
3335            return false;
3336        }
3337        if (s1.getClass() != s2.getClass()) {
3338            return false;
3339        }
3340        return s1.equals(s2);
3341    }
3342
3343    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3344        if (pi1.icon != pi2.icon) return false;
3345        if (pi1.logo != pi2.logo) return false;
3346        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3347        if (!compareStrings(pi1.name, pi2.name)) return false;
3348        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3349        // We'll take care of setting this one.
3350        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3351        // These are not currently stored in settings.
3352        //if (!compareStrings(pi1.group, pi2.group)) return false;
3353        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3354        //if (pi1.labelRes != pi2.labelRes) return false;
3355        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3356        return true;
3357    }
3358
3359    int permissionInfoFootprint(PermissionInfo info) {
3360        int size = info.name.length();
3361        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3362        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3363        return size;
3364    }
3365
3366    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3367        int size = 0;
3368        for (BasePermission perm : mSettings.mPermissions.values()) {
3369            if (perm.uid == tree.uid) {
3370                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3371            }
3372        }
3373        return size;
3374    }
3375
3376    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3377        // We calculate the max size of permissions defined by this uid and throw
3378        // if that plus the size of 'info' would exceed our stated maximum.
3379        if (tree.uid != Process.SYSTEM_UID) {
3380            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3381            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3382                throw new SecurityException("Permission tree size cap exceeded");
3383            }
3384        }
3385    }
3386
3387    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3388        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3389            throw new SecurityException("Label must be specified in permission");
3390        }
3391        BasePermission tree = checkPermissionTreeLP(info.name);
3392        BasePermission bp = mSettings.mPermissions.get(info.name);
3393        boolean added = bp == null;
3394        boolean changed = true;
3395        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3396        if (added) {
3397            enforcePermissionCapLocked(info, tree);
3398            bp = new BasePermission(info.name, tree.sourcePackage,
3399                    BasePermission.TYPE_DYNAMIC);
3400        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3401            throw new SecurityException(
3402                    "Not allowed to modify non-dynamic permission "
3403                    + info.name);
3404        } else {
3405            if (bp.protectionLevel == fixedLevel
3406                    && bp.perm.owner.equals(tree.perm.owner)
3407                    && bp.uid == tree.uid
3408                    && comparePermissionInfos(bp.perm.info, info)) {
3409                changed = false;
3410            }
3411        }
3412        bp.protectionLevel = fixedLevel;
3413        info = new PermissionInfo(info);
3414        info.protectionLevel = fixedLevel;
3415        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3416        bp.perm.info.packageName = tree.perm.info.packageName;
3417        bp.uid = tree.uid;
3418        if (added) {
3419            mSettings.mPermissions.put(info.name, bp);
3420        }
3421        if (changed) {
3422            if (!async) {
3423                mSettings.writeLPr();
3424            } else {
3425                scheduleWriteSettingsLocked();
3426            }
3427        }
3428        return added;
3429    }
3430
3431    @Override
3432    public boolean addPermission(PermissionInfo info) {
3433        synchronized (mPackages) {
3434            return addPermissionLocked(info, false);
3435        }
3436    }
3437
3438    @Override
3439    public boolean addPermissionAsync(PermissionInfo info) {
3440        synchronized (mPackages) {
3441            return addPermissionLocked(info, true);
3442        }
3443    }
3444
3445    @Override
3446    public void removePermission(String name) {
3447        synchronized (mPackages) {
3448            checkPermissionTreeLP(name);
3449            BasePermission bp = mSettings.mPermissions.get(name);
3450            if (bp != null) {
3451                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3452                    throw new SecurityException(
3453                            "Not allowed to modify non-dynamic permission "
3454                            + name);
3455                }
3456                mSettings.mPermissions.remove(name);
3457                mSettings.writeLPr();
3458            }
3459        }
3460    }
3461
3462    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3463            BasePermission bp) {
3464        int index = pkg.requestedPermissions.indexOf(bp.name);
3465        if (index == -1) {
3466            throw new SecurityException("Package " + pkg.packageName
3467                    + " has not requested permission " + bp.name);
3468        }
3469        if (!bp.isRuntime() && !bp.isDevelopment()) {
3470            throw new SecurityException("Permission " + bp.name
3471                    + " is not a changeable permission type");
3472        }
3473    }
3474
3475    @Override
3476    public void grantRuntimePermission(String packageName, String name, final int userId) {
3477        if (!sUserManager.exists(userId)) {
3478            Log.e(TAG, "No such user:" + userId);
3479            return;
3480        }
3481
3482        mContext.enforceCallingOrSelfPermission(
3483                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3484                "grantRuntimePermission");
3485
3486        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3487                "grantRuntimePermission");
3488
3489        final int uid;
3490        final SettingBase sb;
3491
3492        synchronized (mPackages) {
3493            final PackageParser.Package pkg = mPackages.get(packageName);
3494            if (pkg == null) {
3495                throw new IllegalArgumentException("Unknown package: " + packageName);
3496            }
3497
3498            final BasePermission bp = mSettings.mPermissions.get(name);
3499            if (bp == null) {
3500                throw new IllegalArgumentException("Unknown permission: " + name);
3501            }
3502
3503            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3504
3505            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3506            sb = (SettingBase) pkg.mExtras;
3507            if (sb == null) {
3508                throw new IllegalArgumentException("Unknown package: " + packageName);
3509            }
3510
3511            final PermissionsState permissionsState = sb.getPermissionsState();
3512
3513            final int flags = permissionsState.getPermissionFlags(name, userId);
3514            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3515                throw new SecurityException("Cannot grant system fixed permission: "
3516                        + name + " for package: " + packageName);
3517            }
3518
3519            if (bp.isDevelopment()) {
3520                // Development permissions must be handled specially, since they are not
3521                // normal runtime permissions.  For now they apply to all users.
3522                if (permissionsState.grantInstallPermission(bp) !=
3523                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3524                    scheduleWriteSettingsLocked();
3525                }
3526                return;
3527            }
3528
3529            final int result = permissionsState.grantRuntimePermission(bp, userId);
3530            switch (result) {
3531                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3532                    return;
3533                }
3534
3535                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3536                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3537                    mHandler.post(new Runnable() {
3538                        @Override
3539                        public void run() {
3540                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3541                        }
3542                    });
3543                }
3544                break;
3545            }
3546
3547            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3548
3549            // Not critical if that is lost - app has to request again.
3550            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3551        }
3552
3553        // Only need to do this if user is initialized. Otherwise it's a new user
3554        // and there are no processes running as the user yet and there's no need
3555        // to make an expensive call to remount processes for the changed permissions.
3556        if (READ_EXTERNAL_STORAGE.equals(name)
3557                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3558            final long token = Binder.clearCallingIdentity();
3559            try {
3560                if (sUserManager.isInitialized(userId)) {
3561                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3562                            MountServiceInternal.class);
3563                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3564                }
3565            } finally {
3566                Binder.restoreCallingIdentity(token);
3567            }
3568        }
3569    }
3570
3571    @Override
3572    public void revokeRuntimePermission(String packageName, String name, int userId) {
3573        if (!sUserManager.exists(userId)) {
3574            Log.e(TAG, "No such user:" + userId);
3575            return;
3576        }
3577
3578        mContext.enforceCallingOrSelfPermission(
3579                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3580                "revokeRuntimePermission");
3581
3582        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3583                "revokeRuntimePermission");
3584
3585        final int appId;
3586
3587        synchronized (mPackages) {
3588            final PackageParser.Package pkg = mPackages.get(packageName);
3589            if (pkg == null) {
3590                throw new IllegalArgumentException("Unknown package: " + packageName);
3591            }
3592
3593            final BasePermission bp = mSettings.mPermissions.get(name);
3594            if (bp == null) {
3595                throw new IllegalArgumentException("Unknown permission: " + name);
3596            }
3597
3598            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3599
3600            SettingBase sb = (SettingBase) pkg.mExtras;
3601            if (sb == null) {
3602                throw new IllegalArgumentException("Unknown package: " + packageName);
3603            }
3604
3605            final PermissionsState permissionsState = sb.getPermissionsState();
3606
3607            final int flags = permissionsState.getPermissionFlags(name, userId);
3608            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3609                throw new SecurityException("Cannot revoke system fixed permission: "
3610                        + name + " for package: " + packageName);
3611            }
3612
3613            if (bp.isDevelopment()) {
3614                // Development permissions must be handled specially, since they are not
3615                // normal runtime permissions.  For now they apply to all users.
3616                if (permissionsState.revokeInstallPermission(bp) !=
3617                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3618                    scheduleWriteSettingsLocked();
3619                }
3620                return;
3621            }
3622
3623            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3624                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3625                return;
3626            }
3627
3628            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3629
3630            // Critical, after this call app should never have the permission.
3631            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3632
3633            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3634        }
3635
3636        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3637    }
3638
3639    @Override
3640    public void resetRuntimePermissions() {
3641        mContext.enforceCallingOrSelfPermission(
3642                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3643                "revokeRuntimePermission");
3644
3645        int callingUid = Binder.getCallingUid();
3646        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3647            mContext.enforceCallingOrSelfPermission(
3648                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3649                    "resetRuntimePermissions");
3650        }
3651
3652        synchronized (mPackages) {
3653            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3654            for (int userId : UserManagerService.getInstance().getUserIds()) {
3655                final int packageCount = mPackages.size();
3656                for (int i = 0; i < packageCount; i++) {
3657                    PackageParser.Package pkg = mPackages.valueAt(i);
3658                    if (!(pkg.mExtras instanceof PackageSetting)) {
3659                        continue;
3660                    }
3661                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3662                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3663                }
3664            }
3665        }
3666    }
3667
3668    @Override
3669    public int getPermissionFlags(String name, String packageName, int userId) {
3670        if (!sUserManager.exists(userId)) {
3671            return 0;
3672        }
3673
3674        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3675
3676        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3677                "getPermissionFlags");
3678
3679        synchronized (mPackages) {
3680            final PackageParser.Package pkg = mPackages.get(packageName);
3681            if (pkg == null) {
3682                throw new IllegalArgumentException("Unknown package: " + packageName);
3683            }
3684
3685            final BasePermission bp = mSettings.mPermissions.get(name);
3686            if (bp == null) {
3687                throw new IllegalArgumentException("Unknown permission: " + name);
3688            }
3689
3690            SettingBase sb = (SettingBase) pkg.mExtras;
3691            if (sb == null) {
3692                throw new IllegalArgumentException("Unknown package: " + packageName);
3693            }
3694
3695            PermissionsState permissionsState = sb.getPermissionsState();
3696            return permissionsState.getPermissionFlags(name, userId);
3697        }
3698    }
3699
3700    @Override
3701    public void updatePermissionFlags(String name, String packageName, int flagMask,
3702            int flagValues, int userId) {
3703        if (!sUserManager.exists(userId)) {
3704            return;
3705        }
3706
3707        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3708
3709        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3710                "updatePermissionFlags");
3711
3712        // Only the system can change these flags and nothing else.
3713        if (getCallingUid() != Process.SYSTEM_UID) {
3714            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3715            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3716            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3717            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3718        }
3719
3720        synchronized (mPackages) {
3721            final PackageParser.Package pkg = mPackages.get(packageName);
3722            if (pkg == null) {
3723                throw new IllegalArgumentException("Unknown package: " + packageName);
3724            }
3725
3726            final BasePermission bp = mSettings.mPermissions.get(name);
3727            if (bp == null) {
3728                throw new IllegalArgumentException("Unknown permission: " + name);
3729            }
3730
3731            SettingBase sb = (SettingBase) pkg.mExtras;
3732            if (sb == null) {
3733                throw new IllegalArgumentException("Unknown package: " + packageName);
3734            }
3735
3736            PermissionsState permissionsState = sb.getPermissionsState();
3737
3738            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3739
3740            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3741                // Install and runtime permissions are stored in different places,
3742                // so figure out what permission changed and persist the change.
3743                if (permissionsState.getInstallPermissionState(name) != null) {
3744                    scheduleWriteSettingsLocked();
3745                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3746                        || hadState) {
3747                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3748                }
3749            }
3750        }
3751    }
3752
3753    /**
3754     * Update the permission flags for all packages and runtime permissions of a user in order
3755     * to allow device or profile owner to remove POLICY_FIXED.
3756     */
3757    @Override
3758    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3759        if (!sUserManager.exists(userId)) {
3760            return;
3761        }
3762
3763        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3764
3765        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3766                "updatePermissionFlagsForAllApps");
3767
3768        // Only the system can change system fixed flags.
3769        if (getCallingUid() != Process.SYSTEM_UID) {
3770            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3771            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3772        }
3773
3774        synchronized (mPackages) {
3775            boolean changed = false;
3776            final int packageCount = mPackages.size();
3777            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3778                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3779                SettingBase sb = (SettingBase) pkg.mExtras;
3780                if (sb == null) {
3781                    continue;
3782                }
3783                PermissionsState permissionsState = sb.getPermissionsState();
3784                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3785                        userId, flagMask, flagValues);
3786            }
3787            if (changed) {
3788                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3789            }
3790        }
3791    }
3792
3793    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3794        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3795                != PackageManager.PERMISSION_GRANTED
3796            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3797                != PackageManager.PERMISSION_GRANTED) {
3798            throw new SecurityException(message + " requires "
3799                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3800                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3801        }
3802    }
3803
3804    @Override
3805    public boolean shouldShowRequestPermissionRationale(String permissionName,
3806            String packageName, int userId) {
3807        if (UserHandle.getCallingUserId() != userId) {
3808            mContext.enforceCallingPermission(
3809                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3810                    "canShowRequestPermissionRationale for user " + userId);
3811        }
3812
3813        final int uid = getPackageUid(packageName, userId);
3814        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3815            return false;
3816        }
3817
3818        if (checkPermission(permissionName, packageName, userId)
3819                == PackageManager.PERMISSION_GRANTED) {
3820            return false;
3821        }
3822
3823        final int flags;
3824
3825        final long identity = Binder.clearCallingIdentity();
3826        try {
3827            flags = getPermissionFlags(permissionName,
3828                    packageName, userId);
3829        } finally {
3830            Binder.restoreCallingIdentity(identity);
3831        }
3832
3833        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3834                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3835                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3836
3837        if ((flags & fixedFlags) != 0) {
3838            return false;
3839        }
3840
3841        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3842    }
3843
3844    @Override
3845    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3846        mContext.enforceCallingOrSelfPermission(
3847                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3848                "addOnPermissionsChangeListener");
3849
3850        synchronized (mPackages) {
3851            mOnPermissionChangeListeners.addListenerLocked(listener);
3852        }
3853    }
3854
3855    @Override
3856    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3857        synchronized (mPackages) {
3858            mOnPermissionChangeListeners.removeListenerLocked(listener);
3859        }
3860    }
3861
3862    @Override
3863    public boolean isProtectedBroadcast(String actionName) {
3864        synchronized (mPackages) {
3865            return mProtectedBroadcasts.contains(actionName);
3866        }
3867    }
3868
3869    @Override
3870    public int checkSignatures(String pkg1, String pkg2) {
3871        synchronized (mPackages) {
3872            final PackageParser.Package p1 = mPackages.get(pkg1);
3873            final PackageParser.Package p2 = mPackages.get(pkg2);
3874            if (p1 == null || p1.mExtras == null
3875                    || p2 == null || p2.mExtras == null) {
3876                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3877            }
3878            return compareSignatures(p1.mSignatures, p2.mSignatures);
3879        }
3880    }
3881
3882    @Override
3883    public int checkUidSignatures(int uid1, int uid2) {
3884        // Map to base uids.
3885        uid1 = UserHandle.getAppId(uid1);
3886        uid2 = UserHandle.getAppId(uid2);
3887        // reader
3888        synchronized (mPackages) {
3889            Signature[] s1;
3890            Signature[] s2;
3891            Object obj = mSettings.getUserIdLPr(uid1);
3892            if (obj != null) {
3893                if (obj instanceof SharedUserSetting) {
3894                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3895                } else if (obj instanceof PackageSetting) {
3896                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3897                } else {
3898                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3899                }
3900            } else {
3901                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3902            }
3903            obj = mSettings.getUserIdLPr(uid2);
3904            if (obj != null) {
3905                if (obj instanceof SharedUserSetting) {
3906                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3907                } else if (obj instanceof PackageSetting) {
3908                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3909                } else {
3910                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3911                }
3912            } else {
3913                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3914            }
3915            return compareSignatures(s1, s2);
3916        }
3917    }
3918
3919    private void killUid(int appId, int userId, String reason) {
3920        final long identity = Binder.clearCallingIdentity();
3921        try {
3922            IActivityManager am = ActivityManagerNative.getDefault();
3923            if (am != null) {
3924                try {
3925                    am.killUid(appId, userId, reason);
3926                } catch (RemoteException e) {
3927                    /* ignore - same process */
3928                }
3929            }
3930        } finally {
3931            Binder.restoreCallingIdentity(identity);
3932        }
3933    }
3934
3935    /**
3936     * Compares two sets of signatures. Returns:
3937     * <br />
3938     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3939     * <br />
3940     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3941     * <br />
3942     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3943     * <br />
3944     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3945     * <br />
3946     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3947     */
3948    static int compareSignatures(Signature[] s1, Signature[] s2) {
3949        if (s1 == null) {
3950            return s2 == null
3951                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3952                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3953        }
3954
3955        if (s2 == null) {
3956            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3957        }
3958
3959        if (s1.length != s2.length) {
3960            return PackageManager.SIGNATURE_NO_MATCH;
3961        }
3962
3963        // Since both signature sets are of size 1, we can compare without HashSets.
3964        if (s1.length == 1) {
3965            return s1[0].equals(s2[0]) ?
3966                    PackageManager.SIGNATURE_MATCH :
3967                    PackageManager.SIGNATURE_NO_MATCH;
3968        }
3969
3970        ArraySet<Signature> set1 = new ArraySet<Signature>();
3971        for (Signature sig : s1) {
3972            set1.add(sig);
3973        }
3974        ArraySet<Signature> set2 = new ArraySet<Signature>();
3975        for (Signature sig : s2) {
3976            set2.add(sig);
3977        }
3978        // Make sure s2 contains all signatures in s1.
3979        if (set1.equals(set2)) {
3980            return PackageManager.SIGNATURE_MATCH;
3981        }
3982        return PackageManager.SIGNATURE_NO_MATCH;
3983    }
3984
3985    /**
3986     * If the database version for this type of package (internal storage or
3987     * external storage) is less than the version where package signatures
3988     * were updated, return true.
3989     */
3990    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3991        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
3992        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
3993    }
3994
3995    /**
3996     * Used for backward compatibility to make sure any packages with
3997     * certificate chains get upgraded to the new style. {@code existingSigs}
3998     * will be in the old format (since they were stored on disk from before the
3999     * system upgrade) and {@code scannedSigs} will be in the newer format.
4000     */
4001    private int compareSignaturesCompat(PackageSignatures existingSigs,
4002            PackageParser.Package scannedPkg) {
4003        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4004            return PackageManager.SIGNATURE_NO_MATCH;
4005        }
4006
4007        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4008        for (Signature sig : existingSigs.mSignatures) {
4009            existingSet.add(sig);
4010        }
4011        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4012        for (Signature sig : scannedPkg.mSignatures) {
4013            try {
4014                Signature[] chainSignatures = sig.getChainSignatures();
4015                for (Signature chainSig : chainSignatures) {
4016                    scannedCompatSet.add(chainSig);
4017                }
4018            } catch (CertificateEncodingException e) {
4019                scannedCompatSet.add(sig);
4020            }
4021        }
4022        /*
4023         * Make sure the expanded scanned set contains all signatures in the
4024         * existing one.
4025         */
4026        if (scannedCompatSet.equals(existingSet)) {
4027            // Migrate the old signatures to the new scheme.
4028            existingSigs.assignSignatures(scannedPkg.mSignatures);
4029            // The new KeySets will be re-added later in the scanning process.
4030            synchronized (mPackages) {
4031                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4032            }
4033            return PackageManager.SIGNATURE_MATCH;
4034        }
4035        return PackageManager.SIGNATURE_NO_MATCH;
4036    }
4037
4038    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4039        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4040        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4041    }
4042
4043    private int compareSignaturesRecover(PackageSignatures existingSigs,
4044            PackageParser.Package scannedPkg) {
4045        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4046            return PackageManager.SIGNATURE_NO_MATCH;
4047        }
4048
4049        String msg = null;
4050        try {
4051            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4052                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4053                        + scannedPkg.packageName);
4054                return PackageManager.SIGNATURE_MATCH;
4055            }
4056        } catch (CertificateException e) {
4057            msg = e.getMessage();
4058        }
4059
4060        logCriticalInfo(Log.INFO,
4061                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4062        return PackageManager.SIGNATURE_NO_MATCH;
4063    }
4064
4065    @Override
4066    public String[] getPackagesForUid(int uid) {
4067        uid = UserHandle.getAppId(uid);
4068        // reader
4069        synchronized (mPackages) {
4070            Object obj = mSettings.getUserIdLPr(uid);
4071            if (obj instanceof SharedUserSetting) {
4072                final SharedUserSetting sus = (SharedUserSetting) obj;
4073                final int N = sus.packages.size();
4074                final String[] res = new String[N];
4075                final Iterator<PackageSetting> it = sus.packages.iterator();
4076                int i = 0;
4077                while (it.hasNext()) {
4078                    res[i++] = it.next().name;
4079                }
4080                return res;
4081            } else if (obj instanceof PackageSetting) {
4082                final PackageSetting ps = (PackageSetting) obj;
4083                return new String[] { ps.name };
4084            }
4085        }
4086        return null;
4087    }
4088
4089    @Override
4090    public String getNameForUid(int uid) {
4091        // reader
4092        synchronized (mPackages) {
4093            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4094            if (obj instanceof SharedUserSetting) {
4095                final SharedUserSetting sus = (SharedUserSetting) obj;
4096                return sus.name + ":" + sus.userId;
4097            } else if (obj instanceof PackageSetting) {
4098                final PackageSetting ps = (PackageSetting) obj;
4099                return ps.name;
4100            }
4101        }
4102        return null;
4103    }
4104
4105    @Override
4106    public int getUidForSharedUser(String sharedUserName) {
4107        if(sharedUserName == null) {
4108            return -1;
4109        }
4110        // reader
4111        synchronized (mPackages) {
4112            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4113            if (suid == null) {
4114                return -1;
4115            }
4116            return suid.userId;
4117        }
4118    }
4119
4120    @Override
4121    public int getFlagsForUid(int uid) {
4122        synchronized (mPackages) {
4123            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4124            if (obj instanceof SharedUserSetting) {
4125                final SharedUserSetting sus = (SharedUserSetting) obj;
4126                return sus.pkgFlags;
4127            } else if (obj instanceof PackageSetting) {
4128                final PackageSetting ps = (PackageSetting) obj;
4129                return ps.pkgFlags;
4130            }
4131        }
4132        return 0;
4133    }
4134
4135    @Override
4136    public int getPrivateFlagsForUid(int uid) {
4137        synchronized (mPackages) {
4138            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4139            if (obj instanceof SharedUserSetting) {
4140                final SharedUserSetting sus = (SharedUserSetting) obj;
4141                return sus.pkgPrivateFlags;
4142            } else if (obj instanceof PackageSetting) {
4143                final PackageSetting ps = (PackageSetting) obj;
4144                return ps.pkgPrivateFlags;
4145            }
4146        }
4147        return 0;
4148    }
4149
4150    @Override
4151    public boolean isUidPrivileged(int uid) {
4152        uid = UserHandle.getAppId(uid);
4153        // reader
4154        synchronized (mPackages) {
4155            Object obj = mSettings.getUserIdLPr(uid);
4156            if (obj instanceof SharedUserSetting) {
4157                final SharedUserSetting sus = (SharedUserSetting) obj;
4158                final Iterator<PackageSetting> it = sus.packages.iterator();
4159                while (it.hasNext()) {
4160                    if (it.next().isPrivileged()) {
4161                        return true;
4162                    }
4163                }
4164            } else if (obj instanceof PackageSetting) {
4165                final PackageSetting ps = (PackageSetting) obj;
4166                return ps.isPrivileged();
4167            }
4168        }
4169        return false;
4170    }
4171
4172    @Override
4173    public String[] getAppOpPermissionPackages(String permissionName) {
4174        synchronized (mPackages) {
4175            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4176            if (pkgs == null) {
4177                return null;
4178            }
4179            return pkgs.toArray(new String[pkgs.size()]);
4180        }
4181    }
4182
4183    @Override
4184    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4185            int flags, int userId) {
4186        if (!sUserManager.exists(userId)) return null;
4187        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4188        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4189        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4190    }
4191
4192    @Override
4193    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4194            IntentFilter filter, int match, ComponentName activity) {
4195        final int userId = UserHandle.getCallingUserId();
4196        if (DEBUG_PREFERRED) {
4197            Log.v(TAG, "setLastChosenActivity intent=" + intent
4198                + " resolvedType=" + resolvedType
4199                + " flags=" + flags
4200                + " filter=" + filter
4201                + " match=" + match
4202                + " activity=" + activity);
4203            filter.dump(new PrintStreamPrinter(System.out), "    ");
4204        }
4205        intent.setComponent(null);
4206        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4207        // Find any earlier preferred or last chosen entries and nuke them
4208        findPreferredActivity(intent, resolvedType,
4209                flags, query, 0, false, true, false, userId);
4210        // Add the new activity as the last chosen for this filter
4211        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4212                "Setting last chosen");
4213    }
4214
4215    @Override
4216    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4217        final int userId = UserHandle.getCallingUserId();
4218        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4219        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4220        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4221                false, false, false, userId);
4222    }
4223
4224    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4225            int flags, List<ResolveInfo> query, int userId) {
4226        if (query != null) {
4227            final int N = query.size();
4228            if (N == 1) {
4229                return query.get(0);
4230            } else if (N > 1) {
4231                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4232                // If there is more than one activity with the same priority,
4233                // then let the user decide between them.
4234                ResolveInfo r0 = query.get(0);
4235                ResolveInfo r1 = query.get(1);
4236                if (DEBUG_INTENT_MATCHING || debug) {
4237                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4238                            + r1.activityInfo.name + "=" + r1.priority);
4239                }
4240                // If the first activity has a higher priority, or a different
4241                // default, then it is always desireable to pick it.
4242                if (r0.priority != r1.priority
4243                        || r0.preferredOrder != r1.preferredOrder
4244                        || r0.isDefault != r1.isDefault) {
4245                    return query.get(0);
4246                }
4247                // If we have saved a preference for a preferred activity for
4248                // this Intent, use that.
4249                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4250                        flags, query, r0.priority, true, false, debug, userId);
4251                if (ri != null) {
4252                    return ri;
4253                }
4254                ri = new ResolveInfo(mResolveInfo);
4255                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4256                ri.activityInfo.applicationInfo = new ApplicationInfo(
4257                        ri.activityInfo.applicationInfo);
4258                if (userId != 0) {
4259                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4260                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4261                }
4262                // Make sure that the resolver is displayable in car mode
4263                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4264                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4265                return ri;
4266            }
4267        }
4268        return null;
4269    }
4270
4271    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4272            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4273        final int N = query.size();
4274        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4275                .get(userId);
4276        // Get the list of persistent preferred activities that handle the intent
4277        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4278        List<PersistentPreferredActivity> pprefs = ppir != null
4279                ? ppir.queryIntent(intent, resolvedType,
4280                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4281                : null;
4282        if (pprefs != null && pprefs.size() > 0) {
4283            final int M = pprefs.size();
4284            for (int i=0; i<M; i++) {
4285                final PersistentPreferredActivity ppa = pprefs.get(i);
4286                if (DEBUG_PREFERRED || debug) {
4287                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4288                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4289                            + "\n  component=" + ppa.mComponent);
4290                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4291                }
4292                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4293                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4294                if (DEBUG_PREFERRED || debug) {
4295                    Slog.v(TAG, "Found persistent preferred activity:");
4296                    if (ai != null) {
4297                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4298                    } else {
4299                        Slog.v(TAG, "  null");
4300                    }
4301                }
4302                if (ai == null) {
4303                    // This previously registered persistent preferred activity
4304                    // component is no longer known. Ignore it and do NOT remove it.
4305                    continue;
4306                }
4307                for (int j=0; j<N; j++) {
4308                    final ResolveInfo ri = query.get(j);
4309                    if (!ri.activityInfo.applicationInfo.packageName
4310                            .equals(ai.applicationInfo.packageName)) {
4311                        continue;
4312                    }
4313                    if (!ri.activityInfo.name.equals(ai.name)) {
4314                        continue;
4315                    }
4316                    //  Found a persistent preference that can handle the intent.
4317                    if (DEBUG_PREFERRED || debug) {
4318                        Slog.v(TAG, "Returning persistent preferred activity: " +
4319                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4320                    }
4321                    return ri;
4322                }
4323            }
4324        }
4325        return null;
4326    }
4327
4328    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4329            List<ResolveInfo> query, int priority, boolean always,
4330            boolean removeMatches, boolean debug, int userId) {
4331        if (!sUserManager.exists(userId)) return null;
4332        // writer
4333        synchronized (mPackages) {
4334            if (intent.getSelector() != null) {
4335                intent = intent.getSelector();
4336            }
4337            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4338
4339            // Try to find a matching persistent preferred activity.
4340            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4341                    debug, userId);
4342
4343            // If a persistent preferred activity matched, use it.
4344            if (pri != null) {
4345                return pri;
4346            }
4347
4348            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4349            // Get the list of preferred activities that handle the intent
4350            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4351            List<PreferredActivity> prefs = pir != null
4352                    ? pir.queryIntent(intent, resolvedType,
4353                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4354                    : null;
4355            if (prefs != null && prefs.size() > 0) {
4356                boolean changed = false;
4357                try {
4358                    // First figure out how good the original match set is.
4359                    // We will only allow preferred activities that came
4360                    // from the same match quality.
4361                    int match = 0;
4362
4363                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4364
4365                    final int N = query.size();
4366                    for (int j=0; j<N; j++) {
4367                        final ResolveInfo ri = query.get(j);
4368                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4369                                + ": 0x" + Integer.toHexString(match));
4370                        if (ri.match > match) {
4371                            match = ri.match;
4372                        }
4373                    }
4374
4375                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4376                            + Integer.toHexString(match));
4377
4378                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4379                    final int M = prefs.size();
4380                    for (int i=0; i<M; i++) {
4381                        final PreferredActivity pa = prefs.get(i);
4382                        if (DEBUG_PREFERRED || debug) {
4383                            Slog.v(TAG, "Checking PreferredActivity ds="
4384                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4385                                    + "\n  component=" + pa.mPref.mComponent);
4386                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4387                        }
4388                        if (pa.mPref.mMatch != match) {
4389                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4390                                    + Integer.toHexString(pa.mPref.mMatch));
4391                            continue;
4392                        }
4393                        // If it's not an "always" type preferred activity and that's what we're
4394                        // looking for, skip it.
4395                        if (always && !pa.mPref.mAlways) {
4396                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4397                            continue;
4398                        }
4399                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4400                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4401                        if (DEBUG_PREFERRED || debug) {
4402                            Slog.v(TAG, "Found preferred activity:");
4403                            if (ai != null) {
4404                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4405                            } else {
4406                                Slog.v(TAG, "  null");
4407                            }
4408                        }
4409                        if (ai == null) {
4410                            // This previously registered preferred activity
4411                            // component is no longer known.  Most likely an update
4412                            // to the app was installed and in the new version this
4413                            // component no longer exists.  Clean it up by removing
4414                            // it from the preferred activities list, and skip it.
4415                            Slog.w(TAG, "Removing dangling preferred activity: "
4416                                    + pa.mPref.mComponent);
4417                            pir.removeFilter(pa);
4418                            changed = true;
4419                            continue;
4420                        }
4421                        for (int j=0; j<N; j++) {
4422                            final ResolveInfo ri = query.get(j);
4423                            if (!ri.activityInfo.applicationInfo.packageName
4424                                    .equals(ai.applicationInfo.packageName)) {
4425                                continue;
4426                            }
4427                            if (!ri.activityInfo.name.equals(ai.name)) {
4428                                continue;
4429                            }
4430
4431                            if (removeMatches) {
4432                                pir.removeFilter(pa);
4433                                changed = true;
4434                                if (DEBUG_PREFERRED) {
4435                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4436                                }
4437                                break;
4438                            }
4439
4440                            // Okay we found a previously set preferred or last chosen app.
4441                            // If the result set is different from when this
4442                            // was created, we need to clear it and re-ask the
4443                            // user their preference, if we're looking for an "always" type entry.
4444                            if (always && !pa.mPref.sameSet(query)) {
4445                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4446                                        + intent + " type " + resolvedType);
4447                                if (DEBUG_PREFERRED) {
4448                                    Slog.v(TAG, "Removing preferred activity since set changed "
4449                                            + pa.mPref.mComponent);
4450                                }
4451                                pir.removeFilter(pa);
4452                                // Re-add the filter as a "last chosen" entry (!always)
4453                                PreferredActivity lastChosen = new PreferredActivity(
4454                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4455                                pir.addFilter(lastChosen);
4456                                changed = true;
4457                                return null;
4458                            }
4459
4460                            // Yay! Either the set matched or we're looking for the last chosen
4461                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4462                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4463                            return ri;
4464                        }
4465                    }
4466                } finally {
4467                    if (changed) {
4468                        if (DEBUG_PREFERRED) {
4469                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4470                        }
4471                        scheduleWritePackageRestrictionsLocked(userId);
4472                    }
4473                }
4474            }
4475        }
4476        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4477        return null;
4478    }
4479
4480    /*
4481     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4482     */
4483    @Override
4484    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4485            int targetUserId) {
4486        mContext.enforceCallingOrSelfPermission(
4487                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4488        List<CrossProfileIntentFilter> matches =
4489                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4490        if (matches != null) {
4491            int size = matches.size();
4492            for (int i = 0; i < size; i++) {
4493                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4494            }
4495        }
4496        if (hasWebURI(intent)) {
4497            // cross-profile app linking works only towards the parent.
4498            final UserInfo parent = getProfileParent(sourceUserId);
4499            synchronized(mPackages) {
4500                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4501                        intent, resolvedType, 0, sourceUserId, parent.id);
4502                return xpDomainInfo != null;
4503            }
4504        }
4505        return false;
4506    }
4507
4508    private UserInfo getProfileParent(int userId) {
4509        final long identity = Binder.clearCallingIdentity();
4510        try {
4511            return sUserManager.getProfileParent(userId);
4512        } finally {
4513            Binder.restoreCallingIdentity(identity);
4514        }
4515    }
4516
4517    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4518            String resolvedType, int userId) {
4519        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4520        if (resolver != null) {
4521            return resolver.queryIntent(intent, resolvedType, false, userId);
4522        }
4523        return null;
4524    }
4525
4526    @Override
4527    public List<ResolveInfo> queryIntentActivities(Intent intent,
4528            String resolvedType, int flags, int userId) {
4529        if (!sUserManager.exists(userId)) return Collections.emptyList();
4530        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4531        ComponentName comp = intent.getComponent();
4532        if (comp == null) {
4533            if (intent.getSelector() != null) {
4534                intent = intent.getSelector();
4535                comp = intent.getComponent();
4536            }
4537        }
4538
4539        if (comp != null) {
4540            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4541            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4542            if (ai != null) {
4543                final ResolveInfo ri = new ResolveInfo();
4544                ri.activityInfo = ai;
4545                list.add(ri);
4546            }
4547            return list;
4548        }
4549
4550        // reader
4551        synchronized (mPackages) {
4552            final String pkgName = intent.getPackage();
4553            if (pkgName == null) {
4554                List<CrossProfileIntentFilter> matchingFilters =
4555                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4556                // Check for results that need to skip the current profile.
4557                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4558                        resolvedType, flags, userId);
4559                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4560                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4561                    result.add(xpResolveInfo);
4562                    return filterIfNotPrimaryUser(result, userId);
4563                }
4564
4565                // Check for results in the current profile.
4566                List<ResolveInfo> result = mActivities.queryIntent(
4567                        intent, resolvedType, flags, userId);
4568
4569                // Check for cross profile results.
4570                xpResolveInfo = queryCrossProfileIntents(
4571                        matchingFilters, intent, resolvedType, flags, userId);
4572                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4573                    result.add(xpResolveInfo);
4574                    Collections.sort(result, mResolvePrioritySorter);
4575                }
4576                result = filterIfNotPrimaryUser(result, userId);
4577                if (hasWebURI(intent)) {
4578                    CrossProfileDomainInfo xpDomainInfo = null;
4579                    final UserInfo parent = getProfileParent(userId);
4580                    if (parent != null) {
4581                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4582                                flags, userId, parent.id);
4583                    }
4584                    if (xpDomainInfo != null) {
4585                        if (xpResolveInfo != null) {
4586                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4587                            // in the result.
4588                            result.remove(xpResolveInfo);
4589                        }
4590                        if (result.size() == 0) {
4591                            result.add(xpDomainInfo.resolveInfo);
4592                            return result;
4593                        }
4594                    } else if (result.size() <= 1) {
4595                        return result;
4596                    }
4597                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4598                            xpDomainInfo, userId);
4599                    Collections.sort(result, mResolvePrioritySorter);
4600                }
4601                return result;
4602            }
4603            final PackageParser.Package pkg = mPackages.get(pkgName);
4604            if (pkg != null) {
4605                return filterIfNotPrimaryUser(
4606                        mActivities.queryIntentForPackage(
4607                                intent, resolvedType, flags, pkg.activities, userId),
4608                        userId);
4609            }
4610            return new ArrayList<ResolveInfo>();
4611        }
4612    }
4613
4614    private static class CrossProfileDomainInfo {
4615        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4616        ResolveInfo resolveInfo;
4617        /* Best domain verification status of the activities found in the other profile */
4618        int bestDomainVerificationStatus;
4619    }
4620
4621    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4622            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4623        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4624                sourceUserId)) {
4625            return null;
4626        }
4627        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4628                resolvedType, flags, parentUserId);
4629
4630        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4631            return null;
4632        }
4633        CrossProfileDomainInfo result = null;
4634        int size = resultTargetUser.size();
4635        for (int i = 0; i < size; i++) {
4636            ResolveInfo riTargetUser = resultTargetUser.get(i);
4637            // Intent filter verification is only for filters that specify a host. So don't return
4638            // those that handle all web uris.
4639            if (riTargetUser.handleAllWebDataURI) {
4640                continue;
4641            }
4642            String packageName = riTargetUser.activityInfo.packageName;
4643            PackageSetting ps = mSettings.mPackages.get(packageName);
4644            if (ps == null) {
4645                continue;
4646            }
4647            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4648            int status = (int)(verificationState >> 32);
4649            if (result == null) {
4650                result = new CrossProfileDomainInfo();
4651                result.resolveInfo =
4652                        createForwardingResolveInfo(new IntentFilter(), sourceUserId, parentUserId);
4653                result.bestDomainVerificationStatus = status;
4654            } else {
4655                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4656                        result.bestDomainVerificationStatus);
4657            }
4658        }
4659        // Don't consider matches with status NEVER across profiles.
4660        if (result != null && result.bestDomainVerificationStatus
4661                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4662            return null;
4663        }
4664        return result;
4665    }
4666
4667    /**
4668     * Verification statuses are ordered from the worse to the best, except for
4669     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4670     */
4671    private int bestDomainVerificationStatus(int status1, int status2) {
4672        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4673            return status2;
4674        }
4675        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4676            return status1;
4677        }
4678        return (int) MathUtils.max(status1, status2);
4679    }
4680
4681    private boolean isUserEnabled(int userId) {
4682        long callingId = Binder.clearCallingIdentity();
4683        try {
4684            UserInfo userInfo = sUserManager.getUserInfo(userId);
4685            return userInfo != null && userInfo.isEnabled();
4686        } finally {
4687            Binder.restoreCallingIdentity(callingId);
4688        }
4689    }
4690
4691    /**
4692     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4693     *
4694     * @return filtered list
4695     */
4696    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4697        if (userId == UserHandle.USER_OWNER) {
4698            return resolveInfos;
4699        }
4700        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4701            ResolveInfo info = resolveInfos.get(i);
4702            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4703                resolveInfos.remove(i);
4704            }
4705        }
4706        return resolveInfos;
4707    }
4708
4709    private static boolean hasWebURI(Intent intent) {
4710        if (intent.getData() == null) {
4711            return false;
4712        }
4713        final String scheme = intent.getScheme();
4714        if (TextUtils.isEmpty(scheme)) {
4715            return false;
4716        }
4717        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4718    }
4719
4720    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4721            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4722            int userId) {
4723        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4724
4725        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4726            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4727                    candidates.size());
4728        }
4729
4730        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4731        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4732        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4733        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4734        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4735        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4736
4737        synchronized (mPackages) {
4738            final int count = candidates.size();
4739            // First, try to use linked apps. Partition the candidates into four lists:
4740            // one for the final results, one for the "do not use ever", one for "undefined status"
4741            // and finally one for "browser app type".
4742            for (int n=0; n<count; n++) {
4743                ResolveInfo info = candidates.get(n);
4744                String packageName = info.activityInfo.packageName;
4745                PackageSetting ps = mSettings.mPackages.get(packageName);
4746                if (ps != null) {
4747                    // Add to the special match all list (Browser use case)
4748                    if (info.handleAllWebDataURI) {
4749                        matchAllList.add(info);
4750                        continue;
4751                    }
4752                    // Try to get the status from User settings first
4753                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4754                    int status = (int)(packedStatus >> 32);
4755                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4756                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4757                        if (DEBUG_DOMAIN_VERIFICATION) {
4758                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4759                                    + " : linkgen=" + linkGeneration);
4760                        }
4761                        // Use link-enabled generation as preferredOrder, i.e.
4762                        // prefer newly-enabled over earlier-enabled.
4763                        info.preferredOrder = linkGeneration;
4764                        alwaysList.add(info);
4765                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4766                        if (DEBUG_DOMAIN_VERIFICATION) {
4767                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4768                        }
4769                        neverList.add(info);
4770                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4771                        if (DEBUG_DOMAIN_VERIFICATION) {
4772                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4773                        }
4774                        alwaysAskList.add(info);
4775                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4776                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4777                        if (DEBUG_DOMAIN_VERIFICATION) {
4778                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4779                        }
4780                        undefinedList.add(info);
4781                    }
4782                }
4783            }
4784
4785            // We'll want to include browser possibilities in a few cases
4786            boolean includeBrowser = false;
4787
4788            // First try to add the "always" resolution(s) for the current user, if any
4789            if (alwaysList.size() > 0) {
4790                result.addAll(alwaysList);
4791            } else {
4792                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4793                result.addAll(undefinedList);
4794                // Maybe add one for the other profile.
4795                if (xpDomainInfo != null && (
4796                        xpDomainInfo.bestDomainVerificationStatus
4797                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
4798                    result.add(xpDomainInfo.resolveInfo);
4799                }
4800                includeBrowser = true;
4801            }
4802
4803            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4804            // If there were 'always' entries their preferred order has been set, so we also
4805            // back that off to make the alternatives equivalent
4806            if (alwaysAskList.size() > 0) {
4807                for (ResolveInfo i : result) {
4808                    i.preferredOrder = 0;
4809                }
4810                result.addAll(alwaysAskList);
4811                includeBrowser = true;
4812            }
4813
4814            if (includeBrowser) {
4815                // Also add browsers (all of them or only the default one)
4816                if (DEBUG_DOMAIN_VERIFICATION) {
4817                    Slog.v(TAG, "   ...including browsers in candidate set");
4818                }
4819                if ((matchFlags & MATCH_ALL) != 0) {
4820                    result.addAll(matchAllList);
4821                } else {
4822                    // Browser/generic handling case.  If there's a default browser, go straight
4823                    // to that (but only if there is no other higher-priority match).
4824                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4825                    int maxMatchPrio = 0;
4826                    ResolveInfo defaultBrowserMatch = null;
4827                    final int numCandidates = matchAllList.size();
4828                    for (int n = 0; n < numCandidates; n++) {
4829                        ResolveInfo info = matchAllList.get(n);
4830                        // track the highest overall match priority...
4831                        if (info.priority > maxMatchPrio) {
4832                            maxMatchPrio = info.priority;
4833                        }
4834                        // ...and the highest-priority default browser match
4835                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4836                            if (defaultBrowserMatch == null
4837                                    || (defaultBrowserMatch.priority < info.priority)) {
4838                                if (debug) {
4839                                    Slog.v(TAG, "Considering default browser match " + info);
4840                                }
4841                                defaultBrowserMatch = info;
4842                            }
4843                        }
4844                    }
4845                    if (defaultBrowserMatch != null
4846                            && defaultBrowserMatch.priority >= maxMatchPrio
4847                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4848                    {
4849                        if (debug) {
4850                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4851                        }
4852                        result.add(defaultBrowserMatch);
4853                    } else {
4854                        result.addAll(matchAllList);
4855                    }
4856                }
4857
4858                // If there is nothing selected, add all candidates and remove the ones that the user
4859                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4860                if (result.size() == 0) {
4861                    result.addAll(candidates);
4862                    result.removeAll(neverList);
4863                }
4864            }
4865        }
4866        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4867            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4868                    result.size());
4869            for (ResolveInfo info : result) {
4870                Slog.v(TAG, "  + " + info.activityInfo);
4871            }
4872        }
4873        return result;
4874    }
4875
4876    // Returns a packed value as a long:
4877    //
4878    // high 'int'-sized word: link status: undefined/ask/never/always.
4879    // low 'int'-sized word: relative priority among 'always' results.
4880    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4881        long result = ps.getDomainVerificationStatusForUser(userId);
4882        // if none available, get the master status
4883        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4884            if (ps.getIntentFilterVerificationInfo() != null) {
4885                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4886            }
4887        }
4888        return result;
4889    }
4890
4891    private ResolveInfo querySkipCurrentProfileIntents(
4892            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4893            int flags, int sourceUserId) {
4894        if (matchingFilters != null) {
4895            int size = matchingFilters.size();
4896            for (int i = 0; i < size; i ++) {
4897                CrossProfileIntentFilter filter = matchingFilters.get(i);
4898                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4899                    // Checking if there are activities in the target user that can handle the
4900                    // intent.
4901                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4902                            flags, sourceUserId);
4903                    if (resolveInfo != null) {
4904                        return resolveInfo;
4905                    }
4906                }
4907            }
4908        }
4909        return null;
4910    }
4911
4912    // Return matching ResolveInfo if any for skip current profile intent filters.
4913    private ResolveInfo queryCrossProfileIntents(
4914            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4915            int flags, int sourceUserId) {
4916        if (matchingFilters != null) {
4917            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4918            // match the same intent. For performance reasons, it is better not to
4919            // run queryIntent twice for the same userId
4920            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4921            int size = matchingFilters.size();
4922            for (int i = 0; i < size; i++) {
4923                CrossProfileIntentFilter filter = matchingFilters.get(i);
4924                int targetUserId = filter.getTargetUserId();
4925                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4926                        && !alreadyTriedUserIds.get(targetUserId)) {
4927                    // Checking if there are activities in the target user that can handle the
4928                    // intent.
4929                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4930                            flags, sourceUserId);
4931                    if (resolveInfo != null) return resolveInfo;
4932                    alreadyTriedUserIds.put(targetUserId, true);
4933                }
4934            }
4935        }
4936        return null;
4937    }
4938
4939    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4940            String resolvedType, int flags, int sourceUserId) {
4941        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4942                resolvedType, flags, filter.getTargetUserId());
4943        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4944            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4945        }
4946        return null;
4947    }
4948
4949    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4950            int sourceUserId, int targetUserId) {
4951        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4952        String className;
4953        if (targetUserId == UserHandle.USER_OWNER) {
4954            className = FORWARD_INTENT_TO_USER_OWNER;
4955        } else {
4956            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4957        }
4958        ComponentName forwardingActivityComponentName = new ComponentName(
4959                mAndroidApplication.packageName, className);
4960        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4961                sourceUserId);
4962        if (targetUserId == UserHandle.USER_OWNER) {
4963            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4964            forwardingResolveInfo.noResourceId = true;
4965        }
4966        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4967        forwardingResolveInfo.priority = 0;
4968        forwardingResolveInfo.preferredOrder = 0;
4969        forwardingResolveInfo.match = 0;
4970        forwardingResolveInfo.isDefault = true;
4971        forwardingResolveInfo.filter = filter;
4972        forwardingResolveInfo.targetUserId = targetUserId;
4973        return forwardingResolveInfo;
4974    }
4975
4976    @Override
4977    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4978            Intent[] specifics, String[] specificTypes, Intent intent,
4979            String resolvedType, int flags, int userId) {
4980        if (!sUserManager.exists(userId)) return Collections.emptyList();
4981        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4982                false, "query intent activity options");
4983        final String resultsAction = intent.getAction();
4984
4985        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4986                | PackageManager.GET_RESOLVED_FILTER, userId);
4987
4988        if (DEBUG_INTENT_MATCHING) {
4989            Log.v(TAG, "Query " + intent + ": " + results);
4990        }
4991
4992        int specificsPos = 0;
4993        int N;
4994
4995        // todo: note that the algorithm used here is O(N^2).  This
4996        // isn't a problem in our current environment, but if we start running
4997        // into situations where we have more than 5 or 10 matches then this
4998        // should probably be changed to something smarter...
4999
5000        // First we go through and resolve each of the specific items
5001        // that were supplied, taking care of removing any corresponding
5002        // duplicate items in the generic resolve list.
5003        if (specifics != null) {
5004            for (int i=0; i<specifics.length; i++) {
5005                final Intent sintent = specifics[i];
5006                if (sintent == null) {
5007                    continue;
5008                }
5009
5010                if (DEBUG_INTENT_MATCHING) {
5011                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5012                }
5013
5014                String action = sintent.getAction();
5015                if (resultsAction != null && resultsAction.equals(action)) {
5016                    // If this action was explicitly requested, then don't
5017                    // remove things that have it.
5018                    action = null;
5019                }
5020
5021                ResolveInfo ri = null;
5022                ActivityInfo ai = null;
5023
5024                ComponentName comp = sintent.getComponent();
5025                if (comp == null) {
5026                    ri = resolveIntent(
5027                        sintent,
5028                        specificTypes != null ? specificTypes[i] : null,
5029                            flags, userId);
5030                    if (ri == null) {
5031                        continue;
5032                    }
5033                    if (ri == mResolveInfo) {
5034                        // ACK!  Must do something better with this.
5035                    }
5036                    ai = ri.activityInfo;
5037                    comp = new ComponentName(ai.applicationInfo.packageName,
5038                            ai.name);
5039                } else {
5040                    ai = getActivityInfo(comp, flags, userId);
5041                    if (ai == null) {
5042                        continue;
5043                    }
5044                }
5045
5046                // Look for any generic query activities that are duplicates
5047                // of this specific one, and remove them from the results.
5048                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5049                N = results.size();
5050                int j;
5051                for (j=specificsPos; j<N; j++) {
5052                    ResolveInfo sri = results.get(j);
5053                    if ((sri.activityInfo.name.equals(comp.getClassName())
5054                            && sri.activityInfo.applicationInfo.packageName.equals(
5055                                    comp.getPackageName()))
5056                        || (action != null && sri.filter.matchAction(action))) {
5057                        results.remove(j);
5058                        if (DEBUG_INTENT_MATCHING) Log.v(
5059                            TAG, "Removing duplicate item from " + j
5060                            + " due to specific " + specificsPos);
5061                        if (ri == null) {
5062                            ri = sri;
5063                        }
5064                        j--;
5065                        N--;
5066                    }
5067                }
5068
5069                // Add this specific item to its proper place.
5070                if (ri == null) {
5071                    ri = new ResolveInfo();
5072                    ri.activityInfo = ai;
5073                }
5074                results.add(specificsPos, ri);
5075                ri.specificIndex = i;
5076                specificsPos++;
5077            }
5078        }
5079
5080        // Now we go through the remaining generic results and remove any
5081        // duplicate actions that are found here.
5082        N = results.size();
5083        for (int i=specificsPos; i<N-1; i++) {
5084            final ResolveInfo rii = results.get(i);
5085            if (rii.filter == null) {
5086                continue;
5087            }
5088
5089            // Iterate over all of the actions of this result's intent
5090            // filter...  typically this should be just one.
5091            final Iterator<String> it = rii.filter.actionsIterator();
5092            if (it == null) {
5093                continue;
5094            }
5095            while (it.hasNext()) {
5096                final String action = it.next();
5097                if (resultsAction != null && resultsAction.equals(action)) {
5098                    // If this action was explicitly requested, then don't
5099                    // remove things that have it.
5100                    continue;
5101                }
5102                for (int j=i+1; j<N; j++) {
5103                    final ResolveInfo rij = results.get(j);
5104                    if (rij.filter != null && rij.filter.hasAction(action)) {
5105                        results.remove(j);
5106                        if (DEBUG_INTENT_MATCHING) Log.v(
5107                            TAG, "Removing duplicate item from " + j
5108                            + " due to action " + action + " at " + i);
5109                        j--;
5110                        N--;
5111                    }
5112                }
5113            }
5114
5115            // If the caller didn't request filter information, drop it now
5116            // so we don't have to marshall/unmarshall it.
5117            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5118                rii.filter = null;
5119            }
5120        }
5121
5122        // Filter out the caller activity if so requested.
5123        if (caller != null) {
5124            N = results.size();
5125            for (int i=0; i<N; i++) {
5126                ActivityInfo ainfo = results.get(i).activityInfo;
5127                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5128                        && caller.getClassName().equals(ainfo.name)) {
5129                    results.remove(i);
5130                    break;
5131                }
5132            }
5133        }
5134
5135        // If the caller didn't request filter information,
5136        // drop them now so we don't have to
5137        // marshall/unmarshall it.
5138        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5139            N = results.size();
5140            for (int i=0; i<N; i++) {
5141                results.get(i).filter = null;
5142            }
5143        }
5144
5145        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5146        return results;
5147    }
5148
5149    @Override
5150    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5151            int userId) {
5152        if (!sUserManager.exists(userId)) return Collections.emptyList();
5153        ComponentName comp = intent.getComponent();
5154        if (comp == null) {
5155            if (intent.getSelector() != null) {
5156                intent = intent.getSelector();
5157                comp = intent.getComponent();
5158            }
5159        }
5160        if (comp != null) {
5161            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5162            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5163            if (ai != null) {
5164                ResolveInfo ri = new ResolveInfo();
5165                ri.activityInfo = ai;
5166                list.add(ri);
5167            }
5168            return list;
5169        }
5170
5171        // reader
5172        synchronized (mPackages) {
5173            String pkgName = intent.getPackage();
5174            if (pkgName == null) {
5175                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5176            }
5177            final PackageParser.Package pkg = mPackages.get(pkgName);
5178            if (pkg != null) {
5179                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5180                        userId);
5181            }
5182            return null;
5183        }
5184    }
5185
5186    @Override
5187    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5188        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5189        if (!sUserManager.exists(userId)) return null;
5190        if (query != null) {
5191            if (query.size() >= 1) {
5192                // If there is more than one service with the same priority,
5193                // just arbitrarily pick the first one.
5194                return query.get(0);
5195            }
5196        }
5197        return null;
5198    }
5199
5200    @Override
5201    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5202            int userId) {
5203        if (!sUserManager.exists(userId)) return Collections.emptyList();
5204        ComponentName comp = intent.getComponent();
5205        if (comp == null) {
5206            if (intent.getSelector() != null) {
5207                intent = intent.getSelector();
5208                comp = intent.getComponent();
5209            }
5210        }
5211        if (comp != null) {
5212            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5213            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5214            if (si != null) {
5215                final ResolveInfo ri = new ResolveInfo();
5216                ri.serviceInfo = si;
5217                list.add(ri);
5218            }
5219            return list;
5220        }
5221
5222        // reader
5223        synchronized (mPackages) {
5224            String pkgName = intent.getPackage();
5225            if (pkgName == null) {
5226                return mServices.queryIntent(intent, resolvedType, flags, userId);
5227            }
5228            final PackageParser.Package pkg = mPackages.get(pkgName);
5229            if (pkg != null) {
5230                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5231                        userId);
5232            }
5233            return null;
5234        }
5235    }
5236
5237    @Override
5238    public List<ResolveInfo> queryIntentContentProviders(
5239            Intent intent, String resolvedType, int flags, int userId) {
5240        if (!sUserManager.exists(userId)) return Collections.emptyList();
5241        ComponentName comp = intent.getComponent();
5242        if (comp == null) {
5243            if (intent.getSelector() != null) {
5244                intent = intent.getSelector();
5245                comp = intent.getComponent();
5246            }
5247        }
5248        if (comp != null) {
5249            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5250            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5251            if (pi != null) {
5252                final ResolveInfo ri = new ResolveInfo();
5253                ri.providerInfo = pi;
5254                list.add(ri);
5255            }
5256            return list;
5257        }
5258
5259        // reader
5260        synchronized (mPackages) {
5261            String pkgName = intent.getPackage();
5262            if (pkgName == null) {
5263                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5264            }
5265            final PackageParser.Package pkg = mPackages.get(pkgName);
5266            if (pkg != null) {
5267                return mProviders.queryIntentForPackage(
5268                        intent, resolvedType, flags, pkg.providers, userId);
5269            }
5270            return null;
5271        }
5272    }
5273
5274    @Override
5275    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5276        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5277
5278        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5279
5280        // writer
5281        synchronized (mPackages) {
5282            ArrayList<PackageInfo> list;
5283            if (listUninstalled) {
5284                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5285                for (PackageSetting ps : mSettings.mPackages.values()) {
5286                    PackageInfo pi;
5287                    if (ps.pkg != null) {
5288                        pi = generatePackageInfo(ps.pkg, flags, userId);
5289                    } else {
5290                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5291                    }
5292                    if (pi != null) {
5293                        list.add(pi);
5294                    }
5295                }
5296            } else {
5297                list = new ArrayList<PackageInfo>(mPackages.size());
5298                for (PackageParser.Package p : mPackages.values()) {
5299                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5300                    if (pi != null) {
5301                        list.add(pi);
5302                    }
5303                }
5304            }
5305
5306            return new ParceledListSlice<PackageInfo>(list);
5307        }
5308    }
5309
5310    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5311            String[] permissions, boolean[] tmp, int flags, int userId) {
5312        int numMatch = 0;
5313        final PermissionsState permissionsState = ps.getPermissionsState();
5314        for (int i=0; i<permissions.length; i++) {
5315            final String permission = permissions[i];
5316            if (permissionsState.hasPermission(permission, userId)) {
5317                tmp[i] = true;
5318                numMatch++;
5319            } else {
5320                tmp[i] = false;
5321            }
5322        }
5323        if (numMatch == 0) {
5324            return;
5325        }
5326        PackageInfo pi;
5327        if (ps.pkg != null) {
5328            pi = generatePackageInfo(ps.pkg, flags, userId);
5329        } else {
5330            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5331        }
5332        // The above might return null in cases of uninstalled apps or install-state
5333        // skew across users/profiles.
5334        if (pi != null) {
5335            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5336                if (numMatch == permissions.length) {
5337                    pi.requestedPermissions = permissions;
5338                } else {
5339                    pi.requestedPermissions = new String[numMatch];
5340                    numMatch = 0;
5341                    for (int i=0; i<permissions.length; i++) {
5342                        if (tmp[i]) {
5343                            pi.requestedPermissions[numMatch] = permissions[i];
5344                            numMatch++;
5345                        }
5346                    }
5347                }
5348            }
5349            list.add(pi);
5350        }
5351    }
5352
5353    @Override
5354    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5355            String[] permissions, int flags, int userId) {
5356        if (!sUserManager.exists(userId)) return null;
5357        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5358
5359        // writer
5360        synchronized (mPackages) {
5361            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5362            boolean[] tmpBools = new boolean[permissions.length];
5363            if (listUninstalled) {
5364                for (PackageSetting ps : mSettings.mPackages.values()) {
5365                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5366                }
5367            } else {
5368                for (PackageParser.Package pkg : mPackages.values()) {
5369                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5370                    if (ps != null) {
5371                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5372                                userId);
5373                    }
5374                }
5375            }
5376
5377            return new ParceledListSlice<PackageInfo>(list);
5378        }
5379    }
5380
5381    @Override
5382    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5383        if (!sUserManager.exists(userId)) return null;
5384        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5385
5386        // writer
5387        synchronized (mPackages) {
5388            ArrayList<ApplicationInfo> list;
5389            if (listUninstalled) {
5390                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5391                for (PackageSetting ps : mSettings.mPackages.values()) {
5392                    ApplicationInfo ai;
5393                    if (ps.pkg != null) {
5394                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5395                                ps.readUserState(userId), userId);
5396                    } else {
5397                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5398                    }
5399                    if (ai != null) {
5400                        list.add(ai);
5401                    }
5402                }
5403            } else {
5404                list = new ArrayList<ApplicationInfo>(mPackages.size());
5405                for (PackageParser.Package p : mPackages.values()) {
5406                    if (p.mExtras != null) {
5407                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5408                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5409                        if (ai != null) {
5410                            list.add(ai);
5411                        }
5412                    }
5413                }
5414            }
5415
5416            return new ParceledListSlice<ApplicationInfo>(list);
5417        }
5418    }
5419
5420    public List<ApplicationInfo> getPersistentApplications(int flags) {
5421        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5422
5423        // reader
5424        synchronized (mPackages) {
5425            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5426            final int userId = UserHandle.getCallingUserId();
5427            while (i.hasNext()) {
5428                final PackageParser.Package p = i.next();
5429                if (p.applicationInfo != null
5430                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5431                        && (!mSafeMode || isSystemApp(p))) {
5432                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5433                    if (ps != null) {
5434                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5435                                ps.readUserState(userId), userId);
5436                        if (ai != null) {
5437                            finalList.add(ai);
5438                        }
5439                    }
5440                }
5441            }
5442        }
5443
5444        return finalList;
5445    }
5446
5447    @Override
5448    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5449        if (!sUserManager.exists(userId)) return null;
5450        // reader
5451        synchronized (mPackages) {
5452            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5453            PackageSetting ps = provider != null
5454                    ? mSettings.mPackages.get(provider.owner.packageName)
5455                    : null;
5456            return ps != null
5457                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5458                    && (!mSafeMode || (provider.info.applicationInfo.flags
5459                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5460                    ? PackageParser.generateProviderInfo(provider, flags,
5461                            ps.readUserState(userId), userId)
5462                    : null;
5463        }
5464    }
5465
5466    /**
5467     * @deprecated
5468     */
5469    @Deprecated
5470    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5471        // reader
5472        synchronized (mPackages) {
5473            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5474                    .entrySet().iterator();
5475            final int userId = UserHandle.getCallingUserId();
5476            while (i.hasNext()) {
5477                Map.Entry<String, PackageParser.Provider> entry = i.next();
5478                PackageParser.Provider p = entry.getValue();
5479                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5480
5481                if (ps != null && p.syncable
5482                        && (!mSafeMode || (p.info.applicationInfo.flags
5483                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5484                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5485                            ps.readUserState(userId), userId);
5486                    if (info != null) {
5487                        outNames.add(entry.getKey());
5488                        outInfo.add(info);
5489                    }
5490                }
5491            }
5492        }
5493    }
5494
5495    @Override
5496    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5497            int uid, int flags) {
5498        ArrayList<ProviderInfo> finalList = null;
5499        // reader
5500        synchronized (mPackages) {
5501            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5502            final int userId = processName != null ?
5503                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5504            while (i.hasNext()) {
5505                final PackageParser.Provider p = i.next();
5506                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5507                if (ps != null && p.info.authority != null
5508                        && (processName == null
5509                                || (p.info.processName.equals(processName)
5510                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5511                        && mSettings.isEnabledLPr(p.info, flags, userId)
5512                        && (!mSafeMode
5513                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5514                    if (finalList == null) {
5515                        finalList = new ArrayList<ProviderInfo>(3);
5516                    }
5517                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5518                            ps.readUserState(userId), userId);
5519                    if (info != null) {
5520                        finalList.add(info);
5521                    }
5522                }
5523            }
5524        }
5525
5526        if (finalList != null) {
5527            Collections.sort(finalList, mProviderInitOrderSorter);
5528            return new ParceledListSlice<ProviderInfo>(finalList);
5529        }
5530
5531        return null;
5532    }
5533
5534    @Override
5535    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5536            int flags) {
5537        // reader
5538        synchronized (mPackages) {
5539            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5540            return PackageParser.generateInstrumentationInfo(i, flags);
5541        }
5542    }
5543
5544    @Override
5545    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5546            int flags) {
5547        ArrayList<InstrumentationInfo> finalList =
5548            new ArrayList<InstrumentationInfo>();
5549
5550        // reader
5551        synchronized (mPackages) {
5552            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5553            while (i.hasNext()) {
5554                final PackageParser.Instrumentation p = i.next();
5555                if (targetPackage == null
5556                        || targetPackage.equals(p.info.targetPackage)) {
5557                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5558                            flags);
5559                    if (ii != null) {
5560                        finalList.add(ii);
5561                    }
5562                }
5563            }
5564        }
5565
5566        return finalList;
5567    }
5568
5569    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5570        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5571        if (overlays == null) {
5572            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5573            return;
5574        }
5575        for (PackageParser.Package opkg : overlays.values()) {
5576            // Not much to do if idmap fails: we already logged the error
5577            // and we certainly don't want to abort installation of pkg simply
5578            // because an overlay didn't fit properly. For these reasons,
5579            // ignore the return value of createIdmapForPackagePairLI.
5580            createIdmapForPackagePairLI(pkg, opkg);
5581        }
5582    }
5583
5584    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5585            PackageParser.Package opkg) {
5586        if (!opkg.mTrustedOverlay) {
5587            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5588                    opkg.baseCodePath + ": overlay not trusted");
5589            return false;
5590        }
5591        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5592        if (overlaySet == null) {
5593            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5594                    opkg.baseCodePath + " but target package has no known overlays");
5595            return false;
5596        }
5597        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5598        // TODO: generate idmap for split APKs
5599        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5600            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5601                    + opkg.baseCodePath);
5602            return false;
5603        }
5604        PackageParser.Package[] overlayArray =
5605            overlaySet.values().toArray(new PackageParser.Package[0]);
5606        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5607            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5608                return p1.mOverlayPriority - p2.mOverlayPriority;
5609            }
5610        };
5611        Arrays.sort(overlayArray, cmp);
5612
5613        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5614        int i = 0;
5615        for (PackageParser.Package p : overlayArray) {
5616            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5617        }
5618        return true;
5619    }
5620
5621    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5622        final File[] files = dir.listFiles();
5623        if (ArrayUtils.isEmpty(files)) {
5624            Log.d(TAG, "No files in app dir " + dir);
5625            return;
5626        }
5627
5628        if (DEBUG_PACKAGE_SCANNING) {
5629            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5630                    + " flags=0x" + Integer.toHexString(parseFlags));
5631        }
5632
5633        for (File file : files) {
5634            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5635                    && !PackageInstallerService.isStageName(file.getName());
5636            if (!isPackage) {
5637                // Ignore entries which are not packages
5638                continue;
5639            }
5640            try {
5641                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5642                        scanFlags, currentTime, null);
5643            } catch (PackageManagerException e) {
5644                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5645
5646                // Delete invalid userdata apps
5647                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5648                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5649                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5650                    if (file.isDirectory()) {
5651                        mInstaller.rmPackageDir(file.getAbsolutePath());
5652                    } else {
5653                        file.delete();
5654                    }
5655                }
5656            }
5657        }
5658    }
5659
5660    private static File getSettingsProblemFile() {
5661        File dataDir = Environment.getDataDirectory();
5662        File systemDir = new File(dataDir, "system");
5663        File fname = new File(systemDir, "uiderrors.txt");
5664        return fname;
5665    }
5666
5667    static void reportSettingsProblem(int priority, String msg) {
5668        logCriticalInfo(priority, msg);
5669    }
5670
5671    static void logCriticalInfo(int priority, String msg) {
5672        Slog.println(priority, TAG, msg);
5673        EventLogTags.writePmCriticalInfo(msg);
5674        try {
5675            File fname = getSettingsProblemFile();
5676            FileOutputStream out = new FileOutputStream(fname, true);
5677            PrintWriter pw = new FastPrintWriter(out);
5678            SimpleDateFormat formatter = new SimpleDateFormat();
5679            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5680            pw.println(dateString + ": " + msg);
5681            pw.close();
5682            FileUtils.setPermissions(
5683                    fname.toString(),
5684                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5685                    -1, -1);
5686        } catch (java.io.IOException e) {
5687        }
5688    }
5689
5690    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5691            PackageParser.Package pkg, File srcFile, int parseFlags)
5692            throws PackageManagerException {
5693        if (ps != null
5694                && ps.codePath.equals(srcFile)
5695                && ps.timeStamp == srcFile.lastModified()
5696                && !isCompatSignatureUpdateNeeded(pkg)
5697                && !isRecoverSignatureUpdateNeeded(pkg)) {
5698            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5699            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5700            ArraySet<PublicKey> signingKs;
5701            synchronized (mPackages) {
5702                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5703            }
5704            if (ps.signatures.mSignatures != null
5705                    && ps.signatures.mSignatures.length != 0
5706                    && signingKs != null) {
5707                // Optimization: reuse the existing cached certificates
5708                // if the package appears to be unchanged.
5709                pkg.mSignatures = ps.signatures.mSignatures;
5710                pkg.mSigningKeys = signingKs;
5711                return;
5712            }
5713
5714            Slog.w(TAG, "PackageSetting for " + ps.name
5715                    + " is missing signatures.  Collecting certs again to recover them.");
5716        } else {
5717            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5718        }
5719
5720        try {
5721            pp.collectCertificates(pkg, parseFlags);
5722            pp.collectManifestDigest(pkg);
5723        } catch (PackageParserException e) {
5724            throw PackageManagerException.from(e);
5725        }
5726    }
5727
5728    /*
5729     *  Scan a package and return the newly parsed package.
5730     *  Returns null in case of errors and the error code is stored in mLastScanError
5731     */
5732    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5733            long currentTime, UserHandle user) throws PackageManagerException {
5734        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5735        parseFlags |= mDefParseFlags;
5736        PackageParser pp = new PackageParser();
5737        pp.setSeparateProcesses(mSeparateProcesses);
5738        pp.setOnlyCoreApps(mOnlyCore);
5739        pp.setDisplayMetrics(mMetrics);
5740
5741        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5742            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5743        }
5744
5745        final PackageParser.Package pkg;
5746        try {
5747            pkg = pp.parsePackage(scanFile, parseFlags);
5748        } catch (PackageParserException e) {
5749            throw PackageManagerException.from(e);
5750        }
5751
5752        PackageSetting ps = null;
5753        PackageSetting updatedPkg;
5754        // reader
5755        synchronized (mPackages) {
5756            // Look to see if we already know about this package.
5757            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5758            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5759                // This package has been renamed to its original name.  Let's
5760                // use that.
5761                ps = mSettings.peekPackageLPr(oldName);
5762            }
5763            // If there was no original package, see one for the real package name.
5764            if (ps == null) {
5765                ps = mSettings.peekPackageLPr(pkg.packageName);
5766            }
5767            // Check to see if this package could be hiding/updating a system
5768            // package.  Must look for it either under the original or real
5769            // package name depending on our state.
5770            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5771            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5772        }
5773        boolean updatedPkgBetter = false;
5774        // First check if this is a system package that may involve an update
5775        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5776            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5777            // it needs to drop FLAG_PRIVILEGED.
5778            if (locationIsPrivileged(scanFile)) {
5779                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5780            } else {
5781                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5782            }
5783
5784            if (ps != null && !ps.codePath.equals(scanFile)) {
5785                // The path has changed from what was last scanned...  check the
5786                // version of the new path against what we have stored to determine
5787                // what to do.
5788                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5789                if (pkg.mVersionCode <= ps.versionCode) {
5790                    // The system package has been updated and the code path does not match
5791                    // Ignore entry. Skip it.
5792                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5793                            + " ignored: updated version " + ps.versionCode
5794                            + " better than this " + pkg.mVersionCode);
5795                    if (!updatedPkg.codePath.equals(scanFile)) {
5796                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5797                                + ps.name + " changing from " + updatedPkg.codePathString
5798                                + " to " + scanFile);
5799                        updatedPkg.codePath = scanFile;
5800                        updatedPkg.codePathString = scanFile.toString();
5801                        updatedPkg.resourcePath = scanFile;
5802                        updatedPkg.resourcePathString = scanFile.toString();
5803                    }
5804                    updatedPkg.pkg = pkg;
5805                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5806                            "Package " + ps.name + " at " + scanFile
5807                                    + " ignored: updated version " + ps.versionCode
5808                                    + " better than this " + pkg.mVersionCode);
5809                } else {
5810                    // The current app on the system partition is better than
5811                    // what we have updated to on the data partition; switch
5812                    // back to the system partition version.
5813                    // At this point, its safely assumed that package installation for
5814                    // apps in system partition will go through. If not there won't be a working
5815                    // version of the app
5816                    // writer
5817                    synchronized (mPackages) {
5818                        // Just remove the loaded entries from package lists.
5819                        mPackages.remove(ps.name);
5820                    }
5821
5822                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5823                            + " reverting from " + ps.codePathString
5824                            + ": new version " + pkg.mVersionCode
5825                            + " better than installed " + ps.versionCode);
5826
5827                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5828                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5829                    synchronized (mInstallLock) {
5830                        args.cleanUpResourcesLI();
5831                    }
5832                    synchronized (mPackages) {
5833                        mSettings.enableSystemPackageLPw(ps.name);
5834                    }
5835                    updatedPkgBetter = true;
5836                }
5837            }
5838        }
5839
5840        if (updatedPkg != null) {
5841            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5842            // initially
5843            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5844
5845            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5846            // flag set initially
5847            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5848                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5849            }
5850        }
5851
5852        // Verify certificates against what was last scanned
5853        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5854
5855        /*
5856         * A new system app appeared, but we already had a non-system one of the
5857         * same name installed earlier.
5858         */
5859        boolean shouldHideSystemApp = false;
5860        if (updatedPkg == null && ps != null
5861                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5862            /*
5863             * Check to make sure the signatures match first. If they don't,
5864             * wipe the installed application and its data.
5865             */
5866            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5867                    != PackageManager.SIGNATURE_MATCH) {
5868                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5869                        + " signatures don't match existing userdata copy; removing");
5870                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5871                ps = null;
5872            } else {
5873                /*
5874                 * If the newly-added system app is an older version than the
5875                 * already installed version, hide it. It will be scanned later
5876                 * and re-added like an update.
5877                 */
5878                if (pkg.mVersionCode <= ps.versionCode) {
5879                    shouldHideSystemApp = true;
5880                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5881                            + " but new version " + pkg.mVersionCode + " better than installed "
5882                            + ps.versionCode + "; hiding system");
5883                } else {
5884                    /*
5885                     * The newly found system app is a newer version that the
5886                     * one previously installed. Simply remove the
5887                     * already-installed application and replace it with our own
5888                     * while keeping the application data.
5889                     */
5890                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5891                            + " reverting from " + ps.codePathString + ": new version "
5892                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5893                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5894                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5895                    synchronized (mInstallLock) {
5896                        args.cleanUpResourcesLI();
5897                    }
5898                }
5899            }
5900        }
5901
5902        // The apk is forward locked (not public) if its code and resources
5903        // are kept in different files. (except for app in either system or
5904        // vendor path).
5905        // TODO grab this value from PackageSettings
5906        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5907            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5908                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5909            }
5910        }
5911
5912        // TODO: extend to support forward-locked splits
5913        String resourcePath = null;
5914        String baseResourcePath = null;
5915        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5916            if (ps != null && ps.resourcePathString != null) {
5917                resourcePath = ps.resourcePathString;
5918                baseResourcePath = ps.resourcePathString;
5919            } else {
5920                // Should not happen at all. Just log an error.
5921                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5922            }
5923        } else {
5924            resourcePath = pkg.codePath;
5925            baseResourcePath = pkg.baseCodePath;
5926        }
5927
5928        // Set application objects path explicitly.
5929        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5930        pkg.applicationInfo.setCodePath(pkg.codePath);
5931        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5932        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5933        pkg.applicationInfo.setResourcePath(resourcePath);
5934        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5935        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5936
5937        // Note that we invoke the following method only if we are about to unpack an application
5938        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5939                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5940
5941        /*
5942         * If the system app should be overridden by a previously installed
5943         * data, hide the system app now and let the /data/app scan pick it up
5944         * again.
5945         */
5946        if (shouldHideSystemApp) {
5947            synchronized (mPackages) {
5948                mSettings.disableSystemPackageLPw(pkg.packageName);
5949            }
5950        }
5951
5952        return scannedPkg;
5953    }
5954
5955    private static String fixProcessName(String defProcessName,
5956            String processName, int uid) {
5957        if (processName == null) {
5958            return defProcessName;
5959        }
5960        return processName;
5961    }
5962
5963    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5964            throws PackageManagerException {
5965        if (pkgSetting.signatures.mSignatures != null) {
5966            // Already existing package. Make sure signatures match
5967            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5968                    == PackageManager.SIGNATURE_MATCH;
5969            if (!match) {
5970                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5971                        == PackageManager.SIGNATURE_MATCH;
5972            }
5973            if (!match) {
5974                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5975                        == PackageManager.SIGNATURE_MATCH;
5976            }
5977            if (!match) {
5978                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5979                        + pkg.packageName + " signatures do not match the "
5980                        + "previously installed version; ignoring!");
5981            }
5982        }
5983
5984        // Check for shared user signatures
5985        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5986            // Already existing package. Make sure signatures match
5987            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5988                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5989            if (!match) {
5990                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5991                        == PackageManager.SIGNATURE_MATCH;
5992            }
5993            if (!match) {
5994                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5995                        == PackageManager.SIGNATURE_MATCH;
5996            }
5997            if (!match) {
5998                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5999                        "Package " + pkg.packageName
6000                        + " has no signatures that match those in shared user "
6001                        + pkgSetting.sharedUser.name + "; ignoring!");
6002            }
6003        }
6004    }
6005
6006    /**
6007     * Enforces that only the system UID or root's UID can call a method exposed
6008     * via Binder.
6009     *
6010     * @param message used as message if SecurityException is thrown
6011     * @throws SecurityException if the caller is not system or root
6012     */
6013    private static final void enforceSystemOrRoot(String message) {
6014        final int uid = Binder.getCallingUid();
6015        if (uid != Process.SYSTEM_UID && uid != 0) {
6016            throw new SecurityException(message);
6017        }
6018    }
6019
6020    @Override
6021    public void performBootDexOpt() {
6022        enforceSystemOrRoot("Only the system can request dexopt be performed");
6023
6024        // Before everything else, see whether we need to fstrim.
6025        try {
6026            IMountService ms = PackageHelper.getMountService();
6027            if (ms != null) {
6028                final boolean isUpgrade = isUpgrade();
6029                boolean doTrim = isUpgrade;
6030                if (doTrim) {
6031                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6032                } else {
6033                    final long interval = android.provider.Settings.Global.getLong(
6034                            mContext.getContentResolver(),
6035                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6036                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6037                    if (interval > 0) {
6038                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6039                        if (timeSinceLast > interval) {
6040                            doTrim = true;
6041                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6042                                    + "; running immediately");
6043                        }
6044                    }
6045                }
6046                if (doTrim) {
6047                    if (!isFirstBoot()) {
6048                        try {
6049                            ActivityManagerNative.getDefault().showBootMessage(
6050                                    mContext.getResources().getString(
6051                                            R.string.android_upgrading_fstrim), true);
6052                        } catch (RemoteException e) {
6053                        }
6054                    }
6055                    ms.runMaintenance();
6056                }
6057            } else {
6058                Slog.e(TAG, "Mount service unavailable!");
6059            }
6060        } catch (RemoteException e) {
6061            // Can't happen; MountService is local
6062        }
6063
6064        final ArraySet<PackageParser.Package> pkgs;
6065        synchronized (mPackages) {
6066            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6067        }
6068
6069        if (pkgs != null) {
6070            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6071            // in case the device runs out of space.
6072            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6073            // Give priority to core apps.
6074            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6075                PackageParser.Package pkg = it.next();
6076                if (pkg.coreApp) {
6077                    if (DEBUG_DEXOPT) {
6078                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6079                    }
6080                    sortedPkgs.add(pkg);
6081                    it.remove();
6082                }
6083            }
6084            // Give priority to system apps that listen for pre boot complete.
6085            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6086            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
6087            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6088                PackageParser.Package pkg = it.next();
6089                if (pkgNames.contains(pkg.packageName)) {
6090                    if (DEBUG_DEXOPT) {
6091                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6092                    }
6093                    sortedPkgs.add(pkg);
6094                    it.remove();
6095                }
6096            }
6097            // Filter out packages that aren't recently used.
6098            filterRecentlyUsedApps(pkgs);
6099            // Add all remaining apps.
6100            for (PackageParser.Package pkg : pkgs) {
6101                if (DEBUG_DEXOPT) {
6102                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6103                }
6104                sortedPkgs.add(pkg);
6105            }
6106
6107            // If we want to be lazy, filter everything that wasn't recently used.
6108            if (mLazyDexOpt) {
6109                filterRecentlyUsedApps(sortedPkgs);
6110            }
6111
6112            int i = 0;
6113            int total = sortedPkgs.size();
6114            File dataDir = Environment.getDataDirectory();
6115            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6116            if (lowThreshold == 0) {
6117                throw new IllegalStateException("Invalid low memory threshold");
6118            }
6119            for (PackageParser.Package pkg : sortedPkgs) {
6120                long usableSpace = dataDir.getUsableSpace();
6121                if (usableSpace < lowThreshold) {
6122                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6123                    break;
6124                }
6125                performBootDexOpt(pkg, ++i, total);
6126            }
6127        }
6128    }
6129
6130    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6131        // Filter out packages that aren't recently used.
6132        //
6133        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6134        // should do a full dexopt.
6135        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6136            int total = pkgs.size();
6137            int skipped = 0;
6138            long now = System.currentTimeMillis();
6139            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6140                PackageParser.Package pkg = i.next();
6141                long then = pkg.mLastPackageUsageTimeInMills;
6142                if (then + mDexOptLRUThresholdInMills < now) {
6143                    if (DEBUG_DEXOPT) {
6144                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6145                              ((then == 0) ? "never" : new Date(then)));
6146                    }
6147                    i.remove();
6148                    skipped++;
6149                }
6150            }
6151            if (DEBUG_DEXOPT) {
6152                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6153            }
6154        }
6155    }
6156
6157    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
6158        List<ResolveInfo> ris = null;
6159        try {
6160            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6161                    intent, null, 0, UserHandle.USER_OWNER);
6162        } catch (RemoteException e) {
6163        }
6164        ArraySet<String> pkgNames = new ArraySet<String>();
6165        if (ris != null) {
6166            for (ResolveInfo ri : ris) {
6167                pkgNames.add(ri.activityInfo.packageName);
6168            }
6169        }
6170        return pkgNames;
6171    }
6172
6173    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6174        if (DEBUG_DEXOPT) {
6175            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6176        }
6177        if (!isFirstBoot()) {
6178            try {
6179                ActivityManagerNative.getDefault().showBootMessage(
6180                        mContext.getResources().getString(R.string.android_upgrading_apk,
6181                                curr, total), true);
6182            } catch (RemoteException e) {
6183            }
6184        }
6185        PackageParser.Package p = pkg;
6186        synchronized (mInstallLock) {
6187            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6188                    false /* force dex */, false /* defer */, true /* include dependencies */,
6189                    false /* boot complete */, false /*useJit*/);
6190        }
6191    }
6192
6193    @Override
6194    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6195        return performDexOpt(packageName, instructionSet, false);
6196    }
6197
6198    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
6199        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6200        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6201        if (!dexopt && !updateUsage) {
6202            // We aren't going to dexopt or update usage, so bail early.
6203            return false;
6204        }
6205        PackageParser.Package p;
6206        final String targetInstructionSet;
6207        synchronized (mPackages) {
6208            p = mPackages.get(packageName);
6209            if (p == null) {
6210                return false;
6211            }
6212            if (updateUsage) {
6213                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6214            }
6215            mPackageUsage.write(false);
6216            if (!dexopt) {
6217                // We aren't going to dexopt, so bail early.
6218                return false;
6219            }
6220
6221            targetInstructionSet = instructionSet != null ? instructionSet :
6222                    getPrimaryInstructionSet(p.applicationInfo);
6223            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6224                return false;
6225            }
6226        }
6227        long callingId = Binder.clearCallingIdentity();
6228        try {
6229            synchronized (mInstallLock) {
6230                final String[] instructionSets = new String[] { targetInstructionSet };
6231                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6232                        false /* forceDex */, false /* defer */, true /* inclDependencies */,
6233                        true /* boot complete */, false /*useJit*/);
6234                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6235            }
6236        } finally {
6237            Binder.restoreCallingIdentity(callingId);
6238        }
6239    }
6240
6241    public ArraySet<String> getPackagesThatNeedDexOpt() {
6242        ArraySet<String> pkgs = null;
6243        synchronized (mPackages) {
6244            for (PackageParser.Package p : mPackages.values()) {
6245                if (DEBUG_DEXOPT) {
6246                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6247                }
6248                if (!p.mDexOptPerformed.isEmpty()) {
6249                    continue;
6250                }
6251                if (pkgs == null) {
6252                    pkgs = new ArraySet<String>();
6253                }
6254                pkgs.add(p.packageName);
6255            }
6256        }
6257        return pkgs;
6258    }
6259
6260    public void shutdown() {
6261        mPackageUsage.write(true);
6262    }
6263
6264    @Override
6265    public void forceDexOpt(String packageName) {
6266        enforceSystemOrRoot("forceDexOpt");
6267
6268        PackageParser.Package pkg;
6269        synchronized (mPackages) {
6270            pkg = mPackages.get(packageName);
6271            if (pkg == null) {
6272                throw new IllegalArgumentException("Missing package: " + packageName);
6273            }
6274        }
6275
6276        synchronized (mInstallLock) {
6277            final String[] instructionSets = new String[] {
6278                    getPrimaryInstructionSet(pkg.applicationInfo) };
6279            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6280                    true /*forceDex*/, false /* defer */, true /* inclDependencies */,
6281                    true /* boot complete */, false /*useJit*/);
6282            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6283                throw new IllegalStateException("Failed to dexopt: " + res);
6284            }
6285        }
6286    }
6287
6288    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6289        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6290            Slog.w(TAG, "Unable to update from " + oldPkg.name
6291                    + " to " + newPkg.packageName
6292                    + ": old package not in system partition");
6293            return false;
6294        } else if (mPackages.get(oldPkg.name) != null) {
6295            Slog.w(TAG, "Unable to update from " + oldPkg.name
6296                    + " to " + newPkg.packageName
6297                    + ": old package still exists");
6298            return false;
6299        }
6300        return true;
6301    }
6302
6303    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6304        int[] users = sUserManager.getUserIds();
6305        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6306        if (res < 0) {
6307            return res;
6308        }
6309        for (int user : users) {
6310            if (user != 0) {
6311                res = mInstaller.createUserData(volumeUuid, packageName,
6312                        UserHandle.getUid(user, uid), user, seinfo);
6313                if (res < 0) {
6314                    return res;
6315                }
6316            }
6317        }
6318        return res;
6319    }
6320
6321    private int removeDataDirsLI(String volumeUuid, String packageName) {
6322        int[] users = sUserManager.getUserIds();
6323        int res = 0;
6324        for (int user : users) {
6325            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6326            if (resInner < 0) {
6327                res = resInner;
6328            }
6329        }
6330
6331        return res;
6332    }
6333
6334    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6335        int[] users = sUserManager.getUserIds();
6336        int res = 0;
6337        for (int user : users) {
6338            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6339            if (resInner < 0) {
6340                res = resInner;
6341            }
6342        }
6343        return res;
6344    }
6345
6346    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6347            PackageParser.Package changingLib) {
6348        if (file.path != null) {
6349            usesLibraryFiles.add(file.path);
6350            return;
6351        }
6352        PackageParser.Package p = mPackages.get(file.apk);
6353        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6354            // If we are doing this while in the middle of updating a library apk,
6355            // then we need to make sure to use that new apk for determining the
6356            // dependencies here.  (We haven't yet finished committing the new apk
6357            // to the package manager state.)
6358            if (p == null || p.packageName.equals(changingLib.packageName)) {
6359                p = changingLib;
6360            }
6361        }
6362        if (p != null) {
6363            usesLibraryFiles.addAll(p.getAllCodePaths());
6364        }
6365    }
6366
6367    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6368            PackageParser.Package changingLib) throws PackageManagerException {
6369        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6370            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6371            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6372            for (int i=0; i<N; i++) {
6373                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6374                if (file == null) {
6375                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6376                            "Package " + pkg.packageName + " requires unavailable shared library "
6377                            + pkg.usesLibraries.get(i) + "; failing!");
6378                }
6379                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6380            }
6381            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6382            for (int i=0; i<N; i++) {
6383                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6384                if (file == null) {
6385                    Slog.w(TAG, "Package " + pkg.packageName
6386                            + " desires unavailable shared library "
6387                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6388                } else {
6389                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6390                }
6391            }
6392            N = usesLibraryFiles.size();
6393            if (N > 0) {
6394                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6395            } else {
6396                pkg.usesLibraryFiles = null;
6397            }
6398        }
6399    }
6400
6401    private static boolean hasString(List<String> list, List<String> which) {
6402        if (list == null) {
6403            return false;
6404        }
6405        for (int i=list.size()-1; i>=0; i--) {
6406            for (int j=which.size()-1; j>=0; j--) {
6407                if (which.get(j).equals(list.get(i))) {
6408                    return true;
6409                }
6410            }
6411        }
6412        return false;
6413    }
6414
6415    private void updateAllSharedLibrariesLPw() {
6416        for (PackageParser.Package pkg : mPackages.values()) {
6417            try {
6418                updateSharedLibrariesLPw(pkg, null);
6419            } catch (PackageManagerException e) {
6420                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6421            }
6422        }
6423    }
6424
6425    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6426            PackageParser.Package changingPkg) {
6427        ArrayList<PackageParser.Package> res = null;
6428        for (PackageParser.Package pkg : mPackages.values()) {
6429            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6430                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6431                if (res == null) {
6432                    res = new ArrayList<PackageParser.Package>();
6433                }
6434                res.add(pkg);
6435                try {
6436                    updateSharedLibrariesLPw(pkg, changingPkg);
6437                } catch (PackageManagerException e) {
6438                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6439                }
6440            }
6441        }
6442        return res;
6443    }
6444
6445    /**
6446     * Derive the value of the {@code cpuAbiOverride} based on the provided
6447     * value and an optional stored value from the package settings.
6448     */
6449    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6450        String cpuAbiOverride = null;
6451
6452        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6453            cpuAbiOverride = null;
6454        } else if (abiOverride != null) {
6455            cpuAbiOverride = abiOverride;
6456        } else if (settings != null) {
6457            cpuAbiOverride = settings.cpuAbiOverrideString;
6458        }
6459
6460        return cpuAbiOverride;
6461    }
6462
6463    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6464            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6465        boolean success = false;
6466        try {
6467            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6468                    currentTime, user);
6469            success = true;
6470            return res;
6471        } finally {
6472            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6473                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6474            }
6475        }
6476    }
6477
6478    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6479            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6480        final File scanFile = new File(pkg.codePath);
6481        if (pkg.applicationInfo.getCodePath() == null ||
6482                pkg.applicationInfo.getResourcePath() == null) {
6483            // Bail out. The resource and code paths haven't been set.
6484            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6485                    "Code and resource paths haven't been set correctly");
6486        }
6487
6488        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6489            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6490        } else {
6491            // Only allow system apps to be flagged as core apps.
6492            pkg.coreApp = false;
6493        }
6494
6495        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6496            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6497        }
6498
6499        if (mCustomResolverComponentName != null &&
6500                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6501            setUpCustomResolverActivity(pkg);
6502        }
6503
6504        if (pkg.packageName.equals("android")) {
6505            synchronized (mPackages) {
6506                if (mAndroidApplication != null) {
6507                    Slog.w(TAG, "*************************************************");
6508                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6509                    Slog.w(TAG, " file=" + scanFile);
6510                    Slog.w(TAG, "*************************************************");
6511                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6512                            "Core android package being redefined.  Skipping.");
6513                }
6514
6515                // Set up information for our fall-back user intent resolution activity.
6516                mPlatformPackage = pkg;
6517                pkg.mVersionCode = mSdkVersion;
6518                mAndroidApplication = pkg.applicationInfo;
6519
6520                if (!mResolverReplaced) {
6521                    mResolveActivity.applicationInfo = mAndroidApplication;
6522                    mResolveActivity.name = ResolverActivity.class.getName();
6523                    mResolveActivity.packageName = mAndroidApplication.packageName;
6524                    mResolveActivity.processName = "system:ui";
6525                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6526                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6527                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6528                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6529                    mResolveActivity.exported = true;
6530                    mResolveActivity.enabled = true;
6531                    mResolveInfo.activityInfo = mResolveActivity;
6532                    mResolveInfo.priority = 0;
6533                    mResolveInfo.preferredOrder = 0;
6534                    mResolveInfo.match = 0;
6535                    mResolveComponentName = new ComponentName(
6536                            mAndroidApplication.packageName, mResolveActivity.name);
6537                }
6538            }
6539        }
6540
6541        if (DEBUG_PACKAGE_SCANNING) {
6542            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6543                Log.d(TAG, "Scanning package " + pkg.packageName);
6544        }
6545
6546        if (mPackages.containsKey(pkg.packageName)
6547                || mSharedLibraries.containsKey(pkg.packageName)) {
6548            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6549                    "Application package " + pkg.packageName
6550                    + " already installed.  Skipping duplicate.");
6551        }
6552
6553        // If we're only installing presumed-existing packages, require that the
6554        // scanned APK is both already known and at the path previously established
6555        // for it.  Previously unknown packages we pick up normally, but if we have an
6556        // a priori expectation about this package's install presence, enforce it.
6557        // With a singular exception for new system packages. When an OTA contains
6558        // a new system package, we allow the codepath to change from a system location
6559        // to the user-installed location. If we don't allow this change, any newer,
6560        // user-installed version of the application will be ignored.
6561        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6562            if (mExpectingBetter.containsKey(pkg.packageName)) {
6563                logCriticalInfo(Log.WARN,
6564                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6565            } else {
6566                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6567                if (known != null) {
6568                    if (DEBUG_PACKAGE_SCANNING) {
6569                        Log.d(TAG, "Examining " + pkg.codePath
6570                                + " and requiring known paths " + known.codePathString
6571                                + " & " + known.resourcePathString);
6572                    }
6573                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6574                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6575                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6576                                "Application package " + pkg.packageName
6577                                + " found at " + pkg.applicationInfo.getCodePath()
6578                                + " but expected at " + known.codePathString + "; ignoring.");
6579                    }
6580                }
6581            }
6582        }
6583
6584        // Initialize package source and resource directories
6585        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6586        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6587
6588        SharedUserSetting suid = null;
6589        PackageSetting pkgSetting = null;
6590
6591        if (!isSystemApp(pkg)) {
6592            // Only system apps can use these features.
6593            pkg.mOriginalPackages = null;
6594            pkg.mRealPackage = null;
6595            pkg.mAdoptPermissions = null;
6596        }
6597
6598        // writer
6599        synchronized (mPackages) {
6600            if (pkg.mSharedUserId != null) {
6601                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6602                if (suid == null) {
6603                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6604                            "Creating application package " + pkg.packageName
6605                            + " for shared user failed");
6606                }
6607                if (DEBUG_PACKAGE_SCANNING) {
6608                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6609                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6610                                + "): packages=" + suid.packages);
6611                }
6612            }
6613
6614            // Check if we are renaming from an original package name.
6615            PackageSetting origPackage = null;
6616            String realName = null;
6617            if (pkg.mOriginalPackages != null) {
6618                // This package may need to be renamed to a previously
6619                // installed name.  Let's check on that...
6620                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6621                if (pkg.mOriginalPackages.contains(renamed)) {
6622                    // This package had originally been installed as the
6623                    // original name, and we have already taken care of
6624                    // transitioning to the new one.  Just update the new
6625                    // one to continue using the old name.
6626                    realName = pkg.mRealPackage;
6627                    if (!pkg.packageName.equals(renamed)) {
6628                        // Callers into this function may have already taken
6629                        // care of renaming the package; only do it here if
6630                        // it is not already done.
6631                        pkg.setPackageName(renamed);
6632                    }
6633
6634                } else {
6635                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6636                        if ((origPackage = mSettings.peekPackageLPr(
6637                                pkg.mOriginalPackages.get(i))) != null) {
6638                            // We do have the package already installed under its
6639                            // original name...  should we use it?
6640                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6641                                // New package is not compatible with original.
6642                                origPackage = null;
6643                                continue;
6644                            } else if (origPackage.sharedUser != null) {
6645                                // Make sure uid is compatible between packages.
6646                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6647                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6648                                            + " to " + pkg.packageName + ": old uid "
6649                                            + origPackage.sharedUser.name
6650                                            + " differs from " + pkg.mSharedUserId);
6651                                    origPackage = null;
6652                                    continue;
6653                                }
6654                            } else {
6655                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6656                                        + pkg.packageName + " to old name " + origPackage.name);
6657                            }
6658                            break;
6659                        }
6660                    }
6661                }
6662            }
6663
6664            if (mTransferedPackages.contains(pkg.packageName)) {
6665                Slog.w(TAG, "Package " + pkg.packageName
6666                        + " was transferred to another, but its .apk remains");
6667            }
6668
6669            // Just create the setting, don't add it yet. For already existing packages
6670            // the PkgSetting exists already and doesn't have to be created.
6671            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6672                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6673                    pkg.applicationInfo.primaryCpuAbi,
6674                    pkg.applicationInfo.secondaryCpuAbi,
6675                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6676                    user, false);
6677            if (pkgSetting == null) {
6678                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6679                        "Creating application package " + pkg.packageName + " failed");
6680            }
6681
6682            if (pkgSetting.origPackage != null) {
6683                // If we are first transitioning from an original package,
6684                // fix up the new package's name now.  We need to do this after
6685                // looking up the package under its new name, so getPackageLP
6686                // can take care of fiddling things correctly.
6687                pkg.setPackageName(origPackage.name);
6688
6689                // File a report about this.
6690                String msg = "New package " + pkgSetting.realName
6691                        + " renamed to replace old package " + pkgSetting.name;
6692                reportSettingsProblem(Log.WARN, msg);
6693
6694                // Make a note of it.
6695                mTransferedPackages.add(origPackage.name);
6696
6697                // No longer need to retain this.
6698                pkgSetting.origPackage = null;
6699            }
6700
6701            if (realName != null) {
6702                // Make a note of it.
6703                mTransferedPackages.add(pkg.packageName);
6704            }
6705
6706            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6707                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6708            }
6709
6710            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6711                // Check all shared libraries and map to their actual file path.
6712                // We only do this here for apps not on a system dir, because those
6713                // are the only ones that can fail an install due to this.  We
6714                // will take care of the system apps by updating all of their
6715                // library paths after the scan is done.
6716                updateSharedLibrariesLPw(pkg, null);
6717            }
6718
6719            if (mFoundPolicyFile) {
6720                SELinuxMMAC.assignSeinfoValue(pkg);
6721            }
6722
6723            pkg.applicationInfo.uid = pkgSetting.appId;
6724            pkg.mExtras = pkgSetting;
6725            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6726                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6727                    // We just determined the app is signed correctly, so bring
6728                    // over the latest parsed certs.
6729                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6730                } else {
6731                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6732                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6733                                "Package " + pkg.packageName + " upgrade keys do not match the "
6734                                + "previously installed version");
6735                    } else {
6736                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6737                        String msg = "System package " + pkg.packageName
6738                            + " signature changed; retaining data.";
6739                        reportSettingsProblem(Log.WARN, msg);
6740                    }
6741                }
6742            } else {
6743                try {
6744                    verifySignaturesLP(pkgSetting, pkg);
6745                    // We just determined the app is signed correctly, so bring
6746                    // over the latest parsed certs.
6747                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6748                } catch (PackageManagerException e) {
6749                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6750                        throw e;
6751                    }
6752                    // The signature has changed, but this package is in the system
6753                    // image...  let's recover!
6754                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6755                    // However...  if this package is part of a shared user, but it
6756                    // doesn't match the signature of the shared user, let's fail.
6757                    // What this means is that you can't change the signatures
6758                    // associated with an overall shared user, which doesn't seem all
6759                    // that unreasonable.
6760                    if (pkgSetting.sharedUser != null) {
6761                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6762                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6763                            throw new PackageManagerException(
6764                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6765                                            "Signature mismatch for shared user : "
6766                                            + pkgSetting.sharedUser);
6767                        }
6768                    }
6769                    // File a report about this.
6770                    String msg = "System package " + pkg.packageName
6771                        + " signature changed; retaining data.";
6772                    reportSettingsProblem(Log.WARN, msg);
6773                }
6774            }
6775            // Verify that this new package doesn't have any content providers
6776            // that conflict with existing packages.  Only do this if the
6777            // package isn't already installed, since we don't want to break
6778            // things that are installed.
6779            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6780                final int N = pkg.providers.size();
6781                int i;
6782                for (i=0; i<N; i++) {
6783                    PackageParser.Provider p = pkg.providers.get(i);
6784                    if (p.info.authority != null) {
6785                        String names[] = p.info.authority.split(";");
6786                        for (int j = 0; j < names.length; j++) {
6787                            if (mProvidersByAuthority.containsKey(names[j])) {
6788                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6789                                final String otherPackageName =
6790                                        ((other != null && other.getComponentName() != null) ?
6791                                                other.getComponentName().getPackageName() : "?");
6792                                throw new PackageManagerException(
6793                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6794                                                "Can't install because provider name " + names[j]
6795                                                + " (in package " + pkg.applicationInfo.packageName
6796                                                + ") is already used by " + otherPackageName);
6797                            }
6798                        }
6799                    }
6800                }
6801            }
6802
6803            if (pkg.mAdoptPermissions != null) {
6804                // This package wants to adopt ownership of permissions from
6805                // another package.
6806                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6807                    final String origName = pkg.mAdoptPermissions.get(i);
6808                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6809                    if (orig != null) {
6810                        if (verifyPackageUpdateLPr(orig, pkg)) {
6811                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6812                                    + pkg.packageName);
6813                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6814                        }
6815                    }
6816                }
6817            }
6818        }
6819
6820        final String pkgName = pkg.packageName;
6821
6822        final long scanFileTime = scanFile.lastModified();
6823        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6824        pkg.applicationInfo.processName = fixProcessName(
6825                pkg.applicationInfo.packageName,
6826                pkg.applicationInfo.processName,
6827                pkg.applicationInfo.uid);
6828
6829        File dataPath;
6830        if (mPlatformPackage == pkg) {
6831            // The system package is special.
6832            dataPath = new File(Environment.getDataDirectory(), "system");
6833
6834            pkg.applicationInfo.dataDir = dataPath.getPath();
6835
6836        } else {
6837            // This is a normal package, need to make its data directory.
6838            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6839                    UserHandle.USER_OWNER, pkg.packageName);
6840
6841            boolean uidError = false;
6842            if (dataPath.exists()) {
6843                int currentUid = 0;
6844                try {
6845                    StructStat stat = Os.stat(dataPath.getPath());
6846                    currentUid = stat.st_uid;
6847                } catch (ErrnoException e) {
6848                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6849                }
6850
6851                // If we have mismatched owners for the data path, we have a problem.
6852                if (currentUid != pkg.applicationInfo.uid) {
6853                    boolean recovered = false;
6854                    if (currentUid == 0) {
6855                        // The directory somehow became owned by root.  Wow.
6856                        // This is probably because the system was stopped while
6857                        // installd was in the middle of messing with its libs
6858                        // directory.  Ask installd to fix that.
6859                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6860                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6861                        if (ret >= 0) {
6862                            recovered = true;
6863                            String msg = "Package " + pkg.packageName
6864                                    + " unexpectedly changed to uid 0; recovered to " +
6865                                    + pkg.applicationInfo.uid;
6866                            reportSettingsProblem(Log.WARN, msg);
6867                        }
6868                    }
6869                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6870                            || (scanFlags&SCAN_BOOTING) != 0)) {
6871                        // If this is a system app, we can at least delete its
6872                        // current data so the application will still work.
6873                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6874                        if (ret >= 0) {
6875                            // TODO: Kill the processes first
6876                            // Old data gone!
6877                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6878                                    ? "System package " : "Third party package ";
6879                            String msg = prefix + pkg.packageName
6880                                    + " has changed from uid: "
6881                                    + currentUid + " to "
6882                                    + pkg.applicationInfo.uid + "; old data erased";
6883                            reportSettingsProblem(Log.WARN, msg);
6884                            recovered = true;
6885
6886                            // And now re-install the app.
6887                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6888                                    pkg.applicationInfo.seinfo);
6889                            if (ret == -1) {
6890                                // Ack should not happen!
6891                                msg = prefix + pkg.packageName
6892                                        + " could not have data directory re-created after delete.";
6893                                reportSettingsProblem(Log.WARN, msg);
6894                                throw new PackageManagerException(
6895                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6896                            }
6897                        }
6898                        if (!recovered) {
6899                            mHasSystemUidErrors = true;
6900                        }
6901                    } else if (!recovered) {
6902                        // If we allow this install to proceed, we will be broken.
6903                        // Abort, abort!
6904                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6905                                "scanPackageLI");
6906                    }
6907                    if (!recovered) {
6908                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6909                            + pkg.applicationInfo.uid + "/fs_"
6910                            + currentUid;
6911                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6912                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6913                        String msg = "Package " + pkg.packageName
6914                                + " has mismatched uid: "
6915                                + currentUid + " on disk, "
6916                                + pkg.applicationInfo.uid + " in settings";
6917                        // writer
6918                        synchronized (mPackages) {
6919                            mSettings.mReadMessages.append(msg);
6920                            mSettings.mReadMessages.append('\n');
6921                            uidError = true;
6922                            if (!pkgSetting.uidError) {
6923                                reportSettingsProblem(Log.ERROR, msg);
6924                            }
6925                        }
6926                    }
6927                }
6928                pkg.applicationInfo.dataDir = dataPath.getPath();
6929                if (mShouldRestoreconData) {
6930                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6931                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6932                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6933                }
6934            } else {
6935                if (DEBUG_PACKAGE_SCANNING) {
6936                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6937                        Log.v(TAG, "Want this data dir: " + dataPath);
6938                }
6939                //invoke installer to do the actual installation
6940                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6941                        pkg.applicationInfo.seinfo);
6942                if (ret < 0) {
6943                    // Error from installer
6944                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6945                            "Unable to create data dirs [errorCode=" + ret + "]");
6946                }
6947
6948                if (dataPath.exists()) {
6949                    pkg.applicationInfo.dataDir = dataPath.getPath();
6950                } else {
6951                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6952                    pkg.applicationInfo.dataDir = null;
6953                }
6954            }
6955
6956            pkgSetting.uidError = uidError;
6957        }
6958
6959        final String path = scanFile.getPath();
6960        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6961
6962        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
6963            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
6964
6965            // Some system apps still use directory structure for native libraries
6966            // in which case we might end up not detecting abi solely based on apk
6967            // structure. Try to detect abi based on directory structure.
6968            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
6969                    pkg.applicationInfo.primaryCpuAbi == null) {
6970                setBundledAppAbisAndRoots(pkg, pkgSetting);
6971                setNativeLibraryPaths(pkg);
6972            }
6973
6974        } else {
6975            if ((scanFlags & SCAN_MOVE) != 0) {
6976                // We haven't run dex-opt for this move (since we've moved the compiled output too)
6977                // but we already have this packages package info in the PackageSetting. We just
6978                // use that and derive the native library path based on the new codepath.
6979                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
6980                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
6981            }
6982
6983            // Set native library paths again. For moves, the path will be updated based on the
6984            // ABIs we've determined above. For non-moves, the path will be updated based on the
6985            // ABIs we determined during compilation, but the path will depend on the final
6986            // package path (after the rename away from the stage path).
6987            setNativeLibraryPaths(pkg);
6988        }
6989
6990        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6991        final int[] userIds = sUserManager.getUserIds();
6992        synchronized (mInstallLock) {
6993            // Make sure all user data directories are ready to roll; we're okay
6994            // if they already exist
6995            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
6996                for (int userId : userIds) {
6997                    if (userId != 0) {
6998                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
6999                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7000                                pkg.applicationInfo.seinfo);
7001                    }
7002                }
7003            }
7004
7005            // Create a native library symlink only if we have native libraries
7006            // and if the native libraries are 32 bit libraries. We do not provide
7007            // this symlink for 64 bit libraries.
7008            if (pkg.applicationInfo.primaryCpuAbi != null &&
7009                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7010                final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7011                for (int userId : userIds) {
7012                    if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7013                            nativeLibPath, userId) < 0) {
7014                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7015                                "Failed linking native library dir (user=" + userId + ")");
7016                    }
7017                }
7018            }
7019        }
7020
7021        // This is a special case for the "system" package, where the ABI is
7022        // dictated by the zygote configuration (and init.rc). We should keep track
7023        // of this ABI so that we can deal with "normal" applications that run under
7024        // the same UID correctly.
7025        if (mPlatformPackage == pkg) {
7026            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7027                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7028        }
7029
7030        // If there's a mismatch between the abi-override in the package setting
7031        // and the abiOverride specified for the install. Warn about this because we
7032        // would've already compiled the app without taking the package setting into
7033        // account.
7034        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7035            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7036                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7037                        " for package: " + pkg.packageName);
7038            }
7039        }
7040
7041        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7042        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7043        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7044
7045        // Copy the derived override back to the parsed package, so that we can
7046        // update the package settings accordingly.
7047        pkg.cpuAbiOverride = cpuAbiOverride;
7048
7049        if (DEBUG_ABI_SELECTION) {
7050            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7051                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7052                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7053        }
7054
7055        // Push the derived path down into PackageSettings so we know what to
7056        // clean up at uninstall time.
7057        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7058
7059        if (DEBUG_ABI_SELECTION) {
7060            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7061                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7062                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7063        }
7064
7065        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7066            // We don't do this here during boot because we can do it all
7067            // at once after scanning all existing packages.
7068            //
7069            // We also do this *before* we perform dexopt on this package, so that
7070            // we can avoid redundant dexopts, and also to make sure we've got the
7071            // code and package path correct.
7072            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7073                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */);
7074        }
7075
7076        if ((scanFlags & SCAN_NO_DEX) == 0) {
7077            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7078                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,
7079                    (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/);
7080            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7081                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7082            }
7083        }
7084        if (mFactoryTest && pkg.requestedPermissions.contains(
7085                android.Manifest.permission.FACTORY_TEST)) {
7086            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7087        }
7088
7089        ArrayList<PackageParser.Package> clientLibPkgs = null;
7090
7091        // writer
7092        synchronized (mPackages) {
7093            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7094                // Only system apps can add new shared libraries.
7095                if (pkg.libraryNames != null) {
7096                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7097                        String name = pkg.libraryNames.get(i);
7098                        boolean allowed = false;
7099                        if (pkg.isUpdatedSystemApp()) {
7100                            // New library entries can only be added through the
7101                            // system image.  This is important to get rid of a lot
7102                            // of nasty edge cases: for example if we allowed a non-
7103                            // system update of the app to add a library, then uninstalling
7104                            // the update would make the library go away, and assumptions
7105                            // we made such as through app install filtering would now
7106                            // have allowed apps on the device which aren't compatible
7107                            // with it.  Better to just have the restriction here, be
7108                            // conservative, and create many fewer cases that can negatively
7109                            // impact the user experience.
7110                            final PackageSetting sysPs = mSettings
7111                                    .getDisabledSystemPkgLPr(pkg.packageName);
7112                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7113                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7114                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7115                                        allowed = true;
7116                                        allowed = true;
7117                                        break;
7118                                    }
7119                                }
7120                            }
7121                        } else {
7122                            allowed = true;
7123                        }
7124                        if (allowed) {
7125                            if (!mSharedLibraries.containsKey(name)) {
7126                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7127                            } else if (!name.equals(pkg.packageName)) {
7128                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7129                                        + name + " already exists; skipping");
7130                            }
7131                        } else {
7132                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7133                                    + name + " that is not declared on system image; skipping");
7134                        }
7135                    }
7136                    if ((scanFlags&SCAN_BOOTING) == 0) {
7137                        // If we are not booting, we need to update any applications
7138                        // that are clients of our shared library.  If we are booting,
7139                        // this will all be done once the scan is complete.
7140                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7141                    }
7142                }
7143            }
7144        }
7145
7146        // We also need to dexopt any apps that are dependent on this library.  Note that
7147        // if these fail, we should abort the install since installing the library will
7148        // result in some apps being broken.
7149        if (clientLibPkgs != null) {
7150            if ((scanFlags & SCAN_NO_DEX) == 0) {
7151                for (int i = 0; i < clientLibPkgs.size(); i++) {
7152                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
7153                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7154                            null /* instruction sets */, forceDex,
7155                            (scanFlags & SCAN_DEFER_DEX) != 0, false,
7156                            (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/);
7157                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7158                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7159                                "scanPackageLI failed to dexopt clientLibPkgs");
7160                    }
7161                }
7162            }
7163        }
7164
7165        // Request the ActivityManager to kill the process(only for existing packages)
7166        // so that we do not end up in a confused state while the user is still using the older
7167        // version of the application while the new one gets installed.
7168        if ((scanFlags & SCAN_REPLACING) != 0) {
7169            killApplication(pkg.applicationInfo.packageName,
7170                        pkg.applicationInfo.uid, "replace pkg");
7171        }
7172
7173        // Also need to kill any apps that are dependent on the library.
7174        if (clientLibPkgs != null) {
7175            for (int i=0; i<clientLibPkgs.size(); i++) {
7176                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7177                killApplication(clientPkg.applicationInfo.packageName,
7178                        clientPkg.applicationInfo.uid, "update lib");
7179            }
7180        }
7181
7182        // Make sure we're not adding any bogus keyset info
7183        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7184        ksms.assertScannedPackageValid(pkg);
7185
7186        // writer
7187        synchronized (mPackages) {
7188            // We don't expect installation to fail beyond this point
7189
7190            // Add the new setting to mSettings
7191            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7192            // Add the new setting to mPackages
7193            mPackages.put(pkg.applicationInfo.packageName, pkg);
7194            // Make sure we don't accidentally delete its data.
7195            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7196            while (iter.hasNext()) {
7197                PackageCleanItem item = iter.next();
7198                if (pkgName.equals(item.packageName)) {
7199                    iter.remove();
7200                }
7201            }
7202
7203            // Take care of first install / last update times.
7204            if (currentTime != 0) {
7205                if (pkgSetting.firstInstallTime == 0) {
7206                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7207                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7208                    pkgSetting.lastUpdateTime = currentTime;
7209                }
7210            } else if (pkgSetting.firstInstallTime == 0) {
7211                // We need *something*.  Take time time stamp of the file.
7212                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7213            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7214                if (scanFileTime != pkgSetting.timeStamp) {
7215                    // A package on the system image has changed; consider this
7216                    // to be an update.
7217                    pkgSetting.lastUpdateTime = scanFileTime;
7218                }
7219            }
7220
7221            // Add the package's KeySets to the global KeySetManagerService
7222            ksms.addScannedPackageLPw(pkg);
7223
7224            int N = pkg.providers.size();
7225            StringBuilder r = null;
7226            int i;
7227            for (i=0; i<N; i++) {
7228                PackageParser.Provider p = pkg.providers.get(i);
7229                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7230                        p.info.processName, pkg.applicationInfo.uid);
7231                mProviders.addProvider(p);
7232                p.syncable = p.info.isSyncable;
7233                if (p.info.authority != null) {
7234                    String names[] = p.info.authority.split(";");
7235                    p.info.authority = null;
7236                    for (int j = 0; j < names.length; j++) {
7237                        if (j == 1 && p.syncable) {
7238                            // We only want the first authority for a provider to possibly be
7239                            // syncable, so if we already added this provider using a different
7240                            // authority clear the syncable flag. We copy the provider before
7241                            // changing it because the mProviders object contains a reference
7242                            // to a provider that we don't want to change.
7243                            // Only do this for the second authority since the resulting provider
7244                            // object can be the same for all future authorities for this provider.
7245                            p = new PackageParser.Provider(p);
7246                            p.syncable = false;
7247                        }
7248                        if (!mProvidersByAuthority.containsKey(names[j])) {
7249                            mProvidersByAuthority.put(names[j], p);
7250                            if (p.info.authority == null) {
7251                                p.info.authority = names[j];
7252                            } else {
7253                                p.info.authority = p.info.authority + ";" + names[j];
7254                            }
7255                            if (DEBUG_PACKAGE_SCANNING) {
7256                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7257                                    Log.d(TAG, "Registered content provider: " + names[j]
7258                                            + ", className = " + p.info.name + ", isSyncable = "
7259                                            + p.info.isSyncable);
7260                            }
7261                        } else {
7262                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7263                            Slog.w(TAG, "Skipping provider name " + names[j] +
7264                                    " (in package " + pkg.applicationInfo.packageName +
7265                                    "): name already used by "
7266                                    + ((other != null && other.getComponentName() != null)
7267                                            ? other.getComponentName().getPackageName() : "?"));
7268                        }
7269                    }
7270                }
7271                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7272                    if (r == null) {
7273                        r = new StringBuilder(256);
7274                    } else {
7275                        r.append(' ');
7276                    }
7277                    r.append(p.info.name);
7278                }
7279            }
7280            if (r != null) {
7281                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7282            }
7283
7284            N = pkg.services.size();
7285            r = null;
7286            for (i=0; i<N; i++) {
7287                PackageParser.Service s = pkg.services.get(i);
7288                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7289                        s.info.processName, pkg.applicationInfo.uid);
7290                mServices.addService(s);
7291                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7292                    if (r == null) {
7293                        r = new StringBuilder(256);
7294                    } else {
7295                        r.append(' ');
7296                    }
7297                    r.append(s.info.name);
7298                }
7299            }
7300            if (r != null) {
7301                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7302            }
7303
7304            N = pkg.receivers.size();
7305            r = null;
7306            for (i=0; i<N; i++) {
7307                PackageParser.Activity a = pkg.receivers.get(i);
7308                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7309                        a.info.processName, pkg.applicationInfo.uid);
7310                mReceivers.addActivity(a, "receiver");
7311                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7312                    if (r == null) {
7313                        r = new StringBuilder(256);
7314                    } else {
7315                        r.append(' ');
7316                    }
7317                    r.append(a.info.name);
7318                }
7319            }
7320            if (r != null) {
7321                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7322            }
7323
7324            N = pkg.activities.size();
7325            r = null;
7326            for (i=0; i<N; i++) {
7327                PackageParser.Activity a = pkg.activities.get(i);
7328                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7329                        a.info.processName, pkg.applicationInfo.uid);
7330                mActivities.addActivity(a, "activity");
7331                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7332                    if (r == null) {
7333                        r = new StringBuilder(256);
7334                    } else {
7335                        r.append(' ');
7336                    }
7337                    r.append(a.info.name);
7338                }
7339            }
7340            if (r != null) {
7341                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7342            }
7343
7344            N = pkg.permissionGroups.size();
7345            r = null;
7346            for (i=0; i<N; i++) {
7347                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7348                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7349                if (cur == null) {
7350                    mPermissionGroups.put(pg.info.name, pg);
7351                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7352                        if (r == null) {
7353                            r = new StringBuilder(256);
7354                        } else {
7355                            r.append(' ');
7356                        }
7357                        r.append(pg.info.name);
7358                    }
7359                } else {
7360                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7361                            + pg.info.packageName + " ignored: original from "
7362                            + cur.info.packageName);
7363                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7364                        if (r == null) {
7365                            r = new StringBuilder(256);
7366                        } else {
7367                            r.append(' ');
7368                        }
7369                        r.append("DUP:");
7370                        r.append(pg.info.name);
7371                    }
7372                }
7373            }
7374            if (r != null) {
7375                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7376            }
7377
7378            N = pkg.permissions.size();
7379            r = null;
7380            for (i=0; i<N; i++) {
7381                PackageParser.Permission p = pkg.permissions.get(i);
7382
7383                // Assume by default that we did not install this permission into the system.
7384                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7385
7386                // Now that permission groups have a special meaning, we ignore permission
7387                // groups for legacy apps to prevent unexpected behavior. In particular,
7388                // permissions for one app being granted to someone just becuase they happen
7389                // to be in a group defined by another app (before this had no implications).
7390                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7391                    p.group = mPermissionGroups.get(p.info.group);
7392                    // Warn for a permission in an unknown group.
7393                    if (p.info.group != null && p.group == null) {
7394                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7395                                + p.info.packageName + " in an unknown group " + p.info.group);
7396                    }
7397                }
7398
7399                ArrayMap<String, BasePermission> permissionMap =
7400                        p.tree ? mSettings.mPermissionTrees
7401                                : mSettings.mPermissions;
7402                BasePermission bp = permissionMap.get(p.info.name);
7403
7404                // Allow system apps to redefine non-system permissions
7405                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7406                    final boolean currentOwnerIsSystem = (bp.perm != null
7407                            && isSystemApp(bp.perm.owner));
7408                    if (isSystemApp(p.owner)) {
7409                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7410                            // It's a built-in permission and no owner, take ownership now
7411                            bp.packageSetting = pkgSetting;
7412                            bp.perm = p;
7413                            bp.uid = pkg.applicationInfo.uid;
7414                            bp.sourcePackage = p.info.packageName;
7415                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7416                        } else if (!currentOwnerIsSystem) {
7417                            String msg = "New decl " + p.owner + " of permission  "
7418                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7419                            reportSettingsProblem(Log.WARN, msg);
7420                            bp = null;
7421                        }
7422                    }
7423                }
7424
7425                if (bp == null) {
7426                    bp = new BasePermission(p.info.name, p.info.packageName,
7427                            BasePermission.TYPE_NORMAL);
7428                    permissionMap.put(p.info.name, bp);
7429                }
7430
7431                if (bp.perm == null) {
7432                    if (bp.sourcePackage == null
7433                            || bp.sourcePackage.equals(p.info.packageName)) {
7434                        BasePermission tree = findPermissionTreeLP(p.info.name);
7435                        if (tree == null
7436                                || tree.sourcePackage.equals(p.info.packageName)) {
7437                            bp.packageSetting = pkgSetting;
7438                            bp.perm = p;
7439                            bp.uid = pkg.applicationInfo.uid;
7440                            bp.sourcePackage = p.info.packageName;
7441                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7442                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7443                                if (r == null) {
7444                                    r = new StringBuilder(256);
7445                                } else {
7446                                    r.append(' ');
7447                                }
7448                                r.append(p.info.name);
7449                            }
7450                        } else {
7451                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7452                                    + p.info.packageName + " ignored: base tree "
7453                                    + tree.name + " is from package "
7454                                    + tree.sourcePackage);
7455                        }
7456                    } else {
7457                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7458                                + p.info.packageName + " ignored: original from "
7459                                + bp.sourcePackage);
7460                    }
7461                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7462                    if (r == null) {
7463                        r = new StringBuilder(256);
7464                    } else {
7465                        r.append(' ');
7466                    }
7467                    r.append("DUP:");
7468                    r.append(p.info.name);
7469                }
7470                if (bp.perm == p) {
7471                    bp.protectionLevel = p.info.protectionLevel;
7472                }
7473            }
7474
7475            if (r != null) {
7476                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7477            }
7478
7479            N = pkg.instrumentation.size();
7480            r = null;
7481            for (i=0; i<N; i++) {
7482                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7483                a.info.packageName = pkg.applicationInfo.packageName;
7484                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7485                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7486                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7487                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7488                a.info.dataDir = pkg.applicationInfo.dataDir;
7489
7490                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7491                // need other information about the application, like the ABI and what not ?
7492                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7493                mInstrumentation.put(a.getComponentName(), a);
7494                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7495                    if (r == null) {
7496                        r = new StringBuilder(256);
7497                    } else {
7498                        r.append(' ');
7499                    }
7500                    r.append(a.info.name);
7501                }
7502            }
7503            if (r != null) {
7504                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7505            }
7506
7507            if (pkg.protectedBroadcasts != null) {
7508                N = pkg.protectedBroadcasts.size();
7509                for (i=0; i<N; i++) {
7510                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7511                }
7512            }
7513
7514            pkgSetting.setTimeStamp(scanFileTime);
7515
7516            // Create idmap files for pairs of (packages, overlay packages).
7517            // Note: "android", ie framework-res.apk, is handled by native layers.
7518            if (pkg.mOverlayTarget != null) {
7519                // This is an overlay package.
7520                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7521                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7522                        mOverlays.put(pkg.mOverlayTarget,
7523                                new ArrayMap<String, PackageParser.Package>());
7524                    }
7525                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7526                    map.put(pkg.packageName, pkg);
7527                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7528                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7529                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7530                                "scanPackageLI failed to createIdmap");
7531                    }
7532                }
7533            } else if (mOverlays.containsKey(pkg.packageName) &&
7534                    !pkg.packageName.equals("android")) {
7535                // This is a regular package, with one or more known overlay packages.
7536                createIdmapsForPackageLI(pkg);
7537            }
7538        }
7539
7540        return pkg;
7541    }
7542
7543    /**
7544     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7545     * is derived purely on the basis of the contents of {@code scanFile} and
7546     * {@code cpuAbiOverride}.
7547     *
7548     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7549     */
7550    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7551                                 String cpuAbiOverride, boolean extractLibs)
7552            throws PackageManagerException {
7553        // TODO: We can probably be smarter about this stuff. For installed apps,
7554        // we can calculate this information at install time once and for all. For
7555        // system apps, we can probably assume that this information doesn't change
7556        // after the first boot scan. As things stand, we do lots of unnecessary work.
7557
7558        // Give ourselves some initial paths; we'll come back for another
7559        // pass once we've determined ABI below.
7560        setNativeLibraryPaths(pkg);
7561
7562        // We would never need to extract libs for forward-locked and external packages,
7563        // since the container service will do it for us. We shouldn't attempt to
7564        // extract libs from system app when it was not updated.
7565        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7566                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7567            extractLibs = false;
7568        }
7569
7570        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7571        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7572
7573        NativeLibraryHelper.Handle handle = null;
7574        try {
7575            handle = NativeLibraryHelper.Handle.create(scanFile);
7576            // TODO(multiArch): This can be null for apps that didn't go through the
7577            // usual installation process. We can calculate it again, like we
7578            // do during install time.
7579            //
7580            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7581            // unnecessary.
7582            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7583
7584            // Null out the abis so that they can be recalculated.
7585            pkg.applicationInfo.primaryCpuAbi = null;
7586            pkg.applicationInfo.secondaryCpuAbi = null;
7587            if (isMultiArch(pkg.applicationInfo)) {
7588                // Warn if we've set an abiOverride for multi-lib packages..
7589                // By definition, we need to copy both 32 and 64 bit libraries for
7590                // such packages.
7591                if (pkg.cpuAbiOverride != null
7592                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7593                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7594                }
7595
7596                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7597                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7598                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7599                    if (extractLibs) {
7600                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7601                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7602                                useIsaSpecificSubdirs);
7603                    } else {
7604                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7605                    }
7606                }
7607
7608                maybeThrowExceptionForMultiArchCopy(
7609                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7610
7611                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7612                    if (extractLibs) {
7613                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7614                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7615                                useIsaSpecificSubdirs);
7616                    } else {
7617                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7618                    }
7619                }
7620
7621                maybeThrowExceptionForMultiArchCopy(
7622                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7623
7624                if (abi64 >= 0) {
7625                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7626                }
7627
7628                if (abi32 >= 0) {
7629                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7630                    if (abi64 >= 0) {
7631                        pkg.applicationInfo.secondaryCpuAbi = abi;
7632                    } else {
7633                        pkg.applicationInfo.primaryCpuAbi = abi;
7634                    }
7635                }
7636            } else {
7637                String[] abiList = (cpuAbiOverride != null) ?
7638                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7639
7640                // Enable gross and lame hacks for apps that are built with old
7641                // SDK tools. We must scan their APKs for renderscript bitcode and
7642                // not launch them if it's present. Don't bother checking on devices
7643                // that don't have 64 bit support.
7644                boolean needsRenderScriptOverride = false;
7645                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7646                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7647                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7648                    needsRenderScriptOverride = true;
7649                }
7650
7651                final int copyRet;
7652                if (extractLibs) {
7653                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7654                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7655                } else {
7656                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7657                }
7658
7659                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7660                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7661                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7662                }
7663
7664                if (copyRet >= 0) {
7665                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7666                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7667                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7668                } else if (needsRenderScriptOverride) {
7669                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7670                }
7671            }
7672        } catch (IOException ioe) {
7673            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7674        } finally {
7675            IoUtils.closeQuietly(handle);
7676        }
7677
7678        // Now that we've calculated the ABIs and determined if it's an internal app,
7679        // we will go ahead and populate the nativeLibraryPath.
7680        setNativeLibraryPaths(pkg);
7681    }
7682
7683    /**
7684     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7685     * i.e, so that all packages can be run inside a single process if required.
7686     *
7687     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7688     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7689     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7690     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7691     * updating a package that belongs to a shared user.
7692     *
7693     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7694     * adds unnecessary complexity.
7695     */
7696    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7697            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt,
7698            boolean bootComplete) {
7699        String requiredInstructionSet = null;
7700        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7701            requiredInstructionSet = VMRuntime.getInstructionSet(
7702                     scannedPackage.applicationInfo.primaryCpuAbi);
7703        }
7704
7705        PackageSetting requirer = null;
7706        for (PackageSetting ps : packagesForUser) {
7707            // If packagesForUser contains scannedPackage, we skip it. This will happen
7708            // when scannedPackage is an update of an existing package. Without this check,
7709            // we will never be able to change the ABI of any package belonging to a shared
7710            // user, even if it's compatible with other packages.
7711            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7712                if (ps.primaryCpuAbiString == null) {
7713                    continue;
7714                }
7715
7716                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7717                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7718                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7719                    // this but there's not much we can do.
7720                    String errorMessage = "Instruction set mismatch, "
7721                            + ((requirer == null) ? "[caller]" : requirer)
7722                            + " requires " + requiredInstructionSet + " whereas " + ps
7723                            + " requires " + instructionSet;
7724                    Slog.w(TAG, errorMessage);
7725                }
7726
7727                if (requiredInstructionSet == null) {
7728                    requiredInstructionSet = instructionSet;
7729                    requirer = ps;
7730                }
7731            }
7732        }
7733
7734        if (requiredInstructionSet != null) {
7735            String adjustedAbi;
7736            if (requirer != null) {
7737                // requirer != null implies that either scannedPackage was null or that scannedPackage
7738                // did not require an ABI, in which case we have to adjust scannedPackage to match
7739                // the ABI of the set (which is the same as requirer's ABI)
7740                adjustedAbi = requirer.primaryCpuAbiString;
7741                if (scannedPackage != null) {
7742                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7743                }
7744            } else {
7745                // requirer == null implies that we're updating all ABIs in the set to
7746                // match scannedPackage.
7747                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7748            }
7749
7750            for (PackageSetting ps : packagesForUser) {
7751                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7752                    if (ps.primaryCpuAbiString != null) {
7753                        continue;
7754                    }
7755
7756                    ps.primaryCpuAbiString = adjustedAbi;
7757                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7758                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7759                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7760
7761                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7762                                null /* instruction sets */, forceDexOpt, deferDexOpt, true,
7763                                bootComplete, false /*useJit*/);
7764                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7765                            ps.primaryCpuAbiString = null;
7766                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7767                            return;
7768                        } else {
7769                            mInstaller.rmdex(ps.codePathString,
7770                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7771                        }
7772                    }
7773                }
7774            }
7775        }
7776    }
7777
7778    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7779        synchronized (mPackages) {
7780            mResolverReplaced = true;
7781            // Set up information for custom user intent resolution activity.
7782            mResolveActivity.applicationInfo = pkg.applicationInfo;
7783            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7784            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7785            mResolveActivity.processName = pkg.applicationInfo.packageName;
7786            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7787            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7788                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7789            mResolveActivity.theme = 0;
7790            mResolveActivity.exported = true;
7791            mResolveActivity.enabled = true;
7792            mResolveInfo.activityInfo = mResolveActivity;
7793            mResolveInfo.priority = 0;
7794            mResolveInfo.preferredOrder = 0;
7795            mResolveInfo.match = 0;
7796            mResolveComponentName = mCustomResolverComponentName;
7797            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7798                    mResolveComponentName);
7799        }
7800    }
7801
7802    private static String calculateBundledApkRoot(final String codePathString) {
7803        final File codePath = new File(codePathString);
7804        final File codeRoot;
7805        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7806            codeRoot = Environment.getRootDirectory();
7807        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7808            codeRoot = Environment.getOemDirectory();
7809        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7810            codeRoot = Environment.getVendorDirectory();
7811        } else {
7812            // Unrecognized code path; take its top real segment as the apk root:
7813            // e.g. /something/app/blah.apk => /something
7814            try {
7815                File f = codePath.getCanonicalFile();
7816                File parent = f.getParentFile();    // non-null because codePath is a file
7817                File tmp;
7818                while ((tmp = parent.getParentFile()) != null) {
7819                    f = parent;
7820                    parent = tmp;
7821                }
7822                codeRoot = f;
7823                Slog.w(TAG, "Unrecognized code path "
7824                        + codePath + " - using " + codeRoot);
7825            } catch (IOException e) {
7826                // Can't canonicalize the code path -- shenanigans?
7827                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7828                return Environment.getRootDirectory().getPath();
7829            }
7830        }
7831        return codeRoot.getPath();
7832    }
7833
7834    /**
7835     * Derive and set the location of native libraries for the given package,
7836     * which varies depending on where and how the package was installed.
7837     */
7838    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7839        final ApplicationInfo info = pkg.applicationInfo;
7840        final String codePath = pkg.codePath;
7841        final File codeFile = new File(codePath);
7842        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7843        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
7844
7845        info.nativeLibraryRootDir = null;
7846        info.nativeLibraryRootRequiresIsa = false;
7847        info.nativeLibraryDir = null;
7848        info.secondaryNativeLibraryDir = null;
7849
7850        if (isApkFile(codeFile)) {
7851            // Monolithic install
7852            if (bundledApp) {
7853                // If "/system/lib64/apkname" exists, assume that is the per-package
7854                // native library directory to use; otherwise use "/system/lib/apkname".
7855                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7856                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7857                        getPrimaryInstructionSet(info));
7858
7859                // This is a bundled system app so choose the path based on the ABI.
7860                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7861                // is just the default path.
7862                final String apkName = deriveCodePathName(codePath);
7863                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7864                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7865                        apkName).getAbsolutePath();
7866
7867                if (info.secondaryCpuAbi != null) {
7868                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7869                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7870                            secondaryLibDir, apkName).getAbsolutePath();
7871                }
7872            } else if (asecApp) {
7873                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7874                        .getAbsolutePath();
7875            } else {
7876                final String apkName = deriveCodePathName(codePath);
7877                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7878                        .getAbsolutePath();
7879            }
7880
7881            info.nativeLibraryRootRequiresIsa = false;
7882            info.nativeLibraryDir = info.nativeLibraryRootDir;
7883        } else {
7884            // Cluster install
7885            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7886            info.nativeLibraryRootRequiresIsa = true;
7887
7888            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7889                    getPrimaryInstructionSet(info)).getAbsolutePath();
7890
7891            if (info.secondaryCpuAbi != null) {
7892                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7893                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7894            }
7895        }
7896    }
7897
7898    /**
7899     * Calculate the abis and roots for a bundled app. These can uniquely
7900     * be determined from the contents of the system partition, i.e whether
7901     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7902     * of this information, and instead assume that the system was built
7903     * sensibly.
7904     */
7905    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7906                                           PackageSetting pkgSetting) {
7907        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7908
7909        // If "/system/lib64/apkname" exists, assume that is the per-package
7910        // native library directory to use; otherwise use "/system/lib/apkname".
7911        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7912        setBundledAppAbi(pkg, apkRoot, apkName);
7913        // pkgSetting might be null during rescan following uninstall of updates
7914        // to a bundled app, so accommodate that possibility.  The settings in
7915        // that case will be established later from the parsed package.
7916        //
7917        // If the settings aren't null, sync them up with what we've just derived.
7918        // note that apkRoot isn't stored in the package settings.
7919        if (pkgSetting != null) {
7920            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7921            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7922        }
7923    }
7924
7925    /**
7926     * Deduces the ABI of a bundled app and sets the relevant fields on the
7927     * parsed pkg object.
7928     *
7929     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7930     *        under which system libraries are installed.
7931     * @param apkName the name of the installed package.
7932     */
7933    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7934        final File codeFile = new File(pkg.codePath);
7935
7936        final boolean has64BitLibs;
7937        final boolean has32BitLibs;
7938        if (isApkFile(codeFile)) {
7939            // Monolithic install
7940            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7941            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7942        } else {
7943            // Cluster install
7944            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7945            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7946                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7947                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7948                has64BitLibs = (new File(rootDir, isa)).exists();
7949            } else {
7950                has64BitLibs = false;
7951            }
7952            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7953                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7954                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7955                has32BitLibs = (new File(rootDir, isa)).exists();
7956            } else {
7957                has32BitLibs = false;
7958            }
7959        }
7960
7961        if (has64BitLibs && !has32BitLibs) {
7962            // The package has 64 bit libs, but not 32 bit libs. Its primary
7963            // ABI should be 64 bit. We can safely assume here that the bundled
7964            // native libraries correspond to the most preferred ABI in the list.
7965
7966            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7967            pkg.applicationInfo.secondaryCpuAbi = null;
7968        } else if (has32BitLibs && !has64BitLibs) {
7969            // The package has 32 bit libs but not 64 bit libs. Its primary
7970            // ABI should be 32 bit.
7971
7972            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7973            pkg.applicationInfo.secondaryCpuAbi = null;
7974        } else if (has32BitLibs && has64BitLibs) {
7975            // The application has both 64 and 32 bit bundled libraries. We check
7976            // here that the app declares multiArch support, and warn if it doesn't.
7977            //
7978            // We will be lenient here and record both ABIs. The primary will be the
7979            // ABI that's higher on the list, i.e, a device that's configured to prefer
7980            // 64 bit apps will see a 64 bit primary ABI,
7981
7982            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7983                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7984            }
7985
7986            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7987                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7988                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7989            } else {
7990                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7991                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7992            }
7993        } else {
7994            pkg.applicationInfo.primaryCpuAbi = null;
7995            pkg.applicationInfo.secondaryCpuAbi = null;
7996        }
7997    }
7998
7999    private void killApplication(String pkgName, int appId, String reason) {
8000        // Request the ActivityManager to kill the process(only for existing packages)
8001        // so that we do not end up in a confused state while the user is still using the older
8002        // version of the application while the new one gets installed.
8003        IActivityManager am = ActivityManagerNative.getDefault();
8004        if (am != null) {
8005            try {
8006                am.killApplicationWithAppId(pkgName, appId, reason);
8007            } catch (RemoteException e) {
8008            }
8009        }
8010    }
8011
8012    void removePackageLI(PackageSetting ps, boolean chatty) {
8013        if (DEBUG_INSTALL) {
8014            if (chatty)
8015                Log.d(TAG, "Removing package " + ps.name);
8016        }
8017
8018        // writer
8019        synchronized (mPackages) {
8020            mPackages.remove(ps.name);
8021            final PackageParser.Package pkg = ps.pkg;
8022            if (pkg != null) {
8023                cleanPackageDataStructuresLILPw(pkg, chatty);
8024            }
8025        }
8026    }
8027
8028    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8029        if (DEBUG_INSTALL) {
8030            if (chatty)
8031                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8032        }
8033
8034        // writer
8035        synchronized (mPackages) {
8036            mPackages.remove(pkg.applicationInfo.packageName);
8037            cleanPackageDataStructuresLILPw(pkg, chatty);
8038        }
8039    }
8040
8041    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8042        int N = pkg.providers.size();
8043        StringBuilder r = null;
8044        int i;
8045        for (i=0; i<N; i++) {
8046            PackageParser.Provider p = pkg.providers.get(i);
8047            mProviders.removeProvider(p);
8048            if (p.info.authority == null) {
8049
8050                /* There was another ContentProvider with this authority when
8051                 * this app was installed so this authority is null,
8052                 * Ignore it as we don't have to unregister the provider.
8053                 */
8054                continue;
8055            }
8056            String names[] = p.info.authority.split(";");
8057            for (int j = 0; j < names.length; j++) {
8058                if (mProvidersByAuthority.get(names[j]) == p) {
8059                    mProvidersByAuthority.remove(names[j]);
8060                    if (DEBUG_REMOVE) {
8061                        if (chatty)
8062                            Log.d(TAG, "Unregistered content provider: " + names[j]
8063                                    + ", className = " + p.info.name + ", isSyncable = "
8064                                    + p.info.isSyncable);
8065                    }
8066                }
8067            }
8068            if (DEBUG_REMOVE && chatty) {
8069                if (r == null) {
8070                    r = new StringBuilder(256);
8071                } else {
8072                    r.append(' ');
8073                }
8074                r.append(p.info.name);
8075            }
8076        }
8077        if (r != null) {
8078            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8079        }
8080
8081        N = pkg.services.size();
8082        r = null;
8083        for (i=0; i<N; i++) {
8084            PackageParser.Service s = pkg.services.get(i);
8085            mServices.removeService(s);
8086            if (chatty) {
8087                if (r == null) {
8088                    r = new StringBuilder(256);
8089                } else {
8090                    r.append(' ');
8091                }
8092                r.append(s.info.name);
8093            }
8094        }
8095        if (r != null) {
8096            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8097        }
8098
8099        N = pkg.receivers.size();
8100        r = null;
8101        for (i=0; i<N; i++) {
8102            PackageParser.Activity a = pkg.receivers.get(i);
8103            mReceivers.removeActivity(a, "receiver");
8104            if (DEBUG_REMOVE && chatty) {
8105                if (r == null) {
8106                    r = new StringBuilder(256);
8107                } else {
8108                    r.append(' ');
8109                }
8110                r.append(a.info.name);
8111            }
8112        }
8113        if (r != null) {
8114            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8115        }
8116
8117        N = pkg.activities.size();
8118        r = null;
8119        for (i=0; i<N; i++) {
8120            PackageParser.Activity a = pkg.activities.get(i);
8121            mActivities.removeActivity(a, "activity");
8122            if (DEBUG_REMOVE && chatty) {
8123                if (r == null) {
8124                    r = new StringBuilder(256);
8125                } else {
8126                    r.append(' ');
8127                }
8128                r.append(a.info.name);
8129            }
8130        }
8131        if (r != null) {
8132            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8133        }
8134
8135        N = pkg.permissions.size();
8136        r = null;
8137        for (i=0; i<N; i++) {
8138            PackageParser.Permission p = pkg.permissions.get(i);
8139            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8140            if (bp == null) {
8141                bp = mSettings.mPermissionTrees.get(p.info.name);
8142            }
8143            if (bp != null && bp.perm == p) {
8144                bp.perm = null;
8145                if (DEBUG_REMOVE && chatty) {
8146                    if (r == null) {
8147                        r = new StringBuilder(256);
8148                    } else {
8149                        r.append(' ');
8150                    }
8151                    r.append(p.info.name);
8152                }
8153            }
8154            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8155                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8156                if (appOpPerms != null) {
8157                    appOpPerms.remove(pkg.packageName);
8158                }
8159            }
8160        }
8161        if (r != null) {
8162            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8163        }
8164
8165        N = pkg.requestedPermissions.size();
8166        r = null;
8167        for (i=0; i<N; i++) {
8168            String perm = pkg.requestedPermissions.get(i);
8169            BasePermission bp = mSettings.mPermissions.get(perm);
8170            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8171                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8172                if (appOpPerms != null) {
8173                    appOpPerms.remove(pkg.packageName);
8174                    if (appOpPerms.isEmpty()) {
8175                        mAppOpPermissionPackages.remove(perm);
8176                    }
8177                }
8178            }
8179        }
8180        if (r != null) {
8181            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8182        }
8183
8184        N = pkg.instrumentation.size();
8185        r = null;
8186        for (i=0; i<N; i++) {
8187            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8188            mInstrumentation.remove(a.getComponentName());
8189            if (DEBUG_REMOVE && chatty) {
8190                if (r == null) {
8191                    r = new StringBuilder(256);
8192                } else {
8193                    r.append(' ');
8194                }
8195                r.append(a.info.name);
8196            }
8197        }
8198        if (r != null) {
8199            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8200        }
8201
8202        r = null;
8203        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8204            // Only system apps can hold shared libraries.
8205            if (pkg.libraryNames != null) {
8206                for (i=0; i<pkg.libraryNames.size(); i++) {
8207                    String name = pkg.libraryNames.get(i);
8208                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8209                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8210                        mSharedLibraries.remove(name);
8211                        if (DEBUG_REMOVE && chatty) {
8212                            if (r == null) {
8213                                r = new StringBuilder(256);
8214                            } else {
8215                                r.append(' ');
8216                            }
8217                            r.append(name);
8218                        }
8219                    }
8220                }
8221            }
8222        }
8223        if (r != null) {
8224            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8225        }
8226    }
8227
8228    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8229        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8230            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8231                return true;
8232            }
8233        }
8234        return false;
8235    }
8236
8237    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8238    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8239    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8240
8241    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8242            int flags) {
8243        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8244        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8245    }
8246
8247    private void updatePermissionsLPw(String changingPkg,
8248            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8249        // Make sure there are no dangling permission trees.
8250        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8251        while (it.hasNext()) {
8252            final BasePermission bp = it.next();
8253            if (bp.packageSetting == null) {
8254                // We may not yet have parsed the package, so just see if
8255                // we still know about its settings.
8256                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8257            }
8258            if (bp.packageSetting == null) {
8259                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8260                        + " from package " + bp.sourcePackage);
8261                it.remove();
8262            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8263                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8264                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8265                            + " from package " + bp.sourcePackage);
8266                    flags |= UPDATE_PERMISSIONS_ALL;
8267                    it.remove();
8268                }
8269            }
8270        }
8271
8272        // Make sure all dynamic permissions have been assigned to a package,
8273        // and make sure there are no dangling permissions.
8274        it = mSettings.mPermissions.values().iterator();
8275        while (it.hasNext()) {
8276            final BasePermission bp = it.next();
8277            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8278                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8279                        + bp.name + " pkg=" + bp.sourcePackage
8280                        + " info=" + bp.pendingInfo);
8281                if (bp.packageSetting == null && bp.pendingInfo != null) {
8282                    final BasePermission tree = findPermissionTreeLP(bp.name);
8283                    if (tree != null && tree.perm != null) {
8284                        bp.packageSetting = tree.packageSetting;
8285                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8286                                new PermissionInfo(bp.pendingInfo));
8287                        bp.perm.info.packageName = tree.perm.info.packageName;
8288                        bp.perm.info.name = bp.name;
8289                        bp.uid = tree.uid;
8290                    }
8291                }
8292            }
8293            if (bp.packageSetting == null) {
8294                // We may not yet have parsed the package, so just see if
8295                // we still know about its settings.
8296                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8297            }
8298            if (bp.packageSetting == null) {
8299                Slog.w(TAG, "Removing dangling permission: " + bp.name
8300                        + " from package " + bp.sourcePackage);
8301                it.remove();
8302            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8303                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8304                    Slog.i(TAG, "Removing old permission: " + bp.name
8305                            + " from package " + bp.sourcePackage);
8306                    flags |= UPDATE_PERMISSIONS_ALL;
8307                    it.remove();
8308                }
8309            }
8310        }
8311
8312        // Now update the permissions for all packages, in particular
8313        // replace the granted permissions of the system packages.
8314        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8315            for (PackageParser.Package pkg : mPackages.values()) {
8316                if (pkg != pkgInfo) {
8317                    // Only replace for packages on requested volume
8318                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8319                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8320                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8321                    grantPermissionsLPw(pkg, replace, changingPkg);
8322                }
8323            }
8324        }
8325
8326        if (pkgInfo != null) {
8327            // Only replace for packages on requested volume
8328            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8329            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8330                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8331            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8332        }
8333    }
8334
8335    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8336            String packageOfInterest) {
8337        // IMPORTANT: There are two types of permissions: install and runtime.
8338        // Install time permissions are granted when the app is installed to
8339        // all device users and users added in the future. Runtime permissions
8340        // are granted at runtime explicitly to specific users. Normal and signature
8341        // protected permissions are install time permissions. Dangerous permissions
8342        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8343        // otherwise they are runtime permissions. This function does not manage
8344        // runtime permissions except for the case an app targeting Lollipop MR1
8345        // being upgraded to target a newer SDK, in which case dangerous permissions
8346        // are transformed from install time to runtime ones.
8347
8348        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8349        if (ps == null) {
8350            return;
8351        }
8352
8353        PermissionsState permissionsState = ps.getPermissionsState();
8354        PermissionsState origPermissions = permissionsState;
8355
8356        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8357
8358        boolean runtimePermissionsRevoked = false;
8359        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8360
8361        boolean changedInstallPermission = false;
8362
8363        if (replace) {
8364            ps.installPermissionsFixed = false;
8365            if (!ps.isSharedUser()) {
8366                origPermissions = new PermissionsState(permissionsState);
8367                permissionsState.reset();
8368            } else {
8369                // We need to know only about runtime permission changes since the
8370                // calling code always writes the install permissions state but
8371                // the runtime ones are written only if changed. The only cases of
8372                // changed runtime permissions here are promotion of an install to
8373                // runtime and revocation of a runtime from a shared user.
8374                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8375                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8376                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8377                    runtimePermissionsRevoked = true;
8378                }
8379            }
8380        }
8381
8382        permissionsState.setGlobalGids(mGlobalGids);
8383
8384        final int N = pkg.requestedPermissions.size();
8385        for (int i=0; i<N; i++) {
8386            final String name = pkg.requestedPermissions.get(i);
8387            final BasePermission bp = mSettings.mPermissions.get(name);
8388
8389            if (DEBUG_INSTALL) {
8390                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8391            }
8392
8393            if (bp == null || bp.packageSetting == null) {
8394                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8395                    Slog.w(TAG, "Unknown permission " + name
8396                            + " in package " + pkg.packageName);
8397                }
8398                continue;
8399            }
8400
8401            final String perm = bp.name;
8402            boolean allowedSig = false;
8403            int grant = GRANT_DENIED;
8404
8405            // Keep track of app op permissions.
8406            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8407                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8408                if (pkgs == null) {
8409                    pkgs = new ArraySet<>();
8410                    mAppOpPermissionPackages.put(bp.name, pkgs);
8411                }
8412                pkgs.add(pkg.packageName);
8413            }
8414
8415            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8416            switch (level) {
8417                case PermissionInfo.PROTECTION_NORMAL: {
8418                    // For all apps normal permissions are install time ones.
8419                    grant = GRANT_INSTALL;
8420                } break;
8421
8422                case PermissionInfo.PROTECTION_DANGEROUS: {
8423                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8424                        // For legacy apps dangerous permissions are install time ones.
8425                        grant = GRANT_INSTALL_LEGACY;
8426                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8427                        // For legacy apps that became modern, install becomes runtime.
8428                        grant = GRANT_UPGRADE;
8429                    } else if (mPromoteSystemApps
8430                            && isSystemApp(ps)
8431                            && mExistingSystemPackages.contains(ps.name)) {
8432                        // For legacy system apps, install becomes runtime.
8433                        // We cannot check hasInstallPermission() for system apps since those
8434                        // permissions were granted implicitly and not persisted pre-M.
8435                        grant = GRANT_UPGRADE;
8436                    } else {
8437                        // For modern apps keep runtime permissions unchanged.
8438                        grant = GRANT_RUNTIME;
8439                    }
8440                } break;
8441
8442                case PermissionInfo.PROTECTION_SIGNATURE: {
8443                    // For all apps signature permissions are install time ones.
8444                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8445                    if (allowedSig) {
8446                        grant = GRANT_INSTALL;
8447                    }
8448                } break;
8449            }
8450
8451            if (DEBUG_INSTALL) {
8452                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8453            }
8454
8455            if (grant != GRANT_DENIED) {
8456                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8457                    // If this is an existing, non-system package, then
8458                    // we can't add any new permissions to it.
8459                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8460                        // Except...  if this is a permission that was added
8461                        // to the platform (note: need to only do this when
8462                        // updating the platform).
8463                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8464                            grant = GRANT_DENIED;
8465                        }
8466                    }
8467                }
8468
8469                switch (grant) {
8470                    case GRANT_INSTALL: {
8471                        // Revoke this as runtime permission to handle the case of
8472                        // a runtime permission being downgraded to an install one.
8473                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8474                            if (origPermissions.getRuntimePermissionState(
8475                                    bp.name, userId) != null) {
8476                                // Revoke the runtime permission and clear the flags.
8477                                origPermissions.revokeRuntimePermission(bp, userId);
8478                                origPermissions.updatePermissionFlags(bp, userId,
8479                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8480                                // If we revoked a permission permission, we have to write.
8481                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8482                                        changedRuntimePermissionUserIds, userId);
8483                            }
8484                        }
8485                        // Grant an install permission.
8486                        if (permissionsState.grantInstallPermission(bp) !=
8487                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8488                            changedInstallPermission = true;
8489                        }
8490                    } break;
8491
8492                    case GRANT_INSTALL_LEGACY: {
8493                        // Grant an install permission.
8494                        if (permissionsState.grantInstallPermission(bp) !=
8495                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8496                            changedInstallPermission = true;
8497                        }
8498                    } break;
8499
8500                    case GRANT_RUNTIME: {
8501                        // Grant previously granted runtime permissions.
8502                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8503                            PermissionState permissionState = origPermissions
8504                                    .getRuntimePermissionState(bp.name, userId);
8505                            final int flags = permissionState != null
8506                                    ? permissionState.getFlags() : 0;
8507                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8508                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8509                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8510                                    // If we cannot put the permission as it was, we have to write.
8511                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8512                                            changedRuntimePermissionUserIds, userId);
8513                                }
8514                            }
8515                            // Propagate the permission flags.
8516                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8517                        }
8518                    } break;
8519
8520                    case GRANT_UPGRADE: {
8521                        // Grant runtime permissions for a previously held install permission.
8522                        PermissionState permissionState = origPermissions
8523                                .getInstallPermissionState(bp.name);
8524                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8525
8526                        if (origPermissions.revokeInstallPermission(bp)
8527                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8528                            // We will be transferring the permission flags, so clear them.
8529                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8530                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8531                            changedInstallPermission = true;
8532                        }
8533
8534                        // If the permission is not to be promoted to runtime we ignore it and
8535                        // also its other flags as they are not applicable to install permissions.
8536                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8537                            for (int userId : currentUserIds) {
8538                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8539                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8540                                    // Transfer the permission flags.
8541                                    permissionsState.updatePermissionFlags(bp, userId,
8542                                            flags, flags);
8543                                    // If we granted the permission, we have to write.
8544                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8545                                            changedRuntimePermissionUserIds, userId);
8546                                }
8547                            }
8548                        }
8549                    } break;
8550
8551                    default: {
8552                        if (packageOfInterest == null
8553                                || packageOfInterest.equals(pkg.packageName)) {
8554                            Slog.w(TAG, "Not granting permission " + perm
8555                                    + " to package " + pkg.packageName
8556                                    + " because it was previously installed without");
8557                        }
8558                    } break;
8559                }
8560            } else {
8561                if (permissionsState.revokeInstallPermission(bp) !=
8562                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8563                    // Also drop the permission flags.
8564                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8565                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8566                    changedInstallPermission = true;
8567                    Slog.i(TAG, "Un-granting permission " + perm
8568                            + " from package " + pkg.packageName
8569                            + " (protectionLevel=" + bp.protectionLevel
8570                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8571                            + ")");
8572                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8573                    // Don't print warning for app op permissions, since it is fine for them
8574                    // not to be granted, there is a UI for the user to decide.
8575                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8576                        Slog.w(TAG, "Not granting permission " + perm
8577                                + " to package " + pkg.packageName
8578                                + " (protectionLevel=" + bp.protectionLevel
8579                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8580                                + ")");
8581                    }
8582                }
8583            }
8584        }
8585
8586        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8587                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8588            // This is the first that we have heard about this package, so the
8589            // permissions we have now selected are fixed until explicitly
8590            // changed.
8591            ps.installPermissionsFixed = true;
8592        }
8593
8594        // Persist the runtime permissions state for users with changes. If permissions
8595        // were revoked because no app in the shared user declares them we have to
8596        // write synchronously to avoid losing runtime permissions state.
8597        for (int userId : changedRuntimePermissionUserIds) {
8598            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8599        }
8600    }
8601
8602    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8603        boolean allowed = false;
8604        final int NP = PackageParser.NEW_PERMISSIONS.length;
8605        for (int ip=0; ip<NP; ip++) {
8606            final PackageParser.NewPermissionInfo npi
8607                    = PackageParser.NEW_PERMISSIONS[ip];
8608            if (npi.name.equals(perm)
8609                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8610                allowed = true;
8611                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8612                        + pkg.packageName);
8613                break;
8614            }
8615        }
8616        return allowed;
8617    }
8618
8619    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8620            BasePermission bp, PermissionsState origPermissions) {
8621        boolean allowed;
8622        allowed = (compareSignatures(
8623                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8624                        == PackageManager.SIGNATURE_MATCH)
8625                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8626                        == PackageManager.SIGNATURE_MATCH);
8627        if (!allowed && (bp.protectionLevel
8628                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8629            if (isSystemApp(pkg)) {
8630                // For updated system applications, a system permission
8631                // is granted only if it had been defined by the original application.
8632                if (pkg.isUpdatedSystemApp()) {
8633                    final PackageSetting sysPs = mSettings
8634                            .getDisabledSystemPkgLPr(pkg.packageName);
8635                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8636                        // If the original was granted this permission, we take
8637                        // that grant decision as read and propagate it to the
8638                        // update.
8639                        if (sysPs.isPrivileged()) {
8640                            allowed = true;
8641                        }
8642                    } else {
8643                        // The system apk may have been updated with an older
8644                        // version of the one on the data partition, but which
8645                        // granted a new system permission that it didn't have
8646                        // before.  In this case we do want to allow the app to
8647                        // now get the new permission if the ancestral apk is
8648                        // privileged to get it.
8649                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8650                            for (int j=0;
8651                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8652                                if (perm.equals(
8653                                        sysPs.pkg.requestedPermissions.get(j))) {
8654                                    allowed = true;
8655                                    break;
8656                                }
8657                            }
8658                        }
8659                    }
8660                } else {
8661                    allowed = isPrivilegedApp(pkg);
8662                }
8663            }
8664        }
8665        if (!allowed) {
8666            if (!allowed && (bp.protectionLevel
8667                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8668                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8669                // If this was a previously normal/dangerous permission that got moved
8670                // to a system permission as part of the runtime permission redesign, then
8671                // we still want to blindly grant it to old apps.
8672                allowed = true;
8673            }
8674            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8675                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8676                // If this permission is to be granted to the system installer and
8677                // this app is an installer, then it gets the permission.
8678                allowed = true;
8679            }
8680            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8681                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8682                // If this permission is to be granted to the system verifier and
8683                // this app is a verifier, then it gets the permission.
8684                allowed = true;
8685            }
8686            if (!allowed && (bp.protectionLevel
8687                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8688                    && isSystemApp(pkg)) {
8689                // Any pre-installed system app is allowed to get this permission.
8690                allowed = true;
8691            }
8692            if (!allowed && (bp.protectionLevel
8693                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8694                // For development permissions, a development permission
8695                // is granted only if it was already granted.
8696                allowed = origPermissions.hasInstallPermission(perm);
8697            }
8698        }
8699        return allowed;
8700    }
8701
8702    final class ActivityIntentResolver
8703            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8704        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8705                boolean defaultOnly, int userId) {
8706            if (!sUserManager.exists(userId)) return null;
8707            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8708            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8709        }
8710
8711        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8712                int userId) {
8713            if (!sUserManager.exists(userId)) return null;
8714            mFlags = flags;
8715            return super.queryIntent(intent, resolvedType,
8716                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8717        }
8718
8719        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8720                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8721            if (!sUserManager.exists(userId)) return null;
8722            if (packageActivities == null) {
8723                return null;
8724            }
8725            mFlags = flags;
8726            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8727            final int N = packageActivities.size();
8728            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8729                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8730
8731            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8732            for (int i = 0; i < N; ++i) {
8733                intentFilters = packageActivities.get(i).intents;
8734                if (intentFilters != null && intentFilters.size() > 0) {
8735                    PackageParser.ActivityIntentInfo[] array =
8736                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8737                    intentFilters.toArray(array);
8738                    listCut.add(array);
8739                }
8740            }
8741            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8742        }
8743
8744        public final void addActivity(PackageParser.Activity a, String type) {
8745            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8746            mActivities.put(a.getComponentName(), a);
8747            if (DEBUG_SHOW_INFO)
8748                Log.v(
8749                TAG, "  " + type + " " +
8750                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8751            if (DEBUG_SHOW_INFO)
8752                Log.v(TAG, "    Class=" + a.info.name);
8753            final int NI = a.intents.size();
8754            for (int j=0; j<NI; j++) {
8755                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8756                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8757                    intent.setPriority(0);
8758                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8759                            + a.className + " with priority > 0, forcing to 0");
8760                }
8761                if (DEBUG_SHOW_INFO) {
8762                    Log.v(TAG, "    IntentFilter:");
8763                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8764                }
8765                if (!intent.debugCheck()) {
8766                    Log.w(TAG, "==> For Activity " + a.info.name);
8767                }
8768                addFilter(intent);
8769            }
8770        }
8771
8772        public final void removeActivity(PackageParser.Activity a, String type) {
8773            mActivities.remove(a.getComponentName());
8774            if (DEBUG_SHOW_INFO) {
8775                Log.v(TAG, "  " + type + " "
8776                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8777                                : a.info.name) + ":");
8778                Log.v(TAG, "    Class=" + a.info.name);
8779            }
8780            final int NI = a.intents.size();
8781            for (int j=0; j<NI; j++) {
8782                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8783                if (DEBUG_SHOW_INFO) {
8784                    Log.v(TAG, "    IntentFilter:");
8785                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8786                }
8787                removeFilter(intent);
8788            }
8789        }
8790
8791        @Override
8792        protected boolean allowFilterResult(
8793                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8794            ActivityInfo filterAi = filter.activity.info;
8795            for (int i=dest.size()-1; i>=0; i--) {
8796                ActivityInfo destAi = dest.get(i).activityInfo;
8797                if (destAi.name == filterAi.name
8798                        && destAi.packageName == filterAi.packageName) {
8799                    return false;
8800                }
8801            }
8802            return true;
8803        }
8804
8805        @Override
8806        protected ActivityIntentInfo[] newArray(int size) {
8807            return new ActivityIntentInfo[size];
8808        }
8809
8810        @Override
8811        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8812            if (!sUserManager.exists(userId)) return true;
8813            PackageParser.Package p = filter.activity.owner;
8814            if (p != null) {
8815                PackageSetting ps = (PackageSetting)p.mExtras;
8816                if (ps != null) {
8817                    // System apps are never considered stopped for purposes of
8818                    // filtering, because there may be no way for the user to
8819                    // actually re-launch them.
8820                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8821                            && ps.getStopped(userId);
8822                }
8823            }
8824            return false;
8825        }
8826
8827        @Override
8828        protected boolean isPackageForFilter(String packageName,
8829                PackageParser.ActivityIntentInfo info) {
8830            return packageName.equals(info.activity.owner.packageName);
8831        }
8832
8833        @Override
8834        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8835                int match, int userId) {
8836            if (!sUserManager.exists(userId)) return null;
8837            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8838                return null;
8839            }
8840            final PackageParser.Activity activity = info.activity;
8841            if (mSafeMode && (activity.info.applicationInfo.flags
8842                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8843                return null;
8844            }
8845            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8846            if (ps == null) {
8847                return null;
8848            }
8849            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8850                    ps.readUserState(userId), userId);
8851            if (ai == null) {
8852                return null;
8853            }
8854            final ResolveInfo res = new ResolveInfo();
8855            res.activityInfo = ai;
8856            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8857                res.filter = info;
8858            }
8859            if (info != null) {
8860                res.handleAllWebDataURI = info.handleAllWebDataURI();
8861            }
8862            res.priority = info.getPriority();
8863            res.preferredOrder = activity.owner.mPreferredOrder;
8864            //System.out.println("Result: " + res.activityInfo.className +
8865            //                   " = " + res.priority);
8866            res.match = match;
8867            res.isDefault = info.hasDefault;
8868            res.labelRes = info.labelRes;
8869            res.nonLocalizedLabel = info.nonLocalizedLabel;
8870            if (userNeedsBadging(userId)) {
8871                res.noResourceId = true;
8872            } else {
8873                res.icon = info.icon;
8874            }
8875            res.iconResourceId = info.icon;
8876            res.system = res.activityInfo.applicationInfo.isSystemApp();
8877            return res;
8878        }
8879
8880        @Override
8881        protected void sortResults(List<ResolveInfo> results) {
8882            Collections.sort(results, mResolvePrioritySorter);
8883        }
8884
8885        @Override
8886        protected void dumpFilter(PrintWriter out, String prefix,
8887                PackageParser.ActivityIntentInfo filter) {
8888            out.print(prefix); out.print(
8889                    Integer.toHexString(System.identityHashCode(filter.activity)));
8890                    out.print(' ');
8891                    filter.activity.printComponentShortName(out);
8892                    out.print(" filter ");
8893                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8894        }
8895
8896        @Override
8897        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8898            return filter.activity;
8899        }
8900
8901        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8902            PackageParser.Activity activity = (PackageParser.Activity)label;
8903            out.print(prefix); out.print(
8904                    Integer.toHexString(System.identityHashCode(activity)));
8905                    out.print(' ');
8906                    activity.printComponentShortName(out);
8907            if (count > 1) {
8908                out.print(" ("); out.print(count); out.print(" filters)");
8909            }
8910            out.println();
8911        }
8912
8913//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8914//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8915//            final List<ResolveInfo> retList = Lists.newArrayList();
8916//            while (i.hasNext()) {
8917//                final ResolveInfo resolveInfo = i.next();
8918//                if (isEnabledLP(resolveInfo.activityInfo)) {
8919//                    retList.add(resolveInfo);
8920//                }
8921//            }
8922//            return retList;
8923//        }
8924
8925        // Keys are String (activity class name), values are Activity.
8926        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8927                = new ArrayMap<ComponentName, PackageParser.Activity>();
8928        private int mFlags;
8929    }
8930
8931    private final class ServiceIntentResolver
8932            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8933        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8934                boolean defaultOnly, int userId) {
8935            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8936            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8937        }
8938
8939        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8940                int userId) {
8941            if (!sUserManager.exists(userId)) return null;
8942            mFlags = flags;
8943            return super.queryIntent(intent, resolvedType,
8944                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8945        }
8946
8947        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8948                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8949            if (!sUserManager.exists(userId)) return null;
8950            if (packageServices == null) {
8951                return null;
8952            }
8953            mFlags = flags;
8954            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8955            final int N = packageServices.size();
8956            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8957                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8958
8959            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8960            for (int i = 0; i < N; ++i) {
8961                intentFilters = packageServices.get(i).intents;
8962                if (intentFilters != null && intentFilters.size() > 0) {
8963                    PackageParser.ServiceIntentInfo[] array =
8964                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8965                    intentFilters.toArray(array);
8966                    listCut.add(array);
8967                }
8968            }
8969            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8970        }
8971
8972        public final void addService(PackageParser.Service s) {
8973            mServices.put(s.getComponentName(), s);
8974            if (DEBUG_SHOW_INFO) {
8975                Log.v(TAG, "  "
8976                        + (s.info.nonLocalizedLabel != null
8977                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8978                Log.v(TAG, "    Class=" + s.info.name);
8979            }
8980            final int NI = s.intents.size();
8981            int j;
8982            for (j=0; j<NI; j++) {
8983                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8984                if (DEBUG_SHOW_INFO) {
8985                    Log.v(TAG, "    IntentFilter:");
8986                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8987                }
8988                if (!intent.debugCheck()) {
8989                    Log.w(TAG, "==> For Service " + s.info.name);
8990                }
8991                addFilter(intent);
8992            }
8993        }
8994
8995        public final void removeService(PackageParser.Service s) {
8996            mServices.remove(s.getComponentName());
8997            if (DEBUG_SHOW_INFO) {
8998                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8999                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9000                Log.v(TAG, "    Class=" + s.info.name);
9001            }
9002            final int NI = s.intents.size();
9003            int j;
9004            for (j=0; j<NI; j++) {
9005                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9006                if (DEBUG_SHOW_INFO) {
9007                    Log.v(TAG, "    IntentFilter:");
9008                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9009                }
9010                removeFilter(intent);
9011            }
9012        }
9013
9014        @Override
9015        protected boolean allowFilterResult(
9016                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9017            ServiceInfo filterSi = filter.service.info;
9018            for (int i=dest.size()-1; i>=0; i--) {
9019                ServiceInfo destAi = dest.get(i).serviceInfo;
9020                if (destAi.name == filterSi.name
9021                        && destAi.packageName == filterSi.packageName) {
9022                    return false;
9023                }
9024            }
9025            return true;
9026        }
9027
9028        @Override
9029        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9030            return new PackageParser.ServiceIntentInfo[size];
9031        }
9032
9033        @Override
9034        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9035            if (!sUserManager.exists(userId)) return true;
9036            PackageParser.Package p = filter.service.owner;
9037            if (p != null) {
9038                PackageSetting ps = (PackageSetting)p.mExtras;
9039                if (ps != null) {
9040                    // System apps are never considered stopped for purposes of
9041                    // filtering, because there may be no way for the user to
9042                    // actually re-launch them.
9043                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9044                            && ps.getStopped(userId);
9045                }
9046            }
9047            return false;
9048        }
9049
9050        @Override
9051        protected boolean isPackageForFilter(String packageName,
9052                PackageParser.ServiceIntentInfo info) {
9053            return packageName.equals(info.service.owner.packageName);
9054        }
9055
9056        @Override
9057        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9058                int match, int userId) {
9059            if (!sUserManager.exists(userId)) return null;
9060            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9061            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9062                return null;
9063            }
9064            final PackageParser.Service service = info.service;
9065            if (mSafeMode && (service.info.applicationInfo.flags
9066                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9067                return null;
9068            }
9069            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9070            if (ps == null) {
9071                return null;
9072            }
9073            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9074                    ps.readUserState(userId), userId);
9075            if (si == null) {
9076                return null;
9077            }
9078            final ResolveInfo res = new ResolveInfo();
9079            res.serviceInfo = si;
9080            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9081                res.filter = filter;
9082            }
9083            res.priority = info.getPriority();
9084            res.preferredOrder = service.owner.mPreferredOrder;
9085            res.match = match;
9086            res.isDefault = info.hasDefault;
9087            res.labelRes = info.labelRes;
9088            res.nonLocalizedLabel = info.nonLocalizedLabel;
9089            res.icon = info.icon;
9090            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9091            return res;
9092        }
9093
9094        @Override
9095        protected void sortResults(List<ResolveInfo> results) {
9096            Collections.sort(results, mResolvePrioritySorter);
9097        }
9098
9099        @Override
9100        protected void dumpFilter(PrintWriter out, String prefix,
9101                PackageParser.ServiceIntentInfo filter) {
9102            out.print(prefix); out.print(
9103                    Integer.toHexString(System.identityHashCode(filter.service)));
9104                    out.print(' ');
9105                    filter.service.printComponentShortName(out);
9106                    out.print(" filter ");
9107                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9108        }
9109
9110        @Override
9111        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9112            return filter.service;
9113        }
9114
9115        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9116            PackageParser.Service service = (PackageParser.Service)label;
9117            out.print(prefix); out.print(
9118                    Integer.toHexString(System.identityHashCode(service)));
9119                    out.print(' ');
9120                    service.printComponentShortName(out);
9121            if (count > 1) {
9122                out.print(" ("); out.print(count); out.print(" filters)");
9123            }
9124            out.println();
9125        }
9126
9127//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9128//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9129//            final List<ResolveInfo> retList = Lists.newArrayList();
9130//            while (i.hasNext()) {
9131//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9132//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9133//                    retList.add(resolveInfo);
9134//                }
9135//            }
9136//            return retList;
9137//        }
9138
9139        // Keys are String (activity class name), values are Activity.
9140        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9141                = new ArrayMap<ComponentName, PackageParser.Service>();
9142        private int mFlags;
9143    };
9144
9145    private final class ProviderIntentResolver
9146            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9147        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9148                boolean defaultOnly, int userId) {
9149            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9150            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9151        }
9152
9153        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9154                int userId) {
9155            if (!sUserManager.exists(userId))
9156                return null;
9157            mFlags = flags;
9158            return super.queryIntent(intent, resolvedType,
9159                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9160        }
9161
9162        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9163                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9164            if (!sUserManager.exists(userId))
9165                return null;
9166            if (packageProviders == null) {
9167                return null;
9168            }
9169            mFlags = flags;
9170            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9171            final int N = packageProviders.size();
9172            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9173                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9174
9175            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9176            for (int i = 0; i < N; ++i) {
9177                intentFilters = packageProviders.get(i).intents;
9178                if (intentFilters != null && intentFilters.size() > 0) {
9179                    PackageParser.ProviderIntentInfo[] array =
9180                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9181                    intentFilters.toArray(array);
9182                    listCut.add(array);
9183                }
9184            }
9185            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9186        }
9187
9188        public final void addProvider(PackageParser.Provider p) {
9189            if (mProviders.containsKey(p.getComponentName())) {
9190                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9191                return;
9192            }
9193
9194            mProviders.put(p.getComponentName(), p);
9195            if (DEBUG_SHOW_INFO) {
9196                Log.v(TAG, "  "
9197                        + (p.info.nonLocalizedLabel != null
9198                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9199                Log.v(TAG, "    Class=" + p.info.name);
9200            }
9201            final int NI = p.intents.size();
9202            int j;
9203            for (j = 0; j < NI; j++) {
9204                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9205                if (DEBUG_SHOW_INFO) {
9206                    Log.v(TAG, "    IntentFilter:");
9207                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9208                }
9209                if (!intent.debugCheck()) {
9210                    Log.w(TAG, "==> For Provider " + p.info.name);
9211                }
9212                addFilter(intent);
9213            }
9214        }
9215
9216        public final void removeProvider(PackageParser.Provider p) {
9217            mProviders.remove(p.getComponentName());
9218            if (DEBUG_SHOW_INFO) {
9219                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9220                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9221                Log.v(TAG, "    Class=" + p.info.name);
9222            }
9223            final int NI = p.intents.size();
9224            int j;
9225            for (j = 0; j < NI; j++) {
9226                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9227                if (DEBUG_SHOW_INFO) {
9228                    Log.v(TAG, "    IntentFilter:");
9229                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9230                }
9231                removeFilter(intent);
9232            }
9233        }
9234
9235        @Override
9236        protected boolean allowFilterResult(
9237                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9238            ProviderInfo filterPi = filter.provider.info;
9239            for (int i = dest.size() - 1; i >= 0; i--) {
9240                ProviderInfo destPi = dest.get(i).providerInfo;
9241                if (destPi.name == filterPi.name
9242                        && destPi.packageName == filterPi.packageName) {
9243                    return false;
9244                }
9245            }
9246            return true;
9247        }
9248
9249        @Override
9250        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9251            return new PackageParser.ProviderIntentInfo[size];
9252        }
9253
9254        @Override
9255        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9256            if (!sUserManager.exists(userId))
9257                return true;
9258            PackageParser.Package p = filter.provider.owner;
9259            if (p != null) {
9260                PackageSetting ps = (PackageSetting) p.mExtras;
9261                if (ps != null) {
9262                    // System apps are never considered stopped for purposes of
9263                    // filtering, because there may be no way for the user to
9264                    // actually re-launch them.
9265                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9266                            && ps.getStopped(userId);
9267                }
9268            }
9269            return false;
9270        }
9271
9272        @Override
9273        protected boolean isPackageForFilter(String packageName,
9274                PackageParser.ProviderIntentInfo info) {
9275            return packageName.equals(info.provider.owner.packageName);
9276        }
9277
9278        @Override
9279        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9280                int match, int userId) {
9281            if (!sUserManager.exists(userId))
9282                return null;
9283            final PackageParser.ProviderIntentInfo info = filter;
9284            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9285                return null;
9286            }
9287            final PackageParser.Provider provider = info.provider;
9288            if (mSafeMode && (provider.info.applicationInfo.flags
9289                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9290                return null;
9291            }
9292            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9293            if (ps == null) {
9294                return null;
9295            }
9296            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9297                    ps.readUserState(userId), userId);
9298            if (pi == null) {
9299                return null;
9300            }
9301            final ResolveInfo res = new ResolveInfo();
9302            res.providerInfo = pi;
9303            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9304                res.filter = filter;
9305            }
9306            res.priority = info.getPriority();
9307            res.preferredOrder = provider.owner.mPreferredOrder;
9308            res.match = match;
9309            res.isDefault = info.hasDefault;
9310            res.labelRes = info.labelRes;
9311            res.nonLocalizedLabel = info.nonLocalizedLabel;
9312            res.icon = info.icon;
9313            res.system = res.providerInfo.applicationInfo.isSystemApp();
9314            return res;
9315        }
9316
9317        @Override
9318        protected void sortResults(List<ResolveInfo> results) {
9319            Collections.sort(results, mResolvePrioritySorter);
9320        }
9321
9322        @Override
9323        protected void dumpFilter(PrintWriter out, String prefix,
9324                PackageParser.ProviderIntentInfo filter) {
9325            out.print(prefix);
9326            out.print(
9327                    Integer.toHexString(System.identityHashCode(filter.provider)));
9328            out.print(' ');
9329            filter.provider.printComponentShortName(out);
9330            out.print(" filter ");
9331            out.println(Integer.toHexString(System.identityHashCode(filter)));
9332        }
9333
9334        @Override
9335        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9336            return filter.provider;
9337        }
9338
9339        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9340            PackageParser.Provider provider = (PackageParser.Provider)label;
9341            out.print(prefix); out.print(
9342                    Integer.toHexString(System.identityHashCode(provider)));
9343                    out.print(' ');
9344                    provider.printComponentShortName(out);
9345            if (count > 1) {
9346                out.print(" ("); out.print(count); out.print(" filters)");
9347            }
9348            out.println();
9349        }
9350
9351        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9352                = new ArrayMap<ComponentName, PackageParser.Provider>();
9353        private int mFlags;
9354    };
9355
9356    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9357            new Comparator<ResolveInfo>() {
9358        public int compare(ResolveInfo r1, ResolveInfo r2) {
9359            int v1 = r1.priority;
9360            int v2 = r2.priority;
9361            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9362            if (v1 != v2) {
9363                return (v1 > v2) ? -1 : 1;
9364            }
9365            v1 = r1.preferredOrder;
9366            v2 = r2.preferredOrder;
9367            if (v1 != v2) {
9368                return (v1 > v2) ? -1 : 1;
9369            }
9370            if (r1.isDefault != r2.isDefault) {
9371                return r1.isDefault ? -1 : 1;
9372            }
9373            v1 = r1.match;
9374            v2 = r2.match;
9375            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9376            if (v1 != v2) {
9377                return (v1 > v2) ? -1 : 1;
9378            }
9379            if (r1.system != r2.system) {
9380                return r1.system ? -1 : 1;
9381            }
9382            return 0;
9383        }
9384    };
9385
9386    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9387            new Comparator<ProviderInfo>() {
9388        public int compare(ProviderInfo p1, ProviderInfo p2) {
9389            final int v1 = p1.initOrder;
9390            final int v2 = p2.initOrder;
9391            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9392        }
9393    };
9394
9395    final void sendPackageBroadcast(final String action, final String pkg,
9396            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9397            final int[] userIds) {
9398        mHandler.post(new Runnable() {
9399            @Override
9400            public void run() {
9401                try {
9402                    final IActivityManager am = ActivityManagerNative.getDefault();
9403                    if (am == null) return;
9404                    final int[] resolvedUserIds;
9405                    if (userIds == null) {
9406                        resolvedUserIds = am.getRunningUserIds();
9407                    } else {
9408                        resolvedUserIds = userIds;
9409                    }
9410                    for (int id : resolvedUserIds) {
9411                        final Intent intent = new Intent(action,
9412                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9413                        if (extras != null) {
9414                            intent.putExtras(extras);
9415                        }
9416                        if (targetPkg != null) {
9417                            intent.setPackage(targetPkg);
9418                        }
9419                        // Modify the UID when posting to other users
9420                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9421                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9422                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9423                            intent.putExtra(Intent.EXTRA_UID, uid);
9424                        }
9425                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9426                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9427                        if (DEBUG_BROADCASTS) {
9428                            RuntimeException here = new RuntimeException("here");
9429                            here.fillInStackTrace();
9430                            Slog.d(TAG, "Sending to user " + id + ": "
9431                                    + intent.toShortString(false, true, false, false)
9432                                    + " " + intent.getExtras(), here);
9433                        }
9434                        am.broadcastIntent(null, intent, null, finishedReceiver,
9435                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9436                                null, finishedReceiver != null, false, id);
9437                    }
9438                } catch (RemoteException ex) {
9439                }
9440            }
9441        });
9442    }
9443
9444    /**
9445     * Check if the external storage media is available. This is true if there
9446     * is a mounted external storage medium or if the external storage is
9447     * emulated.
9448     */
9449    private boolean isExternalMediaAvailable() {
9450        return mMediaMounted || Environment.isExternalStorageEmulated();
9451    }
9452
9453    @Override
9454    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9455        // writer
9456        synchronized (mPackages) {
9457            if (!isExternalMediaAvailable()) {
9458                // If the external storage is no longer mounted at this point,
9459                // the caller may not have been able to delete all of this
9460                // packages files and can not delete any more.  Bail.
9461                return null;
9462            }
9463            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9464            if (lastPackage != null) {
9465                pkgs.remove(lastPackage);
9466            }
9467            if (pkgs.size() > 0) {
9468                return pkgs.get(0);
9469            }
9470        }
9471        return null;
9472    }
9473
9474    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9475        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9476                userId, andCode ? 1 : 0, packageName);
9477        if (mSystemReady) {
9478            msg.sendToTarget();
9479        } else {
9480            if (mPostSystemReadyMessages == null) {
9481                mPostSystemReadyMessages = new ArrayList<>();
9482            }
9483            mPostSystemReadyMessages.add(msg);
9484        }
9485    }
9486
9487    void startCleaningPackages() {
9488        // reader
9489        synchronized (mPackages) {
9490            if (!isExternalMediaAvailable()) {
9491                return;
9492            }
9493            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9494                return;
9495            }
9496        }
9497        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9498        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9499        IActivityManager am = ActivityManagerNative.getDefault();
9500        if (am != null) {
9501            try {
9502                am.startService(null, intent, null, mContext.getOpPackageName(),
9503                        UserHandle.USER_OWNER);
9504            } catch (RemoteException e) {
9505            }
9506        }
9507    }
9508
9509    @Override
9510    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9511            int installFlags, String installerPackageName, VerificationParams verificationParams,
9512            String packageAbiOverride) {
9513        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9514                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9515    }
9516
9517    @Override
9518    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9519            int installFlags, String installerPackageName, VerificationParams verificationParams,
9520            String packageAbiOverride, int userId) {
9521        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9522
9523        final int callingUid = Binder.getCallingUid();
9524        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9525
9526        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9527            try {
9528                if (observer != null) {
9529                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9530                }
9531            } catch (RemoteException re) {
9532            }
9533            return;
9534        }
9535
9536        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9537            installFlags |= PackageManager.INSTALL_FROM_ADB;
9538
9539        } else {
9540            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9541            // about installerPackageName.
9542
9543            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9544            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9545        }
9546
9547        UserHandle user;
9548        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9549            user = UserHandle.ALL;
9550        } else {
9551            user = new UserHandle(userId);
9552        }
9553
9554        // Only system components can circumvent runtime permissions when installing.
9555        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9556                && mContext.checkCallingOrSelfPermission(Manifest.permission
9557                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9558            throw new SecurityException("You need the "
9559                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9560                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9561        }
9562
9563        verificationParams.setInstallerUid(callingUid);
9564
9565        final File originFile = new File(originPath);
9566        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9567
9568        final Message msg = mHandler.obtainMessage(INIT_COPY);
9569        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
9570                null, verificationParams, user, packageAbiOverride, null);
9571        mHandler.sendMessage(msg);
9572    }
9573
9574    void installStage(String packageName, File stagedDir, String stagedCid,
9575            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
9576            String installerPackageName, int installerUid, UserHandle user) {
9577        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
9578                params.referrerUri, installerUid, null);
9579        verifParams.setInstallerUid(installerUid);
9580
9581        final OriginInfo origin;
9582        if (stagedDir != null) {
9583            origin = OriginInfo.fromStagedFile(stagedDir);
9584        } else {
9585            origin = OriginInfo.fromStagedContainer(stagedCid);
9586        }
9587
9588        final Message msg = mHandler.obtainMessage(INIT_COPY);
9589        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
9590                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,
9591                params.grantedRuntimePermissions);
9592        mHandler.sendMessage(msg);
9593    }
9594
9595    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9596        Bundle extras = new Bundle(1);
9597        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9598
9599        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9600                packageName, extras, null, null, new int[] {userId});
9601        try {
9602            IActivityManager am = ActivityManagerNative.getDefault();
9603            final boolean isSystem =
9604                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9605            if (isSystem && am.isUserRunning(userId, false)) {
9606                // The just-installed/enabled app is bundled on the system, so presumed
9607                // to be able to run automatically without needing an explicit launch.
9608                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9609                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9610                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9611                        .setPackage(packageName);
9612                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9613                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9614            }
9615        } catch (RemoteException e) {
9616            // shouldn't happen
9617            Slog.w(TAG, "Unable to bootstrap installed package", e);
9618        }
9619    }
9620
9621    @Override
9622    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9623            int userId) {
9624        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9625        PackageSetting pkgSetting;
9626        final int uid = Binder.getCallingUid();
9627        enforceCrossUserPermission(uid, userId, true, true,
9628                "setApplicationHiddenSetting for user " + userId);
9629
9630        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9631            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9632            return false;
9633        }
9634
9635        long callingId = Binder.clearCallingIdentity();
9636        try {
9637            boolean sendAdded = false;
9638            boolean sendRemoved = false;
9639            // writer
9640            synchronized (mPackages) {
9641                pkgSetting = mSettings.mPackages.get(packageName);
9642                if (pkgSetting == null) {
9643                    return false;
9644                }
9645                if (pkgSetting.getHidden(userId) != hidden) {
9646                    pkgSetting.setHidden(hidden, userId);
9647                    mSettings.writePackageRestrictionsLPr(userId);
9648                    if (hidden) {
9649                        sendRemoved = true;
9650                    } else {
9651                        sendAdded = true;
9652                    }
9653                }
9654            }
9655            if (sendAdded) {
9656                sendPackageAddedForUser(packageName, pkgSetting, userId);
9657                return true;
9658            }
9659            if (sendRemoved) {
9660                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9661                        "hiding pkg");
9662                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9663                return true;
9664            }
9665        } finally {
9666            Binder.restoreCallingIdentity(callingId);
9667        }
9668        return false;
9669    }
9670
9671    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9672            int userId) {
9673        final PackageRemovedInfo info = new PackageRemovedInfo();
9674        info.removedPackage = packageName;
9675        info.removedUsers = new int[] {userId};
9676        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9677        info.sendBroadcast(false, false, false);
9678    }
9679
9680    /**
9681     * Returns true if application is not found or there was an error. Otherwise it returns
9682     * the hidden state of the package for the given user.
9683     */
9684    @Override
9685    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9686        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9687        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9688                false, "getApplicationHidden for user " + userId);
9689        PackageSetting pkgSetting;
9690        long callingId = Binder.clearCallingIdentity();
9691        try {
9692            // writer
9693            synchronized (mPackages) {
9694                pkgSetting = mSettings.mPackages.get(packageName);
9695                if (pkgSetting == null) {
9696                    return true;
9697                }
9698                return pkgSetting.getHidden(userId);
9699            }
9700        } finally {
9701            Binder.restoreCallingIdentity(callingId);
9702        }
9703    }
9704
9705    /**
9706     * @hide
9707     */
9708    @Override
9709    public int installExistingPackageAsUser(String packageName, int userId) {
9710        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9711                null);
9712        PackageSetting pkgSetting;
9713        final int uid = Binder.getCallingUid();
9714        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9715                + userId);
9716        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9717            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9718        }
9719
9720        long callingId = Binder.clearCallingIdentity();
9721        try {
9722            boolean sendAdded = false;
9723
9724            // writer
9725            synchronized (mPackages) {
9726                pkgSetting = mSettings.mPackages.get(packageName);
9727                if (pkgSetting == null) {
9728                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9729                }
9730                if (!pkgSetting.getInstalled(userId)) {
9731                    pkgSetting.setInstalled(true, userId);
9732                    pkgSetting.setHidden(false, userId);
9733                    mSettings.writePackageRestrictionsLPr(userId);
9734                    sendAdded = true;
9735                }
9736            }
9737
9738            if (sendAdded) {
9739                sendPackageAddedForUser(packageName, pkgSetting, userId);
9740            }
9741        } finally {
9742            Binder.restoreCallingIdentity(callingId);
9743        }
9744
9745        return PackageManager.INSTALL_SUCCEEDED;
9746    }
9747
9748    boolean isUserRestricted(int userId, String restrictionKey) {
9749        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9750        if (restrictions.getBoolean(restrictionKey, false)) {
9751            Log.w(TAG, "User is restricted: " + restrictionKey);
9752            return true;
9753        }
9754        return false;
9755    }
9756
9757    @Override
9758    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9759        mContext.enforceCallingOrSelfPermission(
9760                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9761                "Only package verification agents can verify applications");
9762
9763        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9764        final PackageVerificationResponse response = new PackageVerificationResponse(
9765                verificationCode, Binder.getCallingUid());
9766        msg.arg1 = id;
9767        msg.obj = response;
9768        mHandler.sendMessage(msg);
9769    }
9770
9771    @Override
9772    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9773            long millisecondsToDelay) {
9774        mContext.enforceCallingOrSelfPermission(
9775                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9776                "Only package verification agents can extend verification timeouts");
9777
9778        final PackageVerificationState state = mPendingVerification.get(id);
9779        final PackageVerificationResponse response = new PackageVerificationResponse(
9780                verificationCodeAtTimeout, Binder.getCallingUid());
9781
9782        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9783            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9784        }
9785        if (millisecondsToDelay < 0) {
9786            millisecondsToDelay = 0;
9787        }
9788        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9789                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9790            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9791        }
9792
9793        if ((state != null) && !state.timeoutExtended()) {
9794            state.extendTimeout();
9795
9796            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9797            msg.arg1 = id;
9798            msg.obj = response;
9799            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9800        }
9801    }
9802
9803    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9804            int verificationCode, UserHandle user) {
9805        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9806        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9807        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9808        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9809        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9810
9811        mContext.sendBroadcastAsUser(intent, user,
9812                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9813    }
9814
9815    private ComponentName matchComponentForVerifier(String packageName,
9816            List<ResolveInfo> receivers) {
9817        ActivityInfo targetReceiver = null;
9818
9819        final int NR = receivers.size();
9820        for (int i = 0; i < NR; i++) {
9821            final ResolveInfo info = receivers.get(i);
9822            if (info.activityInfo == null) {
9823                continue;
9824            }
9825
9826            if (packageName.equals(info.activityInfo.packageName)) {
9827                targetReceiver = info.activityInfo;
9828                break;
9829            }
9830        }
9831
9832        if (targetReceiver == null) {
9833            return null;
9834        }
9835
9836        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9837    }
9838
9839    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9840            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9841        if (pkgInfo.verifiers.length == 0) {
9842            return null;
9843        }
9844
9845        final int N = pkgInfo.verifiers.length;
9846        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9847        for (int i = 0; i < N; i++) {
9848            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9849
9850            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9851                    receivers);
9852            if (comp == null) {
9853                continue;
9854            }
9855
9856            final int verifierUid = getUidForVerifier(verifierInfo);
9857            if (verifierUid == -1) {
9858                continue;
9859            }
9860
9861            if (DEBUG_VERIFY) {
9862                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9863                        + " with the correct signature");
9864            }
9865            sufficientVerifiers.add(comp);
9866            verificationState.addSufficientVerifier(verifierUid);
9867        }
9868
9869        return sufficientVerifiers;
9870    }
9871
9872    private int getUidForVerifier(VerifierInfo verifierInfo) {
9873        synchronized (mPackages) {
9874            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9875            if (pkg == null) {
9876                return -1;
9877            } else if (pkg.mSignatures.length != 1) {
9878                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9879                        + " has more than one signature; ignoring");
9880                return -1;
9881            }
9882
9883            /*
9884             * If the public key of the package's signature does not match
9885             * our expected public key, then this is a different package and
9886             * we should skip.
9887             */
9888
9889            final byte[] expectedPublicKey;
9890            try {
9891                final Signature verifierSig = pkg.mSignatures[0];
9892                final PublicKey publicKey = verifierSig.getPublicKey();
9893                expectedPublicKey = publicKey.getEncoded();
9894            } catch (CertificateException e) {
9895                return -1;
9896            }
9897
9898            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9899
9900            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9901                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9902                        + " does not have the expected public key; ignoring");
9903                return -1;
9904            }
9905
9906            return pkg.applicationInfo.uid;
9907        }
9908    }
9909
9910    @Override
9911    public void finishPackageInstall(int token) {
9912        enforceSystemOrRoot("Only the system is allowed to finish installs");
9913
9914        if (DEBUG_INSTALL) {
9915            Slog.v(TAG, "BM finishing package install for " + token);
9916        }
9917
9918        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9919        mHandler.sendMessage(msg);
9920    }
9921
9922    /**
9923     * Get the verification agent timeout.
9924     *
9925     * @return verification timeout in milliseconds
9926     */
9927    private long getVerificationTimeout() {
9928        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9929                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9930                DEFAULT_VERIFICATION_TIMEOUT);
9931    }
9932
9933    /**
9934     * Get the default verification agent response code.
9935     *
9936     * @return default verification response code
9937     */
9938    private int getDefaultVerificationResponse() {
9939        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9940                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9941                DEFAULT_VERIFICATION_RESPONSE);
9942    }
9943
9944    /**
9945     * Check whether or not package verification has been enabled.
9946     *
9947     * @return true if verification should be performed
9948     */
9949    private boolean isVerificationEnabled(int userId, int installFlags) {
9950        if (!DEFAULT_VERIFY_ENABLE) {
9951            return false;
9952        }
9953
9954        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9955
9956        // Check if installing from ADB
9957        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9958            // Do not run verification in a test harness environment
9959            if (ActivityManager.isRunningInTestHarness()) {
9960                return false;
9961            }
9962            if (ensureVerifyAppsEnabled) {
9963                return true;
9964            }
9965            // Check if the developer does not want package verification for ADB installs
9966            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9967                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9968                return false;
9969            }
9970        }
9971
9972        if (ensureVerifyAppsEnabled) {
9973            return true;
9974        }
9975
9976        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9977                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9978    }
9979
9980    @Override
9981    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9982            throws RemoteException {
9983        mContext.enforceCallingOrSelfPermission(
9984                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9985                "Only intentfilter verification agents can verify applications");
9986
9987        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9988        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9989                Binder.getCallingUid(), verificationCode, failedDomains);
9990        msg.arg1 = id;
9991        msg.obj = response;
9992        mHandler.sendMessage(msg);
9993    }
9994
9995    @Override
9996    public int getIntentVerificationStatus(String packageName, int userId) {
9997        synchronized (mPackages) {
9998            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9999        }
10000    }
10001
10002    @Override
10003    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10004        mContext.enforceCallingOrSelfPermission(
10005                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10006
10007        boolean result = false;
10008        synchronized (mPackages) {
10009            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10010        }
10011        if (result) {
10012            scheduleWritePackageRestrictionsLocked(userId);
10013        }
10014        return result;
10015    }
10016
10017    @Override
10018    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10019        synchronized (mPackages) {
10020            return mSettings.getIntentFilterVerificationsLPr(packageName);
10021        }
10022    }
10023
10024    @Override
10025    public List<IntentFilter> getAllIntentFilters(String packageName) {
10026        if (TextUtils.isEmpty(packageName)) {
10027            return Collections.<IntentFilter>emptyList();
10028        }
10029        synchronized (mPackages) {
10030            PackageParser.Package pkg = mPackages.get(packageName);
10031            if (pkg == null || pkg.activities == null) {
10032                return Collections.<IntentFilter>emptyList();
10033            }
10034            final int count = pkg.activities.size();
10035            ArrayList<IntentFilter> result = new ArrayList<>();
10036            for (int n=0; n<count; n++) {
10037                PackageParser.Activity activity = pkg.activities.get(n);
10038                if (activity.intents != null || activity.intents.size() > 0) {
10039                    result.addAll(activity.intents);
10040                }
10041            }
10042            return result;
10043        }
10044    }
10045
10046    @Override
10047    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10048        mContext.enforceCallingOrSelfPermission(
10049                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10050
10051        synchronized (mPackages) {
10052            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10053            if (packageName != null) {
10054                result |= updateIntentVerificationStatus(packageName,
10055                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10056                        userId);
10057                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10058                        packageName, userId);
10059            }
10060            return result;
10061        }
10062    }
10063
10064    @Override
10065    public String getDefaultBrowserPackageName(int userId) {
10066        synchronized (mPackages) {
10067            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10068        }
10069    }
10070
10071    /**
10072     * Get the "allow unknown sources" setting.
10073     *
10074     * @return the current "allow unknown sources" setting
10075     */
10076    private int getUnknownSourcesSettings() {
10077        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10078                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10079                -1);
10080    }
10081
10082    @Override
10083    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10084        final int uid = Binder.getCallingUid();
10085        // writer
10086        synchronized (mPackages) {
10087            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10088            if (targetPackageSetting == null) {
10089                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10090            }
10091
10092            PackageSetting installerPackageSetting;
10093            if (installerPackageName != null) {
10094                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10095                if (installerPackageSetting == null) {
10096                    throw new IllegalArgumentException("Unknown installer package: "
10097                            + installerPackageName);
10098                }
10099            } else {
10100                installerPackageSetting = null;
10101            }
10102
10103            Signature[] callerSignature;
10104            Object obj = mSettings.getUserIdLPr(uid);
10105            if (obj != null) {
10106                if (obj instanceof SharedUserSetting) {
10107                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10108                } else if (obj instanceof PackageSetting) {
10109                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10110                } else {
10111                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10112                }
10113            } else {
10114                throw new SecurityException("Unknown calling uid " + uid);
10115            }
10116
10117            // Verify: can't set installerPackageName to a package that is
10118            // not signed with the same cert as the caller.
10119            if (installerPackageSetting != null) {
10120                if (compareSignatures(callerSignature,
10121                        installerPackageSetting.signatures.mSignatures)
10122                        != PackageManager.SIGNATURE_MATCH) {
10123                    throw new SecurityException(
10124                            "Caller does not have same cert as new installer package "
10125                            + installerPackageName);
10126                }
10127            }
10128
10129            // Verify: if target already has an installer package, it must
10130            // be signed with the same cert as the caller.
10131            if (targetPackageSetting.installerPackageName != null) {
10132                PackageSetting setting = mSettings.mPackages.get(
10133                        targetPackageSetting.installerPackageName);
10134                // If the currently set package isn't valid, then it's always
10135                // okay to change it.
10136                if (setting != null) {
10137                    if (compareSignatures(callerSignature,
10138                            setting.signatures.mSignatures)
10139                            != PackageManager.SIGNATURE_MATCH) {
10140                        throw new SecurityException(
10141                                "Caller does not have same cert as old installer package "
10142                                + targetPackageSetting.installerPackageName);
10143                    }
10144                }
10145            }
10146
10147            // Okay!
10148            targetPackageSetting.installerPackageName = installerPackageName;
10149            scheduleWriteSettingsLocked();
10150        }
10151    }
10152
10153    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10154        // Queue up an async operation since the package installation may take a little while.
10155        mHandler.post(new Runnable() {
10156            public void run() {
10157                mHandler.removeCallbacks(this);
10158                 // Result object to be returned
10159                PackageInstalledInfo res = new PackageInstalledInfo();
10160                res.returnCode = currentStatus;
10161                res.uid = -1;
10162                res.pkg = null;
10163                res.removedInfo = new PackageRemovedInfo();
10164                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10165                    args.doPreInstall(res.returnCode);
10166                    synchronized (mInstallLock) {
10167                        installPackageLI(args, res);
10168                    }
10169                    args.doPostInstall(res.returnCode, res.uid);
10170                }
10171
10172                // A restore should be performed at this point if (a) the install
10173                // succeeded, (b) the operation is not an update, and (c) the new
10174                // package has not opted out of backup participation.
10175                final boolean update = res.removedInfo.removedPackage != null;
10176                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10177                boolean doRestore = !update
10178                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10179
10180                // Set up the post-install work request bookkeeping.  This will be used
10181                // and cleaned up by the post-install event handling regardless of whether
10182                // there's a restore pass performed.  Token values are >= 1.
10183                int token;
10184                if (mNextInstallToken < 0) mNextInstallToken = 1;
10185                token = mNextInstallToken++;
10186
10187                PostInstallData data = new PostInstallData(args, res);
10188                mRunningInstalls.put(token, data);
10189                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10190
10191                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10192                    // Pass responsibility to the Backup Manager.  It will perform a
10193                    // restore if appropriate, then pass responsibility back to the
10194                    // Package Manager to run the post-install observer callbacks
10195                    // and broadcasts.
10196                    IBackupManager bm = IBackupManager.Stub.asInterface(
10197                            ServiceManager.getService(Context.BACKUP_SERVICE));
10198                    if (bm != null) {
10199                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10200                                + " to BM for possible restore");
10201                        try {
10202                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
10203                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10204                            } else {
10205                                doRestore = false;
10206                            }
10207                        } catch (RemoteException e) {
10208                            // can't happen; the backup manager is local
10209                        } catch (Exception e) {
10210                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10211                            doRestore = false;
10212                        }
10213                    } else {
10214                        Slog.e(TAG, "Backup Manager not found!");
10215                        doRestore = false;
10216                    }
10217                }
10218
10219                if (!doRestore) {
10220                    // No restore possible, or the Backup Manager was mysteriously not
10221                    // available -- just fire the post-install work request directly.
10222                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10223                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10224                    mHandler.sendMessage(msg);
10225                }
10226            }
10227        });
10228    }
10229
10230    private abstract class HandlerParams {
10231        private static final int MAX_RETRIES = 4;
10232
10233        /**
10234         * Number of times startCopy() has been attempted and had a non-fatal
10235         * error.
10236         */
10237        private int mRetries = 0;
10238
10239        /** User handle for the user requesting the information or installation. */
10240        private final UserHandle mUser;
10241
10242        HandlerParams(UserHandle user) {
10243            mUser = user;
10244        }
10245
10246        UserHandle getUser() {
10247            return mUser;
10248        }
10249
10250        final boolean startCopy() {
10251            boolean res;
10252            try {
10253                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10254
10255                if (++mRetries > MAX_RETRIES) {
10256                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10257                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10258                    handleServiceError();
10259                    return false;
10260                } else {
10261                    handleStartCopy();
10262                    res = true;
10263                }
10264            } catch (RemoteException e) {
10265                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10266                mHandler.sendEmptyMessage(MCS_RECONNECT);
10267                res = false;
10268            }
10269            handleReturnCode();
10270            return res;
10271        }
10272
10273        final void serviceError() {
10274            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10275            handleServiceError();
10276            handleReturnCode();
10277        }
10278
10279        abstract void handleStartCopy() throws RemoteException;
10280        abstract void handleServiceError();
10281        abstract void handleReturnCode();
10282    }
10283
10284    class MeasureParams extends HandlerParams {
10285        private final PackageStats mStats;
10286        private boolean mSuccess;
10287
10288        private final IPackageStatsObserver mObserver;
10289
10290        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10291            super(new UserHandle(stats.userHandle));
10292            mObserver = observer;
10293            mStats = stats;
10294        }
10295
10296        @Override
10297        public String toString() {
10298            return "MeasureParams{"
10299                + Integer.toHexString(System.identityHashCode(this))
10300                + " " + mStats.packageName + "}";
10301        }
10302
10303        @Override
10304        void handleStartCopy() throws RemoteException {
10305            synchronized (mInstallLock) {
10306                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10307            }
10308
10309            if (mSuccess) {
10310                final boolean mounted;
10311                if (Environment.isExternalStorageEmulated()) {
10312                    mounted = true;
10313                } else {
10314                    final String status = Environment.getExternalStorageState();
10315                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10316                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10317                }
10318
10319                if (mounted) {
10320                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10321
10322                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10323                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10324
10325                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10326                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10327
10328                    // Always subtract cache size, since it's a subdirectory
10329                    mStats.externalDataSize -= mStats.externalCacheSize;
10330
10331                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10332                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10333
10334                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10335                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10336                }
10337            }
10338        }
10339
10340        @Override
10341        void handleReturnCode() {
10342            if (mObserver != null) {
10343                try {
10344                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10345                } catch (RemoteException e) {
10346                    Slog.i(TAG, "Observer no longer exists.");
10347                }
10348            }
10349        }
10350
10351        @Override
10352        void handleServiceError() {
10353            Slog.e(TAG, "Could not measure application " + mStats.packageName
10354                            + " external storage");
10355        }
10356    }
10357
10358    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10359            throws RemoteException {
10360        long result = 0;
10361        for (File path : paths) {
10362            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10363        }
10364        return result;
10365    }
10366
10367    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10368        for (File path : paths) {
10369            try {
10370                mcs.clearDirectory(path.getAbsolutePath());
10371            } catch (RemoteException e) {
10372            }
10373        }
10374    }
10375
10376    static class OriginInfo {
10377        /**
10378         * Location where install is coming from, before it has been
10379         * copied/renamed into place. This could be a single monolithic APK
10380         * file, or a cluster directory. This location may be untrusted.
10381         */
10382        final File file;
10383        final String cid;
10384
10385        /**
10386         * Flag indicating that {@link #file} or {@link #cid} has already been
10387         * staged, meaning downstream users don't need to defensively copy the
10388         * contents.
10389         */
10390        final boolean staged;
10391
10392        /**
10393         * Flag indicating that {@link #file} or {@link #cid} is an already
10394         * installed app that is being moved.
10395         */
10396        final boolean existing;
10397
10398        final String resolvedPath;
10399        final File resolvedFile;
10400
10401        static OriginInfo fromNothing() {
10402            return new OriginInfo(null, null, false, false);
10403        }
10404
10405        static OriginInfo fromUntrustedFile(File file) {
10406            return new OriginInfo(file, null, false, false);
10407        }
10408
10409        static OriginInfo fromExistingFile(File file) {
10410            return new OriginInfo(file, null, false, true);
10411        }
10412
10413        static OriginInfo fromStagedFile(File file) {
10414            return new OriginInfo(file, null, true, false);
10415        }
10416
10417        static OriginInfo fromStagedContainer(String cid) {
10418            return new OriginInfo(null, cid, true, false);
10419        }
10420
10421        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10422            this.file = file;
10423            this.cid = cid;
10424            this.staged = staged;
10425            this.existing = existing;
10426
10427            if (cid != null) {
10428                resolvedPath = PackageHelper.getSdDir(cid);
10429                resolvedFile = new File(resolvedPath);
10430            } else if (file != null) {
10431                resolvedPath = file.getAbsolutePath();
10432                resolvedFile = file;
10433            } else {
10434                resolvedPath = null;
10435                resolvedFile = null;
10436            }
10437        }
10438    }
10439
10440    class MoveInfo {
10441        final int moveId;
10442        final String fromUuid;
10443        final String toUuid;
10444        final String packageName;
10445        final String dataAppName;
10446        final int appId;
10447        final String seinfo;
10448
10449        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10450                String dataAppName, int appId, String seinfo) {
10451            this.moveId = moveId;
10452            this.fromUuid = fromUuid;
10453            this.toUuid = toUuid;
10454            this.packageName = packageName;
10455            this.dataAppName = dataAppName;
10456            this.appId = appId;
10457            this.seinfo = seinfo;
10458        }
10459    }
10460
10461    class InstallParams extends HandlerParams {
10462        final OriginInfo origin;
10463        final MoveInfo move;
10464        final IPackageInstallObserver2 observer;
10465        int installFlags;
10466        final String installerPackageName;
10467        final String volumeUuid;
10468        final VerificationParams verificationParams;
10469        private InstallArgs mArgs;
10470        private int mRet;
10471        final String packageAbiOverride;
10472        final String[] grantedRuntimePermissions;
10473
10474
10475        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10476                int installFlags, String installerPackageName, String volumeUuid,
10477                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10478                String[] grantedPermissions) {
10479            super(user);
10480            this.origin = origin;
10481            this.move = move;
10482            this.observer = observer;
10483            this.installFlags = installFlags;
10484            this.installerPackageName = installerPackageName;
10485            this.volumeUuid = volumeUuid;
10486            this.verificationParams = verificationParams;
10487            this.packageAbiOverride = packageAbiOverride;
10488            this.grantedRuntimePermissions = grantedPermissions;
10489        }
10490
10491        @Override
10492        public String toString() {
10493            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10494                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10495        }
10496
10497        public ManifestDigest getManifestDigest() {
10498            if (verificationParams == null) {
10499                return null;
10500            }
10501            return verificationParams.getManifestDigest();
10502        }
10503
10504        private int installLocationPolicy(PackageInfoLite pkgLite) {
10505            String packageName = pkgLite.packageName;
10506            int installLocation = pkgLite.installLocation;
10507            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10508            // reader
10509            synchronized (mPackages) {
10510                PackageParser.Package pkg = mPackages.get(packageName);
10511                if (pkg != null) {
10512                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10513                        // Check for downgrading.
10514                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10515                            try {
10516                                checkDowngrade(pkg, pkgLite);
10517                            } catch (PackageManagerException e) {
10518                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10519                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10520                            }
10521                        }
10522                        // Check for updated system application.
10523                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10524                            if (onSd) {
10525                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10526                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10527                            }
10528                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10529                        } else {
10530                            if (onSd) {
10531                                // Install flag overrides everything.
10532                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10533                            }
10534                            // If current upgrade specifies particular preference
10535                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10536                                // Application explicitly specified internal.
10537                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10538                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10539                                // App explictly prefers external. Let policy decide
10540                            } else {
10541                                // Prefer previous location
10542                                if (isExternal(pkg)) {
10543                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10544                                }
10545                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10546                            }
10547                        }
10548                    } else {
10549                        // Invalid install. Return error code
10550                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10551                    }
10552                }
10553            }
10554            // All the special cases have been taken care of.
10555            // Return result based on recommended install location.
10556            if (onSd) {
10557                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10558            }
10559            return pkgLite.recommendedInstallLocation;
10560        }
10561
10562        /*
10563         * Invoke remote method to get package information and install
10564         * location values. Override install location based on default
10565         * policy if needed and then create install arguments based
10566         * on the install location.
10567         */
10568        public void handleStartCopy() throws RemoteException {
10569            int ret = PackageManager.INSTALL_SUCCEEDED;
10570
10571            // If we're already staged, we've firmly committed to an install location
10572            if (origin.staged) {
10573                if (origin.file != null) {
10574                    installFlags |= PackageManager.INSTALL_INTERNAL;
10575                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10576                } else if (origin.cid != null) {
10577                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10578                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10579                } else {
10580                    throw new IllegalStateException("Invalid stage location");
10581                }
10582            }
10583
10584            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10585            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10586
10587            PackageInfoLite pkgLite = null;
10588
10589            if (onInt && onSd) {
10590                // Check if both bits are set.
10591                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10592                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10593            } else {
10594                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10595                        packageAbiOverride);
10596
10597                /*
10598                 * If we have too little free space, try to free cache
10599                 * before giving up.
10600                 */
10601                if (!origin.staged && pkgLite.recommendedInstallLocation
10602                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10603                    // TODO: focus freeing disk space on the target device
10604                    final StorageManager storage = StorageManager.from(mContext);
10605                    final long lowThreshold = storage.getStorageLowBytes(
10606                            Environment.getDataDirectory());
10607
10608                    final long sizeBytes = mContainerService.calculateInstalledSize(
10609                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10610
10611                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10612                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10613                                installFlags, packageAbiOverride);
10614                    }
10615
10616                    /*
10617                     * The cache free must have deleted the file we
10618                     * downloaded to install.
10619                     *
10620                     * TODO: fix the "freeCache" call to not delete
10621                     *       the file we care about.
10622                     */
10623                    if (pkgLite.recommendedInstallLocation
10624                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10625                        pkgLite.recommendedInstallLocation
10626                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10627                    }
10628                }
10629            }
10630
10631            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10632                int loc = pkgLite.recommendedInstallLocation;
10633                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10634                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10635                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10636                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10637                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10638                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10639                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10640                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10641                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10642                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10643                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10644                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10645                } else {
10646                    // Override with defaults if needed.
10647                    loc = installLocationPolicy(pkgLite);
10648                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10649                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10650                    } else if (!onSd && !onInt) {
10651                        // Override install location with flags
10652                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10653                            // Set the flag to install on external media.
10654                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10655                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10656                        } else {
10657                            // Make sure the flag for installing on external
10658                            // media is unset
10659                            installFlags |= PackageManager.INSTALL_INTERNAL;
10660                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10661                        }
10662                    }
10663                }
10664            }
10665
10666            final InstallArgs args = createInstallArgs(this);
10667            mArgs = args;
10668
10669            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10670                 /*
10671                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
10672                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
10673                 */
10674                int userIdentifier = getUser().getIdentifier();
10675                if (userIdentifier == UserHandle.USER_ALL
10676                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
10677                    userIdentifier = UserHandle.USER_OWNER;
10678                }
10679
10680                /*
10681                 * Determine if we have any installed package verifiers. If we
10682                 * do, then we'll defer to them to verify the packages.
10683                 */
10684                final int requiredUid = mRequiredVerifierPackage == null ? -1
10685                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
10686                if (!origin.existing && requiredUid != -1
10687                        && isVerificationEnabled(userIdentifier, installFlags)) {
10688                    final Intent verification = new Intent(
10689                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10690                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10691                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10692                            PACKAGE_MIME_TYPE);
10693                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10694
10695                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10696                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10697                            0 /* TODO: Which userId? */);
10698
10699                    if (DEBUG_VERIFY) {
10700                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10701                                + verification.toString() + " with " + pkgLite.verifiers.length
10702                                + " optional verifiers");
10703                    }
10704
10705                    final int verificationId = mPendingVerificationToken++;
10706
10707                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10708
10709                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10710                            installerPackageName);
10711
10712                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10713                            installFlags);
10714
10715                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10716                            pkgLite.packageName);
10717
10718                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10719                            pkgLite.versionCode);
10720
10721                    if (verificationParams != null) {
10722                        if (verificationParams.getVerificationURI() != null) {
10723                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10724                                 verificationParams.getVerificationURI());
10725                        }
10726                        if (verificationParams.getOriginatingURI() != null) {
10727                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10728                                  verificationParams.getOriginatingURI());
10729                        }
10730                        if (verificationParams.getReferrer() != null) {
10731                            verification.putExtra(Intent.EXTRA_REFERRER,
10732                                  verificationParams.getReferrer());
10733                        }
10734                        if (verificationParams.getOriginatingUid() >= 0) {
10735                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10736                                  verificationParams.getOriginatingUid());
10737                        }
10738                        if (verificationParams.getInstallerUid() >= 0) {
10739                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10740                                  verificationParams.getInstallerUid());
10741                        }
10742                    }
10743
10744                    final PackageVerificationState verificationState = new PackageVerificationState(
10745                            requiredUid, args);
10746
10747                    mPendingVerification.append(verificationId, verificationState);
10748
10749                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10750                            receivers, verificationState);
10751
10752                    // Apps installed for "all" users use the device owner to verify the app
10753                    UserHandle verifierUser = getUser();
10754                    if (verifierUser == UserHandle.ALL) {
10755                        verifierUser = UserHandle.OWNER;
10756                    }
10757
10758                    /*
10759                     * If any sufficient verifiers were listed in the package
10760                     * manifest, attempt to ask them.
10761                     */
10762                    if (sufficientVerifiers != null) {
10763                        final int N = sufficientVerifiers.size();
10764                        if (N == 0) {
10765                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10766                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10767                        } else {
10768                            for (int i = 0; i < N; i++) {
10769                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10770
10771                                final Intent sufficientIntent = new Intent(verification);
10772                                sufficientIntent.setComponent(verifierComponent);
10773                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10774                            }
10775                        }
10776                    }
10777
10778                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10779                            mRequiredVerifierPackage, receivers);
10780                    if (ret == PackageManager.INSTALL_SUCCEEDED
10781                            && mRequiredVerifierPackage != null) {
10782                        /*
10783                         * Send the intent to the required verification agent,
10784                         * but only start the verification timeout after the
10785                         * target BroadcastReceivers have run.
10786                         */
10787                        verification.setComponent(requiredVerifierComponent);
10788                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10789                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10790                                new BroadcastReceiver() {
10791                                    @Override
10792                                    public void onReceive(Context context, Intent intent) {
10793                                        final Message msg = mHandler
10794                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10795                                        msg.arg1 = verificationId;
10796                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10797                                    }
10798                                }, null, 0, null, null);
10799
10800                        /*
10801                         * We don't want the copy to proceed until verification
10802                         * succeeds, so null out this field.
10803                         */
10804                        mArgs = null;
10805                    }
10806                } else {
10807                    /*
10808                     * No package verification is enabled, so immediately start
10809                     * the remote call to initiate copy using temporary file.
10810                     */
10811                    ret = args.copyApk(mContainerService, true);
10812                }
10813            }
10814
10815            mRet = ret;
10816        }
10817
10818        @Override
10819        void handleReturnCode() {
10820            // If mArgs is null, then MCS couldn't be reached. When it
10821            // reconnects, it will try again to install. At that point, this
10822            // will succeed.
10823            if (mArgs != null) {
10824                processPendingInstall(mArgs, mRet);
10825            }
10826        }
10827
10828        @Override
10829        void handleServiceError() {
10830            mArgs = createInstallArgs(this);
10831            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10832        }
10833
10834        public boolean isForwardLocked() {
10835            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10836        }
10837    }
10838
10839    /**
10840     * Used during creation of InstallArgs
10841     *
10842     * @param installFlags package installation flags
10843     * @return true if should be installed on external storage
10844     */
10845    private static boolean installOnExternalAsec(int installFlags) {
10846        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10847            return false;
10848        }
10849        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10850            return true;
10851        }
10852        return false;
10853    }
10854
10855    /**
10856     * Used during creation of InstallArgs
10857     *
10858     * @param installFlags package installation flags
10859     * @return true if should be installed as forward locked
10860     */
10861    private static boolean installForwardLocked(int installFlags) {
10862        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10863    }
10864
10865    private InstallArgs createInstallArgs(InstallParams params) {
10866        if (params.move != null) {
10867            return new MoveInstallArgs(params);
10868        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10869            return new AsecInstallArgs(params);
10870        } else {
10871            return new FileInstallArgs(params);
10872        }
10873    }
10874
10875    /**
10876     * Create args that describe an existing installed package. Typically used
10877     * when cleaning up old installs, or used as a move source.
10878     */
10879    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10880            String resourcePath, String[] instructionSets) {
10881        final boolean isInAsec;
10882        if (installOnExternalAsec(installFlags)) {
10883            /* Apps on SD card are always in ASEC containers. */
10884            isInAsec = true;
10885        } else if (installForwardLocked(installFlags)
10886                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10887            /*
10888             * Forward-locked apps are only in ASEC containers if they're the
10889             * new style
10890             */
10891            isInAsec = true;
10892        } else {
10893            isInAsec = false;
10894        }
10895
10896        if (isInAsec) {
10897            return new AsecInstallArgs(codePath, instructionSets,
10898                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10899        } else {
10900            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10901        }
10902    }
10903
10904    static abstract class InstallArgs {
10905        /** @see InstallParams#origin */
10906        final OriginInfo origin;
10907        /** @see InstallParams#move */
10908        final MoveInfo move;
10909
10910        final IPackageInstallObserver2 observer;
10911        // Always refers to PackageManager flags only
10912        final int installFlags;
10913        final String installerPackageName;
10914        final String volumeUuid;
10915        final ManifestDigest manifestDigest;
10916        final UserHandle user;
10917        final String abiOverride;
10918        final String[] installGrantPermissions;
10919
10920        // The list of instruction sets supported by this app. This is currently
10921        // only used during the rmdex() phase to clean up resources. We can get rid of this
10922        // if we move dex files under the common app path.
10923        /* nullable */ String[] instructionSets;
10924
10925        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10926                int installFlags, String installerPackageName, String volumeUuid,
10927                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10928                String abiOverride, String[] installGrantPermissions) {
10929            this.origin = origin;
10930            this.move = move;
10931            this.installFlags = installFlags;
10932            this.observer = observer;
10933            this.installerPackageName = installerPackageName;
10934            this.volumeUuid = volumeUuid;
10935            this.manifestDigest = manifestDigest;
10936            this.user = user;
10937            this.instructionSets = instructionSets;
10938            this.abiOverride = abiOverride;
10939            this.installGrantPermissions = installGrantPermissions;
10940        }
10941
10942        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10943        abstract int doPreInstall(int status);
10944
10945        /**
10946         * Rename package into final resting place. All paths on the given
10947         * scanned package should be updated to reflect the rename.
10948         */
10949        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10950        abstract int doPostInstall(int status, int uid);
10951
10952        /** @see PackageSettingBase#codePathString */
10953        abstract String getCodePath();
10954        /** @see PackageSettingBase#resourcePathString */
10955        abstract String getResourcePath();
10956
10957        // Need installer lock especially for dex file removal.
10958        abstract void cleanUpResourcesLI();
10959        abstract boolean doPostDeleteLI(boolean delete);
10960
10961        /**
10962         * Called before the source arguments are copied. This is used mostly
10963         * for MoveParams when it needs to read the source file to put it in the
10964         * destination.
10965         */
10966        int doPreCopy() {
10967            return PackageManager.INSTALL_SUCCEEDED;
10968        }
10969
10970        /**
10971         * Called after the source arguments are copied. This is used mostly for
10972         * MoveParams when it needs to read the source file to put it in the
10973         * destination.
10974         *
10975         * @return
10976         */
10977        int doPostCopy(int uid) {
10978            return PackageManager.INSTALL_SUCCEEDED;
10979        }
10980
10981        protected boolean isFwdLocked() {
10982            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10983        }
10984
10985        protected boolean isExternalAsec() {
10986            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10987        }
10988
10989        UserHandle getUser() {
10990            return user;
10991        }
10992    }
10993
10994    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10995        if (!allCodePaths.isEmpty()) {
10996            if (instructionSets == null) {
10997                throw new IllegalStateException("instructionSet == null");
10998            }
10999            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11000            for (String codePath : allCodePaths) {
11001                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11002                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11003                    if (retCode < 0) {
11004                        Slog.w(TAG, "Couldn't remove dex file for package: "
11005                                + " at location " + codePath + ", retcode=" + retCode);
11006                        // we don't consider this to be a failure of the core package deletion
11007                    }
11008                }
11009            }
11010        }
11011    }
11012
11013    /**
11014     * Logic to handle installation of non-ASEC applications, including copying
11015     * and renaming logic.
11016     */
11017    class FileInstallArgs extends InstallArgs {
11018        private File codeFile;
11019        private File resourceFile;
11020
11021        // Example topology:
11022        // /data/app/com.example/base.apk
11023        // /data/app/com.example/split_foo.apk
11024        // /data/app/com.example/lib/arm/libfoo.so
11025        // /data/app/com.example/lib/arm64/libfoo.so
11026        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11027
11028        /** New install */
11029        FileInstallArgs(InstallParams params) {
11030            super(params.origin, params.move, params.observer, params.installFlags,
11031                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11032                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11033                    params.grantedRuntimePermissions);
11034            if (isFwdLocked()) {
11035                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11036            }
11037        }
11038
11039        /** Existing install */
11040        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11041            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11042                    null, null);
11043            this.codeFile = (codePath != null) ? new File(codePath) : null;
11044            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11045        }
11046
11047        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11048            if (origin.staged) {
11049                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11050                codeFile = origin.file;
11051                resourceFile = origin.file;
11052                return PackageManager.INSTALL_SUCCEEDED;
11053            }
11054
11055            try {
11056                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11057                codeFile = tempDir;
11058                resourceFile = tempDir;
11059            } catch (IOException e) {
11060                Slog.w(TAG, "Failed to create copy file: " + e);
11061                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11062            }
11063
11064            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11065                @Override
11066                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11067                    if (!FileUtils.isValidExtFilename(name)) {
11068                        throw new IllegalArgumentException("Invalid filename: " + name);
11069                    }
11070                    try {
11071                        final File file = new File(codeFile, name);
11072                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11073                                O_RDWR | O_CREAT, 0644);
11074                        Os.chmod(file.getAbsolutePath(), 0644);
11075                        return new ParcelFileDescriptor(fd);
11076                    } catch (ErrnoException e) {
11077                        throw new RemoteException("Failed to open: " + e.getMessage());
11078                    }
11079                }
11080            };
11081
11082            int ret = PackageManager.INSTALL_SUCCEEDED;
11083            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11084            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11085                Slog.e(TAG, "Failed to copy package");
11086                return ret;
11087            }
11088
11089            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11090            NativeLibraryHelper.Handle handle = null;
11091            try {
11092                handle = NativeLibraryHelper.Handle.create(codeFile);
11093                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11094                        abiOverride);
11095            } catch (IOException e) {
11096                Slog.e(TAG, "Copying native libraries failed", e);
11097                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11098            } finally {
11099                IoUtils.closeQuietly(handle);
11100            }
11101
11102            return ret;
11103        }
11104
11105        int doPreInstall(int status) {
11106            if (status != PackageManager.INSTALL_SUCCEEDED) {
11107                cleanUp();
11108            }
11109            return status;
11110        }
11111
11112        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11113            if (status != PackageManager.INSTALL_SUCCEEDED) {
11114                cleanUp();
11115                return false;
11116            }
11117
11118            final File targetDir = codeFile.getParentFile();
11119            final File beforeCodeFile = codeFile;
11120            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11121
11122            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11123            try {
11124                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11125            } catch (ErrnoException e) {
11126                Slog.w(TAG, "Failed to rename", e);
11127                return false;
11128            }
11129
11130            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11131                Slog.w(TAG, "Failed to restorecon");
11132                return false;
11133            }
11134
11135            // Reflect the rename internally
11136            codeFile = afterCodeFile;
11137            resourceFile = afterCodeFile;
11138
11139            // Reflect the rename in scanned details
11140            pkg.codePath = afterCodeFile.getAbsolutePath();
11141            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11142                    pkg.baseCodePath);
11143            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11144                    pkg.splitCodePaths);
11145
11146            // Reflect the rename in app info
11147            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11148            pkg.applicationInfo.setCodePath(pkg.codePath);
11149            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11150            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11151            pkg.applicationInfo.setResourcePath(pkg.codePath);
11152            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11153            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11154
11155            return true;
11156        }
11157
11158        int doPostInstall(int status, int uid) {
11159            if (status != PackageManager.INSTALL_SUCCEEDED) {
11160                cleanUp();
11161            }
11162            return status;
11163        }
11164
11165        @Override
11166        String getCodePath() {
11167            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11168        }
11169
11170        @Override
11171        String getResourcePath() {
11172            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11173        }
11174
11175        private boolean cleanUp() {
11176            if (codeFile == null || !codeFile.exists()) {
11177                return false;
11178            }
11179
11180            if (codeFile.isDirectory()) {
11181                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11182            } else {
11183                codeFile.delete();
11184            }
11185
11186            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11187                resourceFile.delete();
11188            }
11189
11190            return true;
11191        }
11192
11193        void cleanUpResourcesLI() {
11194            // Try enumerating all code paths before deleting
11195            List<String> allCodePaths = Collections.EMPTY_LIST;
11196            if (codeFile != null && codeFile.exists()) {
11197                try {
11198                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11199                    allCodePaths = pkg.getAllCodePaths();
11200                } catch (PackageParserException e) {
11201                    // Ignored; we tried our best
11202                }
11203            }
11204
11205            cleanUp();
11206            removeDexFiles(allCodePaths, instructionSets);
11207        }
11208
11209        boolean doPostDeleteLI(boolean delete) {
11210            // XXX err, shouldn't we respect the delete flag?
11211            cleanUpResourcesLI();
11212            return true;
11213        }
11214    }
11215
11216    private boolean isAsecExternal(String cid) {
11217        final String asecPath = PackageHelper.getSdFilesystem(cid);
11218        return !asecPath.startsWith(mAsecInternalPath);
11219    }
11220
11221    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11222            PackageManagerException {
11223        if (copyRet < 0) {
11224            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11225                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11226                throw new PackageManagerException(copyRet, message);
11227            }
11228        }
11229    }
11230
11231    /**
11232     * Extract the MountService "container ID" from the full code path of an
11233     * .apk.
11234     */
11235    static String cidFromCodePath(String fullCodePath) {
11236        int eidx = fullCodePath.lastIndexOf("/");
11237        String subStr1 = fullCodePath.substring(0, eidx);
11238        int sidx = subStr1.lastIndexOf("/");
11239        return subStr1.substring(sidx+1, eidx);
11240    }
11241
11242    /**
11243     * Logic to handle installation of ASEC applications, including copying and
11244     * renaming logic.
11245     */
11246    class AsecInstallArgs extends InstallArgs {
11247        static final String RES_FILE_NAME = "pkg.apk";
11248        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11249
11250        String cid;
11251        String packagePath;
11252        String resourcePath;
11253
11254        /** New install */
11255        AsecInstallArgs(InstallParams params) {
11256            super(params.origin, params.move, params.observer, params.installFlags,
11257                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11258                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11259                    params.grantedRuntimePermissions);
11260        }
11261
11262        /** Existing install */
11263        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11264                        boolean isExternal, boolean isForwardLocked) {
11265            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11266                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11267                    instructionSets, null, null);
11268            // Hackily pretend we're still looking at a full code path
11269            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11270                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11271            }
11272
11273            // Extract cid from fullCodePath
11274            int eidx = fullCodePath.lastIndexOf("/");
11275            String subStr1 = fullCodePath.substring(0, eidx);
11276            int sidx = subStr1.lastIndexOf("/");
11277            cid = subStr1.substring(sidx+1, eidx);
11278            setMountPath(subStr1);
11279        }
11280
11281        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11282            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11283                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11284                    instructionSets, null, null);
11285            this.cid = cid;
11286            setMountPath(PackageHelper.getSdDir(cid));
11287        }
11288
11289        void createCopyFile() {
11290            cid = mInstallerService.allocateExternalStageCidLegacy();
11291        }
11292
11293        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11294            if (origin.staged) {
11295                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11296                cid = origin.cid;
11297                setMountPath(PackageHelper.getSdDir(cid));
11298                return PackageManager.INSTALL_SUCCEEDED;
11299            }
11300
11301            if (temp) {
11302                createCopyFile();
11303            } else {
11304                /*
11305                 * Pre-emptively destroy the container since it's destroyed if
11306                 * copying fails due to it existing anyway.
11307                 */
11308                PackageHelper.destroySdDir(cid);
11309            }
11310
11311            final String newMountPath = imcs.copyPackageToContainer(
11312                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11313                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11314
11315            if (newMountPath != null) {
11316                setMountPath(newMountPath);
11317                return PackageManager.INSTALL_SUCCEEDED;
11318            } else {
11319                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11320            }
11321        }
11322
11323        @Override
11324        String getCodePath() {
11325            return packagePath;
11326        }
11327
11328        @Override
11329        String getResourcePath() {
11330            return resourcePath;
11331        }
11332
11333        int doPreInstall(int status) {
11334            if (status != PackageManager.INSTALL_SUCCEEDED) {
11335                // Destroy container
11336                PackageHelper.destroySdDir(cid);
11337            } else {
11338                boolean mounted = PackageHelper.isContainerMounted(cid);
11339                if (!mounted) {
11340                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11341                            Process.SYSTEM_UID);
11342                    if (newMountPath != null) {
11343                        setMountPath(newMountPath);
11344                    } else {
11345                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11346                    }
11347                }
11348            }
11349            return status;
11350        }
11351
11352        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11353            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11354            String newMountPath = null;
11355            if (PackageHelper.isContainerMounted(cid)) {
11356                // Unmount the container
11357                if (!PackageHelper.unMountSdDir(cid)) {
11358                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11359                    return false;
11360                }
11361            }
11362            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11363                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11364                        " which might be stale. Will try to clean up.");
11365                // Clean up the stale container and proceed to recreate.
11366                if (!PackageHelper.destroySdDir(newCacheId)) {
11367                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11368                    return false;
11369                }
11370                // Successfully cleaned up stale container. Try to rename again.
11371                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11372                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11373                            + " inspite of cleaning it up.");
11374                    return false;
11375                }
11376            }
11377            if (!PackageHelper.isContainerMounted(newCacheId)) {
11378                Slog.w(TAG, "Mounting container " + newCacheId);
11379                newMountPath = PackageHelper.mountSdDir(newCacheId,
11380                        getEncryptKey(), Process.SYSTEM_UID);
11381            } else {
11382                newMountPath = PackageHelper.getSdDir(newCacheId);
11383            }
11384            if (newMountPath == null) {
11385                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11386                return false;
11387            }
11388            Log.i(TAG, "Succesfully renamed " + cid +
11389                    " to " + newCacheId +
11390                    " at new path: " + newMountPath);
11391            cid = newCacheId;
11392
11393            final File beforeCodeFile = new File(packagePath);
11394            setMountPath(newMountPath);
11395            final File afterCodeFile = new File(packagePath);
11396
11397            // Reflect the rename in scanned details
11398            pkg.codePath = afterCodeFile.getAbsolutePath();
11399            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11400                    pkg.baseCodePath);
11401            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11402                    pkg.splitCodePaths);
11403
11404            // Reflect the rename in app info
11405            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11406            pkg.applicationInfo.setCodePath(pkg.codePath);
11407            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11408            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11409            pkg.applicationInfo.setResourcePath(pkg.codePath);
11410            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11411            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11412
11413            return true;
11414        }
11415
11416        private void setMountPath(String mountPath) {
11417            final File mountFile = new File(mountPath);
11418
11419            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11420            if (monolithicFile.exists()) {
11421                packagePath = monolithicFile.getAbsolutePath();
11422                if (isFwdLocked()) {
11423                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11424                } else {
11425                    resourcePath = packagePath;
11426                }
11427            } else {
11428                packagePath = mountFile.getAbsolutePath();
11429                resourcePath = packagePath;
11430            }
11431        }
11432
11433        int doPostInstall(int status, int uid) {
11434            if (status != PackageManager.INSTALL_SUCCEEDED) {
11435                cleanUp();
11436            } else {
11437                final int groupOwner;
11438                final String protectedFile;
11439                if (isFwdLocked()) {
11440                    groupOwner = UserHandle.getSharedAppGid(uid);
11441                    protectedFile = RES_FILE_NAME;
11442                } else {
11443                    groupOwner = -1;
11444                    protectedFile = null;
11445                }
11446
11447                if (uid < Process.FIRST_APPLICATION_UID
11448                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11449                    Slog.e(TAG, "Failed to finalize " + cid);
11450                    PackageHelper.destroySdDir(cid);
11451                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11452                }
11453
11454                boolean mounted = PackageHelper.isContainerMounted(cid);
11455                if (!mounted) {
11456                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11457                }
11458            }
11459            return status;
11460        }
11461
11462        private void cleanUp() {
11463            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11464
11465            // Destroy secure container
11466            PackageHelper.destroySdDir(cid);
11467        }
11468
11469        private List<String> getAllCodePaths() {
11470            final File codeFile = new File(getCodePath());
11471            if (codeFile != null && codeFile.exists()) {
11472                try {
11473                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11474                    return pkg.getAllCodePaths();
11475                } catch (PackageParserException e) {
11476                    // Ignored; we tried our best
11477                }
11478            }
11479            return Collections.EMPTY_LIST;
11480        }
11481
11482        void cleanUpResourcesLI() {
11483            // Enumerate all code paths before deleting
11484            cleanUpResourcesLI(getAllCodePaths());
11485        }
11486
11487        private void cleanUpResourcesLI(List<String> allCodePaths) {
11488            cleanUp();
11489            removeDexFiles(allCodePaths, instructionSets);
11490        }
11491
11492        String getPackageName() {
11493            return getAsecPackageName(cid);
11494        }
11495
11496        boolean doPostDeleteLI(boolean delete) {
11497            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11498            final List<String> allCodePaths = getAllCodePaths();
11499            boolean mounted = PackageHelper.isContainerMounted(cid);
11500            if (mounted) {
11501                // Unmount first
11502                if (PackageHelper.unMountSdDir(cid)) {
11503                    mounted = false;
11504                }
11505            }
11506            if (!mounted && delete) {
11507                cleanUpResourcesLI(allCodePaths);
11508            }
11509            return !mounted;
11510        }
11511
11512        @Override
11513        int doPreCopy() {
11514            if (isFwdLocked()) {
11515                if (!PackageHelper.fixSdPermissions(cid,
11516                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11517                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11518                }
11519            }
11520
11521            return PackageManager.INSTALL_SUCCEEDED;
11522        }
11523
11524        @Override
11525        int doPostCopy(int uid) {
11526            if (isFwdLocked()) {
11527                if (uid < Process.FIRST_APPLICATION_UID
11528                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11529                                RES_FILE_NAME)) {
11530                    Slog.e(TAG, "Failed to finalize " + cid);
11531                    PackageHelper.destroySdDir(cid);
11532                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11533                }
11534            }
11535
11536            return PackageManager.INSTALL_SUCCEEDED;
11537        }
11538    }
11539
11540    /**
11541     * Logic to handle movement of existing installed applications.
11542     */
11543    class MoveInstallArgs extends InstallArgs {
11544        private File codeFile;
11545        private File resourceFile;
11546
11547        /** New install */
11548        MoveInstallArgs(InstallParams params) {
11549            super(params.origin, params.move, params.observer, params.installFlags,
11550                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11551                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11552                    params.grantedRuntimePermissions);
11553        }
11554
11555        int copyApk(IMediaContainerService imcs, boolean temp) {
11556            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11557                    + move.fromUuid + " to " + move.toUuid);
11558            synchronized (mInstaller) {
11559                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11560                        move.dataAppName, move.appId, move.seinfo) != 0) {
11561                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11562                }
11563            }
11564
11565            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11566            resourceFile = codeFile;
11567            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11568
11569            return PackageManager.INSTALL_SUCCEEDED;
11570        }
11571
11572        int doPreInstall(int status) {
11573            if (status != PackageManager.INSTALL_SUCCEEDED) {
11574                cleanUp(move.toUuid);
11575            }
11576            return status;
11577        }
11578
11579        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11580            if (status != PackageManager.INSTALL_SUCCEEDED) {
11581                cleanUp(move.toUuid);
11582                return false;
11583            }
11584
11585            // Reflect the move in app info
11586            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11587            pkg.applicationInfo.setCodePath(pkg.codePath);
11588            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11589            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11590            pkg.applicationInfo.setResourcePath(pkg.codePath);
11591            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11592            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11593
11594            return true;
11595        }
11596
11597        int doPostInstall(int status, int uid) {
11598            if (status == PackageManager.INSTALL_SUCCEEDED) {
11599                cleanUp(move.fromUuid);
11600            } else {
11601                cleanUp(move.toUuid);
11602            }
11603            return status;
11604        }
11605
11606        @Override
11607        String getCodePath() {
11608            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11609        }
11610
11611        @Override
11612        String getResourcePath() {
11613            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11614        }
11615
11616        private boolean cleanUp(String volumeUuid) {
11617            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11618                    move.dataAppName);
11619            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11620            synchronized (mInstallLock) {
11621                // Clean up both app data and code
11622                removeDataDirsLI(volumeUuid, move.packageName);
11623                if (codeFile.isDirectory()) {
11624                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11625                } else {
11626                    codeFile.delete();
11627                }
11628            }
11629            return true;
11630        }
11631
11632        void cleanUpResourcesLI() {
11633            throw new UnsupportedOperationException();
11634        }
11635
11636        boolean doPostDeleteLI(boolean delete) {
11637            throw new UnsupportedOperationException();
11638        }
11639    }
11640
11641    static String getAsecPackageName(String packageCid) {
11642        int idx = packageCid.lastIndexOf("-");
11643        if (idx == -1) {
11644            return packageCid;
11645        }
11646        return packageCid.substring(0, idx);
11647    }
11648
11649    // Utility method used to create code paths based on package name and available index.
11650    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11651        String idxStr = "";
11652        int idx = 1;
11653        // Fall back to default value of idx=1 if prefix is not
11654        // part of oldCodePath
11655        if (oldCodePath != null) {
11656            String subStr = oldCodePath;
11657            // Drop the suffix right away
11658            if (suffix != null && subStr.endsWith(suffix)) {
11659                subStr = subStr.substring(0, subStr.length() - suffix.length());
11660            }
11661            // If oldCodePath already contains prefix find out the
11662            // ending index to either increment or decrement.
11663            int sidx = subStr.lastIndexOf(prefix);
11664            if (sidx != -1) {
11665                subStr = subStr.substring(sidx + prefix.length());
11666                if (subStr != null) {
11667                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11668                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11669                    }
11670                    try {
11671                        idx = Integer.parseInt(subStr);
11672                        if (idx <= 1) {
11673                            idx++;
11674                        } else {
11675                            idx--;
11676                        }
11677                    } catch(NumberFormatException e) {
11678                    }
11679                }
11680            }
11681        }
11682        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11683        return prefix + idxStr;
11684    }
11685
11686    private File getNextCodePath(File targetDir, String packageName) {
11687        int suffix = 1;
11688        File result;
11689        do {
11690            result = new File(targetDir, packageName + "-" + suffix);
11691            suffix++;
11692        } while (result.exists());
11693        return result;
11694    }
11695
11696    // Utility method that returns the relative package path with respect
11697    // to the installation directory. Like say for /data/data/com.test-1.apk
11698    // string com.test-1 is returned.
11699    static String deriveCodePathName(String codePath) {
11700        if (codePath == null) {
11701            return null;
11702        }
11703        final File codeFile = new File(codePath);
11704        final String name = codeFile.getName();
11705        if (codeFile.isDirectory()) {
11706            return name;
11707        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11708            final int lastDot = name.lastIndexOf('.');
11709            return name.substring(0, lastDot);
11710        } else {
11711            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11712            return null;
11713        }
11714    }
11715
11716    class PackageInstalledInfo {
11717        String name;
11718        int uid;
11719        // The set of users that originally had this package installed.
11720        int[] origUsers;
11721        // The set of users that now have this package installed.
11722        int[] newUsers;
11723        PackageParser.Package pkg;
11724        int returnCode;
11725        String returnMsg;
11726        PackageRemovedInfo removedInfo;
11727
11728        public void setError(int code, String msg) {
11729            returnCode = code;
11730            returnMsg = msg;
11731            Slog.w(TAG, msg);
11732        }
11733
11734        public void setError(String msg, PackageParserException e) {
11735            returnCode = e.error;
11736            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11737            Slog.w(TAG, msg, e);
11738        }
11739
11740        public void setError(String msg, PackageManagerException e) {
11741            returnCode = e.error;
11742            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11743            Slog.w(TAG, msg, e);
11744        }
11745
11746        // In some error cases we want to convey more info back to the observer
11747        String origPackage;
11748        String origPermission;
11749    }
11750
11751    /*
11752     * Install a non-existing package.
11753     */
11754    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11755            UserHandle user, String installerPackageName, String volumeUuid,
11756            PackageInstalledInfo res) {
11757        // Remember this for later, in case we need to rollback this install
11758        String pkgName = pkg.packageName;
11759
11760        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11761        final boolean dataDirExists = Environment
11762                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_OWNER, pkgName).exists();
11763        synchronized(mPackages) {
11764            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11765                // A package with the same name is already installed, though
11766                // it has been renamed to an older name.  The package we
11767                // are trying to install should be installed as an update to
11768                // the existing one, but that has not been requested, so bail.
11769                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11770                        + " without first uninstalling package running as "
11771                        + mSettings.mRenamedPackages.get(pkgName));
11772                return;
11773            }
11774            if (mPackages.containsKey(pkgName)) {
11775                // Don't allow installation over an existing package with the same name.
11776                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11777                        + " without first uninstalling.");
11778                return;
11779            }
11780        }
11781
11782        try {
11783            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
11784                    System.currentTimeMillis(), user);
11785
11786            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11787            // delete the partially installed application. the data directory will have to be
11788            // restored if it was already existing
11789            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11790                // remove package from internal structures.  Note that we want deletePackageX to
11791                // delete the package data and cache directories that it created in
11792                // scanPackageLocked, unless those directories existed before we even tried to
11793                // install.
11794                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11795                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11796                                res.removedInfo, true);
11797            }
11798
11799        } catch (PackageManagerException e) {
11800            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11801        }
11802    }
11803
11804    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11805        // Can't rotate keys during boot or if sharedUser.
11806        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11807                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11808            return false;
11809        }
11810        // app is using upgradeKeySets; make sure all are valid
11811        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11812        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11813        for (int i = 0; i < upgradeKeySets.length; i++) {
11814            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11815                Slog.wtf(TAG, "Package "
11816                         + (oldPs.name != null ? oldPs.name : "<null>")
11817                         + " contains upgrade-key-set reference to unknown key-set: "
11818                         + upgradeKeySets[i]
11819                         + " reverting to signatures check.");
11820                return false;
11821            }
11822        }
11823        return true;
11824    }
11825
11826    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11827        // Upgrade keysets are being used.  Determine if new package has a superset of the
11828        // required keys.
11829        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11830        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11831        for (int i = 0; i < upgradeKeySets.length; i++) {
11832            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11833            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
11834                return true;
11835            }
11836        }
11837        return false;
11838    }
11839
11840    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11841            UserHandle user, String installerPackageName, String volumeUuid,
11842            PackageInstalledInfo res) {
11843        final PackageParser.Package oldPackage;
11844        final String pkgName = pkg.packageName;
11845        final int[] allUsers;
11846        final boolean[] perUserInstalled;
11847
11848        // First find the old package info and check signatures
11849        synchronized(mPackages) {
11850            oldPackage = mPackages.get(pkgName);
11851            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11852            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11853            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
11854                if(!checkUpgradeKeySetLP(ps, pkg)) {
11855                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11856                            "New package not signed by keys specified by upgrade-keysets: "
11857                            + pkgName);
11858                    return;
11859                }
11860            } else {
11861                // default to original signature matching
11862                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11863                    != PackageManager.SIGNATURE_MATCH) {
11864                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11865                            "New package has a different signature: " + pkgName);
11866                    return;
11867                }
11868            }
11869
11870            // In case of rollback, remember per-user/profile install state
11871            allUsers = sUserManager.getUserIds();
11872            perUserInstalled = new boolean[allUsers.length];
11873            for (int i = 0; i < allUsers.length; i++) {
11874                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11875            }
11876        }
11877
11878        boolean sysPkg = (isSystemApp(oldPackage));
11879        if (sysPkg) {
11880            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11881                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11882        } else {
11883            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11884                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11885        }
11886    }
11887
11888    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11889            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11890            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11891            String volumeUuid, PackageInstalledInfo res) {
11892        String pkgName = deletedPackage.packageName;
11893        boolean deletedPkg = true;
11894        boolean updatedSettings = false;
11895
11896        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11897                + deletedPackage);
11898        long origUpdateTime;
11899        if (pkg.mExtras != null) {
11900            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11901        } else {
11902            origUpdateTime = 0;
11903        }
11904
11905        // First delete the existing package while retaining the data directory
11906        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11907                res.removedInfo, true)) {
11908            // If the existing package wasn't successfully deleted
11909            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11910            deletedPkg = false;
11911        } else {
11912            // Successfully deleted the old package; proceed with replace.
11913
11914            // If deleted package lived in a container, give users a chance to
11915            // relinquish resources before killing.
11916            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11917                if (DEBUG_INSTALL) {
11918                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11919                }
11920                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11921                final ArrayList<String> pkgList = new ArrayList<String>(1);
11922                pkgList.add(deletedPackage.applicationInfo.packageName);
11923                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11924            }
11925
11926            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11927            try {
11928                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11929                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11930                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11931                        perUserInstalled, res, user);
11932                updatedSettings = true;
11933            } catch (PackageManagerException e) {
11934                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11935            }
11936        }
11937
11938        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11939            // remove package from internal structures.  Note that we want deletePackageX to
11940            // delete the package data and cache directories that it created in
11941            // scanPackageLocked, unless those directories existed before we even tried to
11942            // install.
11943            if(updatedSettings) {
11944                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11945                deletePackageLI(
11946                        pkgName, null, true, allUsers, perUserInstalled,
11947                        PackageManager.DELETE_KEEP_DATA,
11948                                res.removedInfo, true);
11949            }
11950            // Since we failed to install the new package we need to restore the old
11951            // package that we deleted.
11952            if (deletedPkg) {
11953                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11954                File restoreFile = new File(deletedPackage.codePath);
11955                // Parse old package
11956                boolean oldExternal = isExternal(deletedPackage);
11957                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11958                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11959                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11960                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11961                try {
11962                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11963                } catch (PackageManagerException e) {
11964                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11965                            + e.getMessage());
11966                    return;
11967                }
11968                // Restore of old package succeeded. Update permissions.
11969                // writer
11970                synchronized (mPackages) {
11971                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11972                            UPDATE_PERMISSIONS_ALL);
11973                    // can downgrade to reader
11974                    mSettings.writeLPr();
11975                }
11976                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11977            }
11978        }
11979    }
11980
11981    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11982            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11983            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11984            String volumeUuid, PackageInstalledInfo res) {
11985        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11986                + ", old=" + deletedPackage);
11987        boolean disabledSystem = false;
11988        boolean updatedSettings = false;
11989        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11990        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11991                != 0) {
11992            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11993        }
11994        String packageName = deletedPackage.packageName;
11995        if (packageName == null) {
11996            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11997                    "Attempt to delete null packageName.");
11998            return;
11999        }
12000        PackageParser.Package oldPkg;
12001        PackageSetting oldPkgSetting;
12002        // reader
12003        synchronized (mPackages) {
12004            oldPkg = mPackages.get(packageName);
12005            oldPkgSetting = mSettings.mPackages.get(packageName);
12006            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12007                    (oldPkgSetting == null)) {
12008                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12009                        "Couldn't find package:" + packageName + " information");
12010                return;
12011            }
12012        }
12013
12014        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12015
12016        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12017        res.removedInfo.removedPackage = packageName;
12018        // Remove existing system package
12019        removePackageLI(oldPkgSetting, true);
12020        // writer
12021        synchronized (mPackages) {
12022            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12023            if (!disabledSystem && deletedPackage != null) {
12024                // We didn't need to disable the .apk as a current system package,
12025                // which means we are replacing another update that is already
12026                // installed.  We need to make sure to delete the older one's .apk.
12027                res.removedInfo.args = createInstallArgsForExisting(0,
12028                        deletedPackage.applicationInfo.getCodePath(),
12029                        deletedPackage.applicationInfo.getResourcePath(),
12030                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12031            } else {
12032                res.removedInfo.args = null;
12033            }
12034        }
12035
12036        // Successfully disabled the old package. Now proceed with re-installation
12037        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12038
12039        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12040        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12041
12042        PackageParser.Package newPackage = null;
12043        try {
12044            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
12045            if (newPackage.mExtras != null) {
12046                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12047                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12048                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12049
12050                // is the update attempting to change shared user? that isn't going to work...
12051                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12052                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12053                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12054                            + " to " + newPkgSetting.sharedUser);
12055                    updatedSettings = true;
12056                }
12057            }
12058
12059            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12060                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12061                        perUserInstalled, res, user);
12062                updatedSettings = true;
12063            }
12064
12065        } catch (PackageManagerException e) {
12066            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12067        }
12068
12069        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12070            // Re installation failed. Restore old information
12071            // Remove new pkg information
12072            if (newPackage != null) {
12073                removeInstalledPackageLI(newPackage, true);
12074            }
12075            // Add back the old system package
12076            try {
12077                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12078            } catch (PackageManagerException e) {
12079                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12080            }
12081            // Restore the old system information in Settings
12082            synchronized (mPackages) {
12083                if (disabledSystem) {
12084                    mSettings.enableSystemPackageLPw(packageName);
12085                }
12086                if (updatedSettings) {
12087                    mSettings.setInstallerPackageName(packageName,
12088                            oldPkgSetting.installerPackageName);
12089                }
12090                mSettings.writeLPr();
12091            }
12092        }
12093    }
12094
12095    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12096        // Collect all used permissions in the UID
12097        ArraySet<String> usedPermissions = new ArraySet<>();
12098        final int packageCount = su.packages.size();
12099        for (int i = 0; i < packageCount; i++) {
12100            PackageSetting ps = su.packages.valueAt(i);
12101            if (ps.pkg == null) {
12102                continue;
12103            }
12104            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12105            for (int j = 0; j < requestedPermCount; j++) {
12106                String permission = ps.pkg.requestedPermissions.get(j);
12107                BasePermission bp = mSettings.mPermissions.get(permission);
12108                if (bp != null) {
12109                    usedPermissions.add(permission);
12110                }
12111            }
12112        }
12113
12114        PermissionsState permissionsState = su.getPermissionsState();
12115        // Prune install permissions
12116        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12117        final int installPermCount = installPermStates.size();
12118        for (int i = installPermCount - 1; i >= 0;  i--) {
12119            PermissionState permissionState = installPermStates.get(i);
12120            if (!usedPermissions.contains(permissionState.getName())) {
12121                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12122                if (bp != null) {
12123                    permissionsState.revokeInstallPermission(bp);
12124                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12125                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12126                }
12127            }
12128        }
12129
12130        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12131
12132        // Prune runtime permissions
12133        for (int userId : allUserIds) {
12134            List<PermissionState> runtimePermStates = permissionsState
12135                    .getRuntimePermissionStates(userId);
12136            final int runtimePermCount = runtimePermStates.size();
12137            for (int i = runtimePermCount - 1; i >= 0; i--) {
12138                PermissionState permissionState = runtimePermStates.get(i);
12139                if (!usedPermissions.contains(permissionState.getName())) {
12140                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12141                    if (bp != null) {
12142                        permissionsState.revokeRuntimePermission(bp, userId);
12143                        permissionsState.updatePermissionFlags(bp, userId,
12144                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12145                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12146                                runtimePermissionChangedUserIds, userId);
12147                    }
12148                }
12149            }
12150        }
12151
12152        return runtimePermissionChangedUserIds;
12153    }
12154
12155    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12156            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12157            UserHandle user) {
12158        String pkgName = newPackage.packageName;
12159        synchronized (mPackages) {
12160            //write settings. the installStatus will be incomplete at this stage.
12161            //note that the new package setting would have already been
12162            //added to mPackages. It hasn't been persisted yet.
12163            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12164            mSettings.writeLPr();
12165        }
12166
12167        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12168
12169        synchronized (mPackages) {
12170            updatePermissionsLPw(newPackage.packageName, newPackage,
12171                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12172                            ? UPDATE_PERMISSIONS_ALL : 0));
12173            // For system-bundled packages, we assume that installing an upgraded version
12174            // of the package implies that the user actually wants to run that new code,
12175            // so we enable the package.
12176            PackageSetting ps = mSettings.mPackages.get(pkgName);
12177            if (ps != null) {
12178                if (isSystemApp(newPackage)) {
12179                    // NB: implicit assumption that system package upgrades apply to all users
12180                    if (DEBUG_INSTALL) {
12181                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12182                    }
12183                    if (res.origUsers != null) {
12184                        for (int userHandle : res.origUsers) {
12185                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12186                                    userHandle, installerPackageName);
12187                        }
12188                    }
12189                    // Also convey the prior install/uninstall state
12190                    if (allUsers != null && perUserInstalled != null) {
12191                        for (int i = 0; i < allUsers.length; i++) {
12192                            if (DEBUG_INSTALL) {
12193                                Slog.d(TAG, "    user " + allUsers[i]
12194                                        + " => " + perUserInstalled[i]);
12195                            }
12196                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12197                        }
12198                        // these install state changes will be persisted in the
12199                        // upcoming call to mSettings.writeLPr().
12200                    }
12201                }
12202                // It's implied that when a user requests installation, they want the app to be
12203                // installed and enabled.
12204                int userId = user.getIdentifier();
12205                if (userId != UserHandle.USER_ALL) {
12206                    ps.setInstalled(true, userId);
12207                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12208                }
12209            }
12210            res.name = pkgName;
12211            res.uid = newPackage.applicationInfo.uid;
12212            res.pkg = newPackage;
12213            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12214            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12215            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12216            //to update install status
12217            mSettings.writeLPr();
12218        }
12219    }
12220
12221    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12222        final int installFlags = args.installFlags;
12223        final String installerPackageName = args.installerPackageName;
12224        final String volumeUuid = args.volumeUuid;
12225        final File tmpPackageFile = new File(args.getCodePath());
12226        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12227        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12228                || (args.volumeUuid != null));
12229        boolean replace = false;
12230        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12231        if (args.move != null) {
12232            // moving a complete application; perfom an initial scan on the new install location
12233            scanFlags |= SCAN_INITIAL;
12234        }
12235        // Result object to be returned
12236        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12237
12238        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12239        // Retrieve PackageSettings and parse package
12240        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12241                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12242                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12243        PackageParser pp = new PackageParser();
12244        pp.setSeparateProcesses(mSeparateProcesses);
12245        pp.setDisplayMetrics(mMetrics);
12246
12247        final PackageParser.Package pkg;
12248        try {
12249            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12250        } catch (PackageParserException e) {
12251            res.setError("Failed parse during installPackageLI", e);
12252            return;
12253        }
12254
12255        // Mark that we have an install time CPU ABI override.
12256        pkg.cpuAbiOverride = args.abiOverride;
12257
12258        String pkgName = res.name = pkg.packageName;
12259        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12260            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12261                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12262                return;
12263            }
12264        }
12265
12266        try {
12267            pp.collectCertificates(pkg, parseFlags);
12268            pp.collectManifestDigest(pkg);
12269        } catch (PackageParserException e) {
12270            res.setError("Failed collect during installPackageLI", e);
12271            return;
12272        }
12273
12274        /* If the installer passed in a manifest digest, compare it now. */
12275        if (args.manifestDigest != null) {
12276            if (DEBUG_INSTALL) {
12277                final String parsedManifest = pkg.manifestDigest == null ? "null"
12278                        : pkg.manifestDigest.toString();
12279                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12280                        + parsedManifest);
12281            }
12282
12283            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12284                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12285                return;
12286            }
12287        } else if (DEBUG_INSTALL) {
12288            final String parsedManifest = pkg.manifestDigest == null
12289                    ? "null" : pkg.manifestDigest.toString();
12290            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12291        }
12292
12293        // Get rid of all references to package scan path via parser.
12294        pp = null;
12295        String oldCodePath = null;
12296        boolean systemApp = false;
12297        synchronized (mPackages) {
12298            // Check if installing already existing package
12299            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12300                String oldName = mSettings.mRenamedPackages.get(pkgName);
12301                if (pkg.mOriginalPackages != null
12302                        && pkg.mOriginalPackages.contains(oldName)
12303                        && mPackages.containsKey(oldName)) {
12304                    // This package is derived from an original package,
12305                    // and this device has been updating from that original
12306                    // name.  We must continue using the original name, so
12307                    // rename the new package here.
12308                    pkg.setPackageName(oldName);
12309                    pkgName = pkg.packageName;
12310                    replace = true;
12311                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12312                            + oldName + " pkgName=" + pkgName);
12313                } else if (mPackages.containsKey(pkgName)) {
12314                    // This package, under its official name, already exists
12315                    // on the device; we should replace it.
12316                    replace = true;
12317                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12318                }
12319
12320                // Prevent apps opting out from runtime permissions
12321                if (replace) {
12322                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12323                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12324                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12325                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12326                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12327                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12328                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12329                                        + " doesn't support runtime permissions but the old"
12330                                        + " target SDK " + oldTargetSdk + " does.");
12331                        return;
12332                    }
12333                }
12334            }
12335
12336            PackageSetting ps = mSettings.mPackages.get(pkgName);
12337            if (ps != null) {
12338                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12339
12340                // Quick sanity check that we're signed correctly if updating;
12341                // we'll check this again later when scanning, but we want to
12342                // bail early here before tripping over redefined permissions.
12343                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12344                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12345                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12346                                + pkg.packageName + " upgrade keys do not match the "
12347                                + "previously installed version");
12348                        return;
12349                    }
12350                } else {
12351                    try {
12352                        verifySignaturesLP(ps, pkg);
12353                    } catch (PackageManagerException e) {
12354                        res.setError(e.error, e.getMessage());
12355                        return;
12356                    }
12357                }
12358
12359                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12360                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12361                    systemApp = (ps.pkg.applicationInfo.flags &
12362                            ApplicationInfo.FLAG_SYSTEM) != 0;
12363                }
12364                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12365            }
12366
12367            // Check whether the newly-scanned package wants to define an already-defined perm
12368            int N = pkg.permissions.size();
12369            for (int i = N-1; i >= 0; i--) {
12370                PackageParser.Permission perm = pkg.permissions.get(i);
12371                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12372                if (bp != null) {
12373                    // If the defining package is signed with our cert, it's okay.  This
12374                    // also includes the "updating the same package" case, of course.
12375                    // "updating same package" could also involve key-rotation.
12376                    final boolean sigsOk;
12377                    if (bp.sourcePackage.equals(pkg.packageName)
12378                            && (bp.packageSetting instanceof PackageSetting)
12379                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12380                                    scanFlags))) {
12381                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12382                    } else {
12383                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12384                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12385                    }
12386                    if (!sigsOk) {
12387                        // If the owning package is the system itself, we log but allow
12388                        // install to proceed; we fail the install on all other permission
12389                        // redefinitions.
12390                        if (!bp.sourcePackage.equals("android")) {
12391                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12392                                    + pkg.packageName + " attempting to redeclare permission "
12393                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12394                            res.origPermission = perm.info.name;
12395                            res.origPackage = bp.sourcePackage;
12396                            return;
12397                        } else {
12398                            Slog.w(TAG, "Package " + pkg.packageName
12399                                    + " attempting to redeclare system permission "
12400                                    + perm.info.name + "; ignoring new declaration");
12401                            pkg.permissions.remove(i);
12402                        }
12403                    }
12404                }
12405            }
12406
12407        }
12408
12409        if (systemApp && onExternal) {
12410            // Disable updates to system apps on sdcard
12411            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12412                    "Cannot install updates to system apps on sdcard");
12413            return;
12414        }
12415
12416        if (args.move != null) {
12417            // We did an in-place move, so dex is ready to roll
12418            scanFlags |= SCAN_NO_DEX;
12419            scanFlags |= SCAN_MOVE;
12420
12421            synchronized (mPackages) {
12422                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12423                if (ps == null) {
12424                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12425                            "Missing settings for moved package " + pkgName);
12426                }
12427
12428                // We moved the entire application as-is, so bring over the
12429                // previously derived ABI information.
12430                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12431                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12432            }
12433
12434        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12435            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12436            scanFlags |= SCAN_NO_DEX;
12437
12438            try {
12439                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12440                        true /* extract libs */);
12441            } catch (PackageManagerException pme) {
12442                Slog.e(TAG, "Error deriving application ABI", pme);
12443                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12444                return;
12445            }
12446
12447            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12448            int result = mPackageDexOptimizer
12449                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12450                            false /* defer */, false /* inclDependencies */,
12451                            true /*bootComplete*/, false /*useJit*/);
12452            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12453                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12454                return;
12455            }
12456        }
12457
12458        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12459            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12460            return;
12461        }
12462
12463        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12464
12465        if (replace) {
12466            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12467                    installerPackageName, volumeUuid, res);
12468        } else {
12469            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12470                    args.user, installerPackageName, volumeUuid, res);
12471        }
12472        synchronized (mPackages) {
12473            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12474            if (ps != null) {
12475                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12476            }
12477        }
12478    }
12479
12480    private void startIntentFilterVerifications(int userId, boolean replacing,
12481            PackageParser.Package pkg) {
12482        if (mIntentFilterVerifierComponent == null) {
12483            Slog.w(TAG, "No IntentFilter verification will not be done as "
12484                    + "there is no IntentFilterVerifier available!");
12485            return;
12486        }
12487
12488        final int verifierUid = getPackageUid(
12489                mIntentFilterVerifierComponent.getPackageName(),
12490                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
12491
12492        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12493        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12494        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12495        mHandler.sendMessage(msg);
12496    }
12497
12498    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12499            PackageParser.Package pkg) {
12500        int size = pkg.activities.size();
12501        if (size == 0) {
12502            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12503                    "No activity, so no need to verify any IntentFilter!");
12504            return;
12505        }
12506
12507        final boolean hasDomainURLs = hasDomainURLs(pkg);
12508        if (!hasDomainURLs) {
12509            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12510                    "No domain URLs, so no need to verify any IntentFilter!");
12511            return;
12512        }
12513
12514        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12515                + " if any IntentFilter from the " + size
12516                + " Activities needs verification ...");
12517
12518        int count = 0;
12519        final String packageName = pkg.packageName;
12520
12521        synchronized (mPackages) {
12522            // If this is a new install and we see that we've already run verification for this
12523            // package, we have nothing to do: it means the state was restored from backup.
12524            if (!replacing) {
12525                IntentFilterVerificationInfo ivi =
12526                        mSettings.getIntentFilterVerificationLPr(packageName);
12527                if (ivi != null) {
12528                    if (DEBUG_DOMAIN_VERIFICATION) {
12529                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12530                                + ivi.getStatusString());
12531                    }
12532                    return;
12533                }
12534            }
12535
12536            // If any filters need to be verified, then all need to be.
12537            boolean needToVerify = false;
12538            for (PackageParser.Activity a : pkg.activities) {
12539                for (ActivityIntentInfo filter : a.intents) {
12540                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12541                        if (DEBUG_DOMAIN_VERIFICATION) {
12542                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12543                        }
12544                        needToVerify = true;
12545                        break;
12546                    }
12547                }
12548            }
12549
12550            if (needToVerify) {
12551                final int verificationId = mIntentFilterVerificationToken++;
12552                for (PackageParser.Activity a : pkg.activities) {
12553                    for (ActivityIntentInfo filter : a.intents) {
12554                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12555                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12556                                    "Verification needed for IntentFilter:" + filter.toString());
12557                            mIntentFilterVerifier.addOneIntentFilterVerification(
12558                                    verifierUid, userId, verificationId, filter, packageName);
12559                            count++;
12560                        }
12561                    }
12562                }
12563            }
12564        }
12565
12566        if (count > 0) {
12567            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12568                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12569                    +  " for userId:" + userId);
12570            mIntentFilterVerifier.startVerifications(userId);
12571        } else {
12572            if (DEBUG_DOMAIN_VERIFICATION) {
12573                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12574            }
12575        }
12576    }
12577
12578    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12579        final ComponentName cn  = filter.activity.getComponentName();
12580        final String packageName = cn.getPackageName();
12581
12582        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12583                packageName);
12584        if (ivi == null) {
12585            return true;
12586        }
12587        int status = ivi.getStatus();
12588        switch (status) {
12589            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12590            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12591                return true;
12592
12593            default:
12594                // Nothing to do
12595                return false;
12596        }
12597    }
12598
12599    private static boolean isMultiArch(PackageSetting ps) {
12600        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12601    }
12602
12603    private static boolean isMultiArch(ApplicationInfo info) {
12604        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12605    }
12606
12607    private static boolean isExternal(PackageParser.Package pkg) {
12608        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12609    }
12610
12611    private static boolean isExternal(PackageSetting ps) {
12612        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12613    }
12614
12615    private static boolean isExternal(ApplicationInfo info) {
12616        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12617    }
12618
12619    private static boolean isSystemApp(PackageParser.Package pkg) {
12620        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12621    }
12622
12623    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12624        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12625    }
12626
12627    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12628        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12629    }
12630
12631    private static boolean isSystemApp(PackageSetting ps) {
12632        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12633    }
12634
12635    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12636        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12637    }
12638
12639    private int packageFlagsToInstallFlags(PackageSetting ps) {
12640        int installFlags = 0;
12641        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12642            // This existing package was an external ASEC install when we have
12643            // the external flag without a UUID
12644            installFlags |= PackageManager.INSTALL_EXTERNAL;
12645        }
12646        if (ps.isForwardLocked()) {
12647            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12648        }
12649        return installFlags;
12650    }
12651
12652    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
12653        if (isExternal(pkg)) {
12654            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12655                return StorageManager.UUID_PRIMARY_PHYSICAL;
12656            } else {
12657                return pkg.volumeUuid;
12658            }
12659        } else {
12660            return StorageManager.UUID_PRIVATE_INTERNAL;
12661        }
12662    }
12663
12664    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12665        if (isExternal(pkg)) {
12666            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12667                return mSettings.getExternalVersion();
12668            } else {
12669                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12670            }
12671        } else {
12672            return mSettings.getInternalVersion();
12673        }
12674    }
12675
12676    private void deleteTempPackageFiles() {
12677        final FilenameFilter filter = new FilenameFilter() {
12678            public boolean accept(File dir, String name) {
12679                return name.startsWith("vmdl") && name.endsWith(".tmp");
12680            }
12681        };
12682        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12683            file.delete();
12684        }
12685    }
12686
12687    @Override
12688    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12689            int flags) {
12690        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12691                flags);
12692    }
12693
12694    @Override
12695    public void deletePackage(final String packageName,
12696            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12697        mContext.enforceCallingOrSelfPermission(
12698                android.Manifest.permission.DELETE_PACKAGES, null);
12699        Preconditions.checkNotNull(packageName);
12700        Preconditions.checkNotNull(observer);
12701        final int uid = Binder.getCallingUid();
12702        if (UserHandle.getUserId(uid) != userId) {
12703            mContext.enforceCallingPermission(
12704                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12705                    "deletePackage for user " + userId);
12706        }
12707        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12708            try {
12709                observer.onPackageDeleted(packageName,
12710                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12711            } catch (RemoteException re) {
12712            }
12713            return;
12714        }
12715
12716        boolean uninstallBlocked = false;
12717        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
12718            int[] users = sUserManager.getUserIds();
12719            for (int i = 0; i < users.length; ++i) {
12720                if (getBlockUninstallForUser(packageName, users[i])) {
12721                    uninstallBlocked = true;
12722                    break;
12723                }
12724            }
12725        } else {
12726            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
12727        }
12728        if (uninstallBlocked) {
12729            try {
12730                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
12731                        null);
12732            } catch (RemoteException re) {
12733            }
12734            return;
12735        }
12736
12737        if (DEBUG_REMOVE) {
12738            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12739        }
12740        // Queue up an async operation since the package deletion may take a little while.
12741        mHandler.post(new Runnable() {
12742            public void run() {
12743                mHandler.removeCallbacks(this);
12744                final int returnCode = deletePackageX(packageName, userId, flags);
12745                if (observer != null) {
12746                    try {
12747                        observer.onPackageDeleted(packageName, returnCode, null);
12748                    } catch (RemoteException e) {
12749                        Log.i(TAG, "Observer no longer exists.");
12750                    } //end catch
12751                } //end if
12752            } //end run
12753        });
12754    }
12755
12756    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12757        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12758                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12759        try {
12760            if (dpm != null) {
12761                if (dpm.isDeviceOwner(packageName)) {
12762                    return true;
12763                }
12764                int[] users;
12765                if (userId == UserHandle.USER_ALL) {
12766                    users = sUserManager.getUserIds();
12767                } else {
12768                    users = new int[]{userId};
12769                }
12770                for (int i = 0; i < users.length; ++i) {
12771                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12772                        return true;
12773                    }
12774                }
12775            }
12776        } catch (RemoteException e) {
12777        }
12778        return false;
12779    }
12780
12781    /**
12782     *  This method is an internal method that could be get invoked either
12783     *  to delete an installed package or to clean up a failed installation.
12784     *  After deleting an installed package, a broadcast is sent to notify any
12785     *  listeners that the package has been installed. For cleaning up a failed
12786     *  installation, the broadcast is not necessary since the package's
12787     *  installation wouldn't have sent the initial broadcast either
12788     *  The key steps in deleting a package are
12789     *  deleting the package information in internal structures like mPackages,
12790     *  deleting the packages base directories through installd
12791     *  updating mSettings to reflect current status
12792     *  persisting settings for later use
12793     *  sending a broadcast if necessary
12794     */
12795    private int deletePackageX(String packageName, int userId, int flags) {
12796        final PackageRemovedInfo info = new PackageRemovedInfo();
12797        final boolean res;
12798
12799        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12800                ? UserHandle.ALL : new UserHandle(userId);
12801
12802        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12803            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12804            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12805        }
12806
12807        boolean removedForAllUsers = false;
12808        boolean systemUpdate = false;
12809
12810        // for the uninstall-updates case and restricted profiles, remember the per-
12811        // userhandle installed state
12812        int[] allUsers;
12813        boolean[] perUserInstalled;
12814        synchronized (mPackages) {
12815            PackageSetting ps = mSettings.mPackages.get(packageName);
12816            allUsers = sUserManager.getUserIds();
12817            perUserInstalled = new boolean[allUsers.length];
12818            for (int i = 0; i < allUsers.length; i++) {
12819                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12820            }
12821        }
12822
12823        synchronized (mInstallLock) {
12824            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
12825            res = deletePackageLI(packageName, removeForUser,
12826                    true, allUsers, perUserInstalled,
12827                    flags | REMOVE_CHATTY, info, true);
12828            systemUpdate = info.isRemovedPackageSystemUpdate;
12829            if (res && !systemUpdate && mPackages.get(packageName) == null) {
12830                removedForAllUsers = true;
12831            }
12832            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
12833                    + " removedForAllUsers=" + removedForAllUsers);
12834        }
12835
12836        if (res) {
12837            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
12838
12839            // If the removed package was a system update, the old system package
12840            // was re-enabled; we need to broadcast this information
12841            if (systemUpdate) {
12842                Bundle extras = new Bundle(1);
12843                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
12844                        ? info.removedAppId : info.uid);
12845                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12846
12847                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
12848                        extras, null, null, null);
12849                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
12850                        extras, null, null, null);
12851                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
12852                        null, packageName, null, null);
12853            }
12854        }
12855        // Force a gc here.
12856        Runtime.getRuntime().gc();
12857        // Delete the resources here after sending the broadcast to let
12858        // other processes clean up before deleting resources.
12859        if (info.args != null) {
12860            synchronized (mInstallLock) {
12861                info.args.doPostDeleteLI(true);
12862            }
12863        }
12864
12865        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
12866    }
12867
12868    class PackageRemovedInfo {
12869        String removedPackage;
12870        int uid = -1;
12871        int removedAppId = -1;
12872        int[] removedUsers = null;
12873        boolean isRemovedPackageSystemUpdate = false;
12874        // Clean up resources deleted packages.
12875        InstallArgs args = null;
12876
12877        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
12878            Bundle extras = new Bundle(1);
12879            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
12880            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
12881            if (replacing) {
12882                extras.putBoolean(Intent.EXTRA_REPLACING, true);
12883            }
12884            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
12885            if (removedPackage != null) {
12886                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
12887                        extras, null, null, removedUsers);
12888                if (fullRemove && !replacing) {
12889                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
12890                            extras, null, null, removedUsers);
12891                }
12892            }
12893            if (removedAppId >= 0) {
12894                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
12895                        removedUsers);
12896            }
12897        }
12898    }
12899
12900    /*
12901     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
12902     * flag is not set, the data directory is removed as well.
12903     * make sure this flag is set for partially installed apps. If not its meaningless to
12904     * delete a partially installed application.
12905     */
12906    private void removePackageDataLI(PackageSetting ps,
12907            int[] allUserHandles, boolean[] perUserInstalled,
12908            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
12909        String packageName = ps.name;
12910        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
12911        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
12912        // Retrieve object to delete permissions for shared user later on
12913        final PackageSetting deletedPs;
12914        // reader
12915        synchronized (mPackages) {
12916            deletedPs = mSettings.mPackages.get(packageName);
12917            if (outInfo != null) {
12918                outInfo.removedPackage = packageName;
12919                outInfo.removedUsers = deletedPs != null
12920                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
12921                        : null;
12922            }
12923        }
12924        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12925            removeDataDirsLI(ps.volumeUuid, packageName);
12926            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
12927        }
12928        // writer
12929        synchronized (mPackages) {
12930            if (deletedPs != null) {
12931                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
12932                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
12933                    clearDefaultBrowserIfNeeded(packageName);
12934                    if (outInfo != null) {
12935                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
12936                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
12937                    }
12938                    updatePermissionsLPw(deletedPs.name, null, 0);
12939                    if (deletedPs.sharedUser != null) {
12940                        // Remove permissions associated with package. Since runtime
12941                        // permissions are per user we have to kill the removed package
12942                        // or packages running under the shared user of the removed
12943                        // package if revoking the permissions requested only by the removed
12944                        // package is successful and this causes a change in gids.
12945                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12946                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
12947                                    userId);
12948                            if (userIdToKill == UserHandle.USER_ALL
12949                                    || userIdToKill >= UserHandle.USER_OWNER) {
12950                                // If gids changed for this user, kill all affected packages.
12951                                mHandler.post(new Runnable() {
12952                                    @Override
12953                                    public void run() {
12954                                        // This has to happen with no lock held.
12955                                        killApplication(deletedPs.name, deletedPs.appId,
12956                                                KILL_APP_REASON_GIDS_CHANGED);
12957                                    }
12958                                });
12959                                break;
12960                            }
12961                        }
12962                    }
12963                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12964                }
12965                // make sure to preserve per-user disabled state if this removal was just
12966                // a downgrade of a system app to the factory package
12967                if (allUserHandles != null && perUserInstalled != null) {
12968                    if (DEBUG_REMOVE) {
12969                        Slog.d(TAG, "Propagating install state across downgrade");
12970                    }
12971                    for (int i = 0; i < allUserHandles.length; i++) {
12972                        if (DEBUG_REMOVE) {
12973                            Slog.d(TAG, "    user " + allUserHandles[i]
12974                                    + " => " + perUserInstalled[i]);
12975                        }
12976                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12977                    }
12978                }
12979            }
12980            // can downgrade to reader
12981            if (writeSettings) {
12982                // Save settings now
12983                mSettings.writeLPr();
12984            }
12985        }
12986        if (outInfo != null) {
12987            // A user ID was deleted here. Go through all users and remove it
12988            // from KeyStore.
12989            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12990        }
12991    }
12992
12993    static boolean locationIsPrivileged(File path) {
12994        try {
12995            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12996                    .getCanonicalPath();
12997            return path.getCanonicalPath().startsWith(privilegedAppDir);
12998        } catch (IOException e) {
12999            Slog.e(TAG, "Unable to access code path " + path);
13000        }
13001        return false;
13002    }
13003
13004    /*
13005     * Tries to delete system package.
13006     */
13007    private boolean deleteSystemPackageLI(PackageSetting newPs,
13008            int[] allUserHandles, boolean[] perUserInstalled,
13009            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13010        final boolean applyUserRestrictions
13011                = (allUserHandles != null) && (perUserInstalled != null);
13012        PackageSetting disabledPs = null;
13013        // Confirm if the system package has been updated
13014        // An updated system app can be deleted. This will also have to restore
13015        // the system pkg from system partition
13016        // reader
13017        synchronized (mPackages) {
13018            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13019        }
13020        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13021                + " disabledPs=" + disabledPs);
13022        if (disabledPs == null) {
13023            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13024            return false;
13025        } else if (DEBUG_REMOVE) {
13026            Slog.d(TAG, "Deleting system pkg from data partition");
13027        }
13028        if (DEBUG_REMOVE) {
13029            if (applyUserRestrictions) {
13030                Slog.d(TAG, "Remembering install states:");
13031                for (int i = 0; i < allUserHandles.length; i++) {
13032                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13033                }
13034            }
13035        }
13036        // Delete the updated package
13037        outInfo.isRemovedPackageSystemUpdate = true;
13038        if (disabledPs.versionCode < newPs.versionCode) {
13039            // Delete data for downgrades
13040            flags &= ~PackageManager.DELETE_KEEP_DATA;
13041        } else {
13042            // Preserve data by setting flag
13043            flags |= PackageManager.DELETE_KEEP_DATA;
13044        }
13045        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13046                allUserHandles, perUserInstalled, outInfo, writeSettings);
13047        if (!ret) {
13048            return false;
13049        }
13050        // writer
13051        synchronized (mPackages) {
13052            // Reinstate the old system package
13053            mSettings.enableSystemPackageLPw(newPs.name);
13054            // Remove any native libraries from the upgraded package.
13055            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13056        }
13057        // Install the system package
13058        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13059        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13060        if (locationIsPrivileged(disabledPs.codePath)) {
13061            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13062        }
13063
13064        final PackageParser.Package newPkg;
13065        try {
13066            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13067        } catch (PackageManagerException e) {
13068            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13069            return false;
13070        }
13071
13072        // writer
13073        synchronized (mPackages) {
13074            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13075
13076            // Propagate the permissions state as we do not want to drop on the floor
13077            // runtime permissions. The update permissions method below will take
13078            // care of removing obsolete permissions and grant install permissions.
13079            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13080            updatePermissionsLPw(newPkg.packageName, newPkg,
13081                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13082
13083            if (applyUserRestrictions) {
13084                if (DEBUG_REMOVE) {
13085                    Slog.d(TAG, "Propagating install state across reinstall");
13086                }
13087                for (int i = 0; i < allUserHandles.length; i++) {
13088                    if (DEBUG_REMOVE) {
13089                        Slog.d(TAG, "    user " + allUserHandles[i]
13090                                + " => " + perUserInstalled[i]);
13091                    }
13092                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13093
13094                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13095                }
13096                // Regardless of writeSettings we need to ensure that this restriction
13097                // state propagation is persisted
13098                mSettings.writeAllUsersPackageRestrictionsLPr();
13099            }
13100            // can downgrade to reader here
13101            if (writeSettings) {
13102                mSettings.writeLPr();
13103            }
13104        }
13105        return true;
13106    }
13107
13108    private boolean deleteInstalledPackageLI(PackageSetting ps,
13109            boolean deleteCodeAndResources, int flags,
13110            int[] allUserHandles, boolean[] perUserInstalled,
13111            PackageRemovedInfo outInfo, boolean writeSettings) {
13112        if (outInfo != null) {
13113            outInfo.uid = ps.appId;
13114        }
13115
13116        // Delete package data from internal structures and also remove data if flag is set
13117        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13118
13119        // Delete application code and resources
13120        if (deleteCodeAndResources && (outInfo != null)) {
13121            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13122                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13123            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13124        }
13125        return true;
13126    }
13127
13128    @Override
13129    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13130            int userId) {
13131        mContext.enforceCallingOrSelfPermission(
13132                android.Manifest.permission.DELETE_PACKAGES, null);
13133        synchronized (mPackages) {
13134            PackageSetting ps = mSettings.mPackages.get(packageName);
13135            if (ps == null) {
13136                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13137                return false;
13138            }
13139            if (!ps.getInstalled(userId)) {
13140                // Can't block uninstall for an app that is not installed or enabled.
13141                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13142                return false;
13143            }
13144            ps.setBlockUninstall(blockUninstall, userId);
13145            mSettings.writePackageRestrictionsLPr(userId);
13146        }
13147        return true;
13148    }
13149
13150    @Override
13151    public boolean getBlockUninstallForUser(String packageName, int userId) {
13152        synchronized (mPackages) {
13153            PackageSetting ps = mSettings.mPackages.get(packageName);
13154            if (ps == null) {
13155                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13156                return false;
13157            }
13158            return ps.getBlockUninstall(userId);
13159        }
13160    }
13161
13162    /*
13163     * This method handles package deletion in general
13164     */
13165    private boolean deletePackageLI(String packageName, UserHandle user,
13166            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13167            int flags, PackageRemovedInfo outInfo,
13168            boolean writeSettings) {
13169        if (packageName == null) {
13170            Slog.w(TAG, "Attempt to delete null packageName.");
13171            return false;
13172        }
13173        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13174        PackageSetting ps;
13175        boolean dataOnly = false;
13176        int removeUser = -1;
13177        int appId = -1;
13178        synchronized (mPackages) {
13179            ps = mSettings.mPackages.get(packageName);
13180            if (ps == null) {
13181                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13182                return false;
13183            }
13184            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13185                    && user.getIdentifier() != UserHandle.USER_ALL) {
13186                // The caller is asking that the package only be deleted for a single
13187                // user.  To do this, we just mark its uninstalled state and delete
13188                // its data.  If this is a system app, we only allow this to happen if
13189                // they have set the special DELETE_SYSTEM_APP which requests different
13190                // semantics than normal for uninstalling system apps.
13191                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13192                final int userId = user.getIdentifier();
13193                ps.setUserState(userId,
13194                        COMPONENT_ENABLED_STATE_DEFAULT,
13195                        false, //installed
13196                        true,  //stopped
13197                        true,  //notLaunched
13198                        false, //hidden
13199                        null, null, null,
13200                        false, // blockUninstall
13201                        ps.readUserState(userId).domainVerificationStatus, 0);
13202                if (!isSystemApp(ps)) {
13203                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13204                        // Other user still have this package installed, so all
13205                        // we need to do is clear this user's data and save that
13206                        // it is uninstalled.
13207                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13208                        removeUser = user.getIdentifier();
13209                        appId = ps.appId;
13210                        scheduleWritePackageRestrictionsLocked(removeUser);
13211                    } else {
13212                        // We need to set it back to 'installed' so the uninstall
13213                        // broadcasts will be sent correctly.
13214                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13215                        ps.setInstalled(true, user.getIdentifier());
13216                    }
13217                } else {
13218                    // This is a system app, so we assume that the
13219                    // other users still have this package installed, so all
13220                    // we need to do is clear this user's data and save that
13221                    // it is uninstalled.
13222                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13223                    removeUser = user.getIdentifier();
13224                    appId = ps.appId;
13225                    scheduleWritePackageRestrictionsLocked(removeUser);
13226                }
13227            }
13228        }
13229
13230        if (removeUser >= 0) {
13231            // From above, we determined that we are deleting this only
13232            // for a single user.  Continue the work here.
13233            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13234            if (outInfo != null) {
13235                outInfo.removedPackage = packageName;
13236                outInfo.removedAppId = appId;
13237                outInfo.removedUsers = new int[] {removeUser};
13238            }
13239            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13240            removeKeystoreDataIfNeeded(removeUser, appId);
13241            schedulePackageCleaning(packageName, removeUser, false);
13242            synchronized (mPackages) {
13243                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13244                    scheduleWritePackageRestrictionsLocked(removeUser);
13245                }
13246                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13247            }
13248            return true;
13249        }
13250
13251        if (dataOnly) {
13252            // Delete application data first
13253            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13254            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13255            return true;
13256        }
13257
13258        boolean ret = false;
13259        if (isSystemApp(ps)) {
13260            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13261            // When an updated system application is deleted we delete the existing resources as well and
13262            // fall back to existing code in system partition
13263            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13264                    flags, outInfo, writeSettings);
13265        } else {
13266            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13267            // Kill application pre-emptively especially for apps on sd.
13268            killApplication(packageName, ps.appId, "uninstall pkg");
13269            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13270                    allUserHandles, perUserInstalled,
13271                    outInfo, writeSettings);
13272        }
13273
13274        return ret;
13275    }
13276
13277    private final class ClearStorageConnection implements ServiceConnection {
13278        IMediaContainerService mContainerService;
13279
13280        @Override
13281        public void onServiceConnected(ComponentName name, IBinder service) {
13282            synchronized (this) {
13283                mContainerService = IMediaContainerService.Stub.asInterface(service);
13284                notifyAll();
13285            }
13286        }
13287
13288        @Override
13289        public void onServiceDisconnected(ComponentName name) {
13290        }
13291    }
13292
13293    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13294        final boolean mounted;
13295        if (Environment.isExternalStorageEmulated()) {
13296            mounted = true;
13297        } else {
13298            final String status = Environment.getExternalStorageState();
13299
13300            mounted = status.equals(Environment.MEDIA_MOUNTED)
13301                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13302        }
13303
13304        if (!mounted) {
13305            return;
13306        }
13307
13308        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13309        int[] users;
13310        if (userId == UserHandle.USER_ALL) {
13311            users = sUserManager.getUserIds();
13312        } else {
13313            users = new int[] { userId };
13314        }
13315        final ClearStorageConnection conn = new ClearStorageConnection();
13316        if (mContext.bindServiceAsUser(
13317                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
13318            try {
13319                for (int curUser : users) {
13320                    long timeout = SystemClock.uptimeMillis() + 5000;
13321                    synchronized (conn) {
13322                        long now = SystemClock.uptimeMillis();
13323                        while (conn.mContainerService == null && now < timeout) {
13324                            try {
13325                                conn.wait(timeout - now);
13326                            } catch (InterruptedException e) {
13327                            }
13328                        }
13329                    }
13330                    if (conn.mContainerService == null) {
13331                        return;
13332                    }
13333
13334                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13335                    clearDirectory(conn.mContainerService,
13336                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13337                    if (allData) {
13338                        clearDirectory(conn.mContainerService,
13339                                userEnv.buildExternalStorageAppDataDirs(packageName));
13340                        clearDirectory(conn.mContainerService,
13341                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13342                    }
13343                }
13344            } finally {
13345                mContext.unbindService(conn);
13346            }
13347        }
13348    }
13349
13350    @Override
13351    public void clearApplicationUserData(final String packageName,
13352            final IPackageDataObserver observer, final int userId) {
13353        mContext.enforceCallingOrSelfPermission(
13354                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13355        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13356        // Queue up an async operation since the package deletion may take a little while.
13357        mHandler.post(new Runnable() {
13358            public void run() {
13359                mHandler.removeCallbacks(this);
13360                final boolean succeeded;
13361                synchronized (mInstallLock) {
13362                    succeeded = clearApplicationUserDataLI(packageName, userId);
13363                }
13364                clearExternalStorageDataSync(packageName, userId, true);
13365                if (succeeded) {
13366                    // invoke DeviceStorageMonitor's update method to clear any notifications
13367                    DeviceStorageMonitorInternal
13368                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13369                    if (dsm != null) {
13370                        dsm.checkMemory();
13371                    }
13372                }
13373                if(observer != null) {
13374                    try {
13375                        observer.onRemoveCompleted(packageName, succeeded);
13376                    } catch (RemoteException e) {
13377                        Log.i(TAG, "Observer no longer exists.");
13378                    }
13379                } //end if observer
13380            } //end run
13381        });
13382    }
13383
13384    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13385        if (packageName == null) {
13386            Slog.w(TAG, "Attempt to delete null packageName.");
13387            return false;
13388        }
13389
13390        // Try finding details about the requested package
13391        PackageParser.Package pkg;
13392        synchronized (mPackages) {
13393            pkg = mPackages.get(packageName);
13394            if (pkg == null) {
13395                final PackageSetting ps = mSettings.mPackages.get(packageName);
13396                if (ps != null) {
13397                    pkg = ps.pkg;
13398                }
13399            }
13400
13401            if (pkg == null) {
13402                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13403                return false;
13404            }
13405
13406            PackageSetting ps = (PackageSetting) pkg.mExtras;
13407            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13408        }
13409
13410        // Always delete data directories for package, even if we found no other
13411        // record of app. This helps users recover from UID mismatches without
13412        // resorting to a full data wipe.
13413        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13414        if (retCode < 0) {
13415            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13416            return false;
13417        }
13418
13419        final int appId = pkg.applicationInfo.uid;
13420        removeKeystoreDataIfNeeded(userId, appId);
13421
13422        // Create a native library symlink only if we have native libraries
13423        // and if the native libraries are 32 bit libraries. We do not provide
13424        // this symlink for 64 bit libraries.
13425        if (pkg.applicationInfo.primaryCpuAbi != null &&
13426                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13427            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13428            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13429                    nativeLibPath, userId) < 0) {
13430                Slog.w(TAG, "Failed linking native library dir");
13431                return false;
13432            }
13433        }
13434
13435        return true;
13436    }
13437
13438    /**
13439     * Reverts user permission state changes (permissions and flags) in
13440     * all packages for a given user.
13441     *
13442     * @param userId The device user for which to do a reset.
13443     */
13444    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13445        final int packageCount = mPackages.size();
13446        for (int i = 0; i < packageCount; i++) {
13447            PackageParser.Package pkg = mPackages.valueAt(i);
13448            PackageSetting ps = (PackageSetting) pkg.mExtras;
13449            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13450        }
13451    }
13452
13453    /**
13454     * Reverts user permission state changes (permissions and flags).
13455     *
13456     * @param ps The package for which to reset.
13457     * @param userId The device user for which to do a reset.
13458     */
13459    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13460            final PackageSetting ps, final int userId) {
13461        if (ps.pkg == null) {
13462            return;
13463        }
13464
13465        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13466                | FLAG_PERMISSION_USER_FIXED
13467                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13468
13469        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13470                | FLAG_PERMISSION_POLICY_FIXED;
13471
13472        boolean writeInstallPermissions = false;
13473        boolean writeRuntimePermissions = false;
13474
13475        final int permissionCount = ps.pkg.requestedPermissions.size();
13476        for (int i = 0; i < permissionCount; i++) {
13477            String permission = ps.pkg.requestedPermissions.get(i);
13478
13479            BasePermission bp = mSettings.mPermissions.get(permission);
13480            if (bp == null) {
13481                continue;
13482            }
13483
13484            // If shared user we just reset the state to which only this app contributed.
13485            if (ps.sharedUser != null) {
13486                boolean used = false;
13487                final int packageCount = ps.sharedUser.packages.size();
13488                for (int j = 0; j < packageCount; j++) {
13489                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13490                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13491                            && pkg.pkg.requestedPermissions.contains(permission)) {
13492                        used = true;
13493                        break;
13494                    }
13495                }
13496                if (used) {
13497                    continue;
13498                }
13499            }
13500
13501            PermissionsState permissionsState = ps.getPermissionsState();
13502
13503            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13504
13505            // Always clear the user settable flags.
13506            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13507                    bp.name) != null;
13508            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13509                if (hasInstallState) {
13510                    writeInstallPermissions = true;
13511                } else {
13512                    writeRuntimePermissions = true;
13513                }
13514            }
13515
13516            // Below is only runtime permission handling.
13517            if (!bp.isRuntime()) {
13518                continue;
13519            }
13520
13521            // Never clobber system or policy.
13522            if ((oldFlags & policyOrSystemFlags) != 0) {
13523                continue;
13524            }
13525
13526            // If this permission was granted by default, make sure it is.
13527            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13528                if (permissionsState.grantRuntimePermission(bp, userId)
13529                        != PERMISSION_OPERATION_FAILURE) {
13530                    writeRuntimePermissions = true;
13531                }
13532            } else {
13533                // Otherwise, reset the permission.
13534                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13535                switch (revokeResult) {
13536                    case PERMISSION_OPERATION_SUCCESS: {
13537                        writeRuntimePermissions = true;
13538                    } break;
13539
13540                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13541                        writeRuntimePermissions = true;
13542                        final int appId = ps.appId;
13543                        mHandler.post(new Runnable() {
13544                            @Override
13545                            public void run() {
13546                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13547                            }
13548                        });
13549                    } break;
13550                }
13551            }
13552        }
13553
13554        // Synchronously write as we are taking permissions away.
13555        if (writeRuntimePermissions) {
13556            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13557        }
13558
13559        // Synchronously write as we are taking permissions away.
13560        if (writeInstallPermissions) {
13561            mSettings.writeLPr();
13562        }
13563    }
13564
13565    /**
13566     * Remove entries from the keystore daemon. Will only remove it if the
13567     * {@code appId} is valid.
13568     */
13569    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13570        if (appId < 0) {
13571            return;
13572        }
13573
13574        final KeyStore keyStore = KeyStore.getInstance();
13575        if (keyStore != null) {
13576            if (userId == UserHandle.USER_ALL) {
13577                for (final int individual : sUserManager.getUserIds()) {
13578                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13579                }
13580            } else {
13581                keyStore.clearUid(UserHandle.getUid(userId, appId));
13582            }
13583        } else {
13584            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13585        }
13586    }
13587
13588    @Override
13589    public void deleteApplicationCacheFiles(final String packageName,
13590            final IPackageDataObserver observer) {
13591        mContext.enforceCallingOrSelfPermission(
13592                android.Manifest.permission.DELETE_CACHE_FILES, null);
13593        // Queue up an async operation since the package deletion may take a little while.
13594        final int userId = UserHandle.getCallingUserId();
13595        mHandler.post(new Runnable() {
13596            public void run() {
13597                mHandler.removeCallbacks(this);
13598                final boolean succeded;
13599                synchronized (mInstallLock) {
13600                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13601                }
13602                clearExternalStorageDataSync(packageName, userId, false);
13603                if (observer != null) {
13604                    try {
13605                        observer.onRemoveCompleted(packageName, succeded);
13606                    } catch (RemoteException e) {
13607                        Log.i(TAG, "Observer no longer exists.");
13608                    }
13609                } //end if observer
13610            } //end run
13611        });
13612    }
13613
13614    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13615        if (packageName == null) {
13616            Slog.w(TAG, "Attempt to delete null packageName.");
13617            return false;
13618        }
13619        PackageParser.Package p;
13620        synchronized (mPackages) {
13621            p = mPackages.get(packageName);
13622        }
13623        if (p == null) {
13624            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13625            return false;
13626        }
13627        final ApplicationInfo applicationInfo = p.applicationInfo;
13628        if (applicationInfo == null) {
13629            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13630            return false;
13631        }
13632        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13633        if (retCode < 0) {
13634            Slog.w(TAG, "Couldn't remove cache files for package: "
13635                       + packageName + " u" + userId);
13636            return false;
13637        }
13638        return true;
13639    }
13640
13641    @Override
13642    public void getPackageSizeInfo(final String packageName, int userHandle,
13643            final IPackageStatsObserver observer) {
13644        mContext.enforceCallingOrSelfPermission(
13645                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13646        if (packageName == null) {
13647            throw new IllegalArgumentException("Attempt to get size of null packageName");
13648        }
13649
13650        PackageStats stats = new PackageStats(packageName, userHandle);
13651
13652        /*
13653         * Queue up an async operation since the package measurement may take a
13654         * little while.
13655         */
13656        Message msg = mHandler.obtainMessage(INIT_COPY);
13657        msg.obj = new MeasureParams(stats, observer);
13658        mHandler.sendMessage(msg);
13659    }
13660
13661    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13662            PackageStats pStats) {
13663        if (packageName == null) {
13664            Slog.w(TAG, "Attempt to get size of null packageName.");
13665            return false;
13666        }
13667        PackageParser.Package p;
13668        boolean dataOnly = false;
13669        String libDirRoot = null;
13670        String asecPath = null;
13671        PackageSetting ps = null;
13672        synchronized (mPackages) {
13673            p = mPackages.get(packageName);
13674            ps = mSettings.mPackages.get(packageName);
13675            if(p == null) {
13676                dataOnly = true;
13677                if((ps == null) || (ps.pkg == null)) {
13678                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13679                    return false;
13680                }
13681                p = ps.pkg;
13682            }
13683            if (ps != null) {
13684                libDirRoot = ps.legacyNativeLibraryPathString;
13685            }
13686            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
13687                final long token = Binder.clearCallingIdentity();
13688                try {
13689                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13690                    if (secureContainerId != null) {
13691                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13692                    }
13693                } finally {
13694                    Binder.restoreCallingIdentity(token);
13695                }
13696            }
13697        }
13698        String publicSrcDir = null;
13699        if(!dataOnly) {
13700            final ApplicationInfo applicationInfo = p.applicationInfo;
13701            if (applicationInfo == null) {
13702                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13703                return false;
13704            }
13705            if (p.isForwardLocked()) {
13706                publicSrcDir = applicationInfo.getBaseResourcePath();
13707            }
13708        }
13709        // TODO: extend to measure size of split APKs
13710        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13711        // not just the first level.
13712        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13713        // just the primary.
13714        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13715
13716        String apkPath;
13717        File packageDir = new File(p.codePath);
13718
13719        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13720            apkPath = packageDir.getAbsolutePath();
13721            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13722            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13723                libDirRoot = null;
13724            }
13725        } else {
13726            apkPath = p.baseCodePath;
13727        }
13728
13729        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
13730                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13731        if (res < 0) {
13732            return false;
13733        }
13734
13735        // Fix-up for forward-locked applications in ASEC containers.
13736        if (!isExternal(p)) {
13737            pStats.codeSize += pStats.externalCodeSize;
13738            pStats.externalCodeSize = 0L;
13739        }
13740
13741        return true;
13742    }
13743
13744
13745    @Override
13746    public void addPackageToPreferred(String packageName) {
13747        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13748    }
13749
13750    @Override
13751    public void removePackageFromPreferred(String packageName) {
13752        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13753    }
13754
13755    @Override
13756    public List<PackageInfo> getPreferredPackages(int flags) {
13757        return new ArrayList<PackageInfo>();
13758    }
13759
13760    private int getUidTargetSdkVersionLockedLPr(int uid) {
13761        Object obj = mSettings.getUserIdLPr(uid);
13762        if (obj instanceof SharedUserSetting) {
13763            final SharedUserSetting sus = (SharedUserSetting) obj;
13764            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13765            final Iterator<PackageSetting> it = sus.packages.iterator();
13766            while (it.hasNext()) {
13767                final PackageSetting ps = it.next();
13768                if (ps.pkg != null) {
13769                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13770                    if (v < vers) vers = v;
13771                }
13772            }
13773            return vers;
13774        } else if (obj instanceof PackageSetting) {
13775            final PackageSetting ps = (PackageSetting) obj;
13776            if (ps.pkg != null) {
13777                return ps.pkg.applicationInfo.targetSdkVersion;
13778            }
13779        }
13780        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13781    }
13782
13783    @Override
13784    public void addPreferredActivity(IntentFilter filter, int match,
13785            ComponentName[] set, ComponentName activity, int userId) {
13786        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13787                "Adding preferred");
13788    }
13789
13790    private void addPreferredActivityInternal(IntentFilter filter, int match,
13791            ComponentName[] set, ComponentName activity, boolean always, int userId,
13792            String opname) {
13793        // writer
13794        int callingUid = Binder.getCallingUid();
13795        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13796        if (filter.countActions() == 0) {
13797            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13798            return;
13799        }
13800        synchronized (mPackages) {
13801            if (mContext.checkCallingOrSelfPermission(
13802                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13803                    != PackageManager.PERMISSION_GRANTED) {
13804                if (getUidTargetSdkVersionLockedLPr(callingUid)
13805                        < Build.VERSION_CODES.FROYO) {
13806                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
13807                            + callingUid);
13808                    return;
13809                }
13810                mContext.enforceCallingOrSelfPermission(
13811                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13812            }
13813
13814            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
13815            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
13816                    + userId + ":");
13817            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13818            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
13819            scheduleWritePackageRestrictionsLocked(userId);
13820        }
13821    }
13822
13823    @Override
13824    public void replacePreferredActivity(IntentFilter filter, int match,
13825            ComponentName[] set, ComponentName activity, int userId) {
13826        if (filter.countActions() != 1) {
13827            throw new IllegalArgumentException(
13828                    "replacePreferredActivity expects filter to have only 1 action.");
13829        }
13830        if (filter.countDataAuthorities() != 0
13831                || filter.countDataPaths() != 0
13832                || filter.countDataSchemes() > 1
13833                || filter.countDataTypes() != 0) {
13834            throw new IllegalArgumentException(
13835                    "replacePreferredActivity expects filter to have no data authorities, " +
13836                    "paths, or types; and at most one scheme.");
13837        }
13838
13839        final int callingUid = Binder.getCallingUid();
13840        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
13841        synchronized (mPackages) {
13842            if (mContext.checkCallingOrSelfPermission(
13843                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13844                    != PackageManager.PERMISSION_GRANTED) {
13845                if (getUidTargetSdkVersionLockedLPr(callingUid)
13846                        < Build.VERSION_CODES.FROYO) {
13847                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
13848                            + Binder.getCallingUid());
13849                    return;
13850                }
13851                mContext.enforceCallingOrSelfPermission(
13852                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13853            }
13854
13855            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
13856            if (pir != null) {
13857                // Get all of the existing entries that exactly match this filter.
13858                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
13859                if (existing != null && existing.size() == 1) {
13860                    PreferredActivity cur = existing.get(0);
13861                    if (DEBUG_PREFERRED) {
13862                        Slog.i(TAG, "Checking replace of preferred:");
13863                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13864                        if (!cur.mPref.mAlways) {
13865                            Slog.i(TAG, "  -- CUR; not mAlways!");
13866                        } else {
13867                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
13868                            Slog.i(TAG, "  -- CUR: mSet="
13869                                    + Arrays.toString(cur.mPref.mSetComponents));
13870                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
13871                            Slog.i(TAG, "  -- NEW: mMatch="
13872                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
13873                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
13874                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
13875                        }
13876                    }
13877                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
13878                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
13879                            && cur.mPref.sameSet(set)) {
13880                        // Setting the preferred activity to what it happens to be already
13881                        if (DEBUG_PREFERRED) {
13882                            Slog.i(TAG, "Replacing with same preferred activity "
13883                                    + cur.mPref.mShortComponent + " for user "
13884                                    + userId + ":");
13885                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13886                        }
13887                        return;
13888                    }
13889                }
13890
13891                if (existing != null) {
13892                    if (DEBUG_PREFERRED) {
13893                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
13894                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
13895                    }
13896                    for (int i = 0; i < existing.size(); i++) {
13897                        PreferredActivity pa = existing.get(i);
13898                        if (DEBUG_PREFERRED) {
13899                            Slog.i(TAG, "Removing existing preferred activity "
13900                                    + pa.mPref.mComponent + ":");
13901                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
13902                        }
13903                        pir.removeFilter(pa);
13904                    }
13905                }
13906            }
13907            addPreferredActivityInternal(filter, match, set, activity, true, userId,
13908                    "Replacing preferred");
13909        }
13910    }
13911
13912    @Override
13913    public void clearPackagePreferredActivities(String packageName) {
13914        final int uid = Binder.getCallingUid();
13915        // writer
13916        synchronized (mPackages) {
13917            PackageParser.Package pkg = mPackages.get(packageName);
13918            if (pkg == null || pkg.applicationInfo.uid != uid) {
13919                if (mContext.checkCallingOrSelfPermission(
13920                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13921                        != PackageManager.PERMISSION_GRANTED) {
13922                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
13923                            < Build.VERSION_CODES.FROYO) {
13924                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
13925                                + Binder.getCallingUid());
13926                        return;
13927                    }
13928                    mContext.enforceCallingOrSelfPermission(
13929                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
13930                }
13931            }
13932
13933            int user = UserHandle.getCallingUserId();
13934            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
13935                scheduleWritePackageRestrictionsLocked(user);
13936            }
13937        }
13938    }
13939
13940    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13941    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
13942        ArrayList<PreferredActivity> removed = null;
13943        boolean changed = false;
13944        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13945            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
13946            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13947            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
13948                continue;
13949            }
13950            Iterator<PreferredActivity> it = pir.filterIterator();
13951            while (it.hasNext()) {
13952                PreferredActivity pa = it.next();
13953                // Mark entry for removal only if it matches the package name
13954                // and the entry is of type "always".
13955                if (packageName == null ||
13956                        (pa.mPref.mComponent.getPackageName().equals(packageName)
13957                                && pa.mPref.mAlways)) {
13958                    if (removed == null) {
13959                        removed = new ArrayList<PreferredActivity>();
13960                    }
13961                    removed.add(pa);
13962                }
13963            }
13964            if (removed != null) {
13965                for (int j=0; j<removed.size(); j++) {
13966                    PreferredActivity pa = removed.get(j);
13967                    pir.removeFilter(pa);
13968                }
13969                changed = true;
13970            }
13971        }
13972        return changed;
13973    }
13974
13975    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13976    private void clearIntentFilterVerificationsLPw(int userId) {
13977        final int packageCount = mPackages.size();
13978        for (int i = 0; i < packageCount; i++) {
13979            PackageParser.Package pkg = mPackages.valueAt(i);
13980            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
13981        }
13982    }
13983
13984    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
13985    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
13986        if (userId == UserHandle.USER_ALL) {
13987            if (mSettings.removeIntentFilterVerificationLPw(packageName,
13988                    sUserManager.getUserIds())) {
13989                for (int oneUserId : sUserManager.getUserIds()) {
13990                    scheduleWritePackageRestrictionsLocked(oneUserId);
13991                }
13992            }
13993        } else {
13994            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
13995                scheduleWritePackageRestrictionsLocked(userId);
13996            }
13997        }
13998    }
13999
14000    void clearDefaultBrowserIfNeeded(String packageName) {
14001        for (int oneUserId : sUserManager.getUserIds()) {
14002            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14003            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14004            if (packageName.equals(defaultBrowserPackageName)) {
14005                setDefaultBrowserPackageName(null, oneUserId);
14006            }
14007        }
14008    }
14009
14010    @Override
14011    public void resetApplicationPreferences(int userId) {
14012        mContext.enforceCallingOrSelfPermission(
14013                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14014        // writer
14015        synchronized (mPackages) {
14016            final long identity = Binder.clearCallingIdentity();
14017            try {
14018                clearPackagePreferredActivitiesLPw(null, userId);
14019                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14020                // TODO: We have to reset the default SMS and Phone. This requires
14021                // significant refactoring to keep all default apps in the package
14022                // manager (cleaner but more work) or have the services provide
14023                // callbacks to the package manager to request a default app reset.
14024                applyFactoryDefaultBrowserLPw(userId);
14025                clearIntentFilterVerificationsLPw(userId);
14026                primeDomainVerificationsLPw(userId);
14027                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14028                scheduleWritePackageRestrictionsLocked(userId);
14029            } finally {
14030                Binder.restoreCallingIdentity(identity);
14031            }
14032        }
14033    }
14034
14035    @Override
14036    public int getPreferredActivities(List<IntentFilter> outFilters,
14037            List<ComponentName> outActivities, String packageName) {
14038
14039        int num = 0;
14040        final int userId = UserHandle.getCallingUserId();
14041        // reader
14042        synchronized (mPackages) {
14043            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14044            if (pir != null) {
14045                final Iterator<PreferredActivity> it = pir.filterIterator();
14046                while (it.hasNext()) {
14047                    final PreferredActivity pa = it.next();
14048                    if (packageName == null
14049                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14050                                    && pa.mPref.mAlways)) {
14051                        if (outFilters != null) {
14052                            outFilters.add(new IntentFilter(pa));
14053                        }
14054                        if (outActivities != null) {
14055                            outActivities.add(pa.mPref.mComponent);
14056                        }
14057                    }
14058                }
14059            }
14060        }
14061
14062        return num;
14063    }
14064
14065    @Override
14066    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14067            int userId) {
14068        int callingUid = Binder.getCallingUid();
14069        if (callingUid != Process.SYSTEM_UID) {
14070            throw new SecurityException(
14071                    "addPersistentPreferredActivity can only be run by the system");
14072        }
14073        if (filter.countActions() == 0) {
14074            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14075            return;
14076        }
14077        synchronized (mPackages) {
14078            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14079                    " :");
14080            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14081            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14082                    new PersistentPreferredActivity(filter, activity));
14083            scheduleWritePackageRestrictionsLocked(userId);
14084        }
14085    }
14086
14087    @Override
14088    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14089        int callingUid = Binder.getCallingUid();
14090        if (callingUid != Process.SYSTEM_UID) {
14091            throw new SecurityException(
14092                    "clearPackagePersistentPreferredActivities can only be run by the system");
14093        }
14094        ArrayList<PersistentPreferredActivity> removed = null;
14095        boolean changed = false;
14096        synchronized (mPackages) {
14097            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14098                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14099                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14100                        .valueAt(i);
14101                if (userId != thisUserId) {
14102                    continue;
14103                }
14104                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14105                while (it.hasNext()) {
14106                    PersistentPreferredActivity ppa = it.next();
14107                    // Mark entry for removal only if it matches the package name.
14108                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14109                        if (removed == null) {
14110                            removed = new ArrayList<PersistentPreferredActivity>();
14111                        }
14112                        removed.add(ppa);
14113                    }
14114                }
14115                if (removed != null) {
14116                    for (int j=0; j<removed.size(); j++) {
14117                        PersistentPreferredActivity ppa = removed.get(j);
14118                        ppir.removeFilter(ppa);
14119                    }
14120                    changed = true;
14121                }
14122            }
14123
14124            if (changed) {
14125                scheduleWritePackageRestrictionsLocked(userId);
14126            }
14127        }
14128    }
14129
14130    /**
14131     * Common machinery for picking apart a restored XML blob and passing
14132     * it to a caller-supplied functor to be applied to the running system.
14133     */
14134    private void restoreFromXml(XmlPullParser parser, int userId,
14135            String expectedStartTag, BlobXmlRestorer functor)
14136            throws IOException, XmlPullParserException {
14137        int type;
14138        while ((type = parser.next()) != XmlPullParser.START_TAG
14139                && type != XmlPullParser.END_DOCUMENT) {
14140        }
14141        if (type != XmlPullParser.START_TAG) {
14142            // oops didn't find a start tag?!
14143            if (DEBUG_BACKUP) {
14144                Slog.e(TAG, "Didn't find start tag during restore");
14145            }
14146            return;
14147        }
14148
14149        // this is supposed to be TAG_PREFERRED_BACKUP
14150        if (!expectedStartTag.equals(parser.getName())) {
14151            if (DEBUG_BACKUP) {
14152                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14153            }
14154            return;
14155        }
14156
14157        // skip interfering stuff, then we're aligned with the backing implementation
14158        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14159        functor.apply(parser, userId);
14160    }
14161
14162    private interface BlobXmlRestorer {
14163        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14164    }
14165
14166    /**
14167     * Non-Binder method, support for the backup/restore mechanism: write the
14168     * full set of preferred activities in its canonical XML format.  Returns the
14169     * XML output as a byte array, or null if there is none.
14170     */
14171    @Override
14172    public byte[] getPreferredActivityBackup(int userId) {
14173        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14174            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14175        }
14176
14177        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14178        try {
14179            final XmlSerializer serializer = new FastXmlSerializer();
14180            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14181            serializer.startDocument(null, true);
14182            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14183
14184            synchronized (mPackages) {
14185                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14186            }
14187
14188            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14189            serializer.endDocument();
14190            serializer.flush();
14191        } catch (Exception e) {
14192            if (DEBUG_BACKUP) {
14193                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14194            }
14195            return null;
14196        }
14197
14198        return dataStream.toByteArray();
14199    }
14200
14201    @Override
14202    public void restorePreferredActivities(byte[] backup, int userId) {
14203        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14204            throw new SecurityException("Only the system may call restorePreferredActivities()");
14205        }
14206
14207        try {
14208            final XmlPullParser parser = Xml.newPullParser();
14209            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14210            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14211                    new BlobXmlRestorer() {
14212                        @Override
14213                        public void apply(XmlPullParser parser, int userId)
14214                                throws XmlPullParserException, IOException {
14215                            synchronized (mPackages) {
14216                                mSettings.readPreferredActivitiesLPw(parser, userId);
14217                            }
14218                        }
14219                    } );
14220        } catch (Exception e) {
14221            if (DEBUG_BACKUP) {
14222                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14223            }
14224        }
14225    }
14226
14227    /**
14228     * Non-Binder method, support for the backup/restore mechanism: write the
14229     * default browser (etc) settings in its canonical XML format.  Returns the default
14230     * browser XML representation as a byte array, or null if there is none.
14231     */
14232    @Override
14233    public byte[] getDefaultAppsBackup(int userId) {
14234        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14235            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14236        }
14237
14238        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14239        try {
14240            final XmlSerializer serializer = new FastXmlSerializer();
14241            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14242            serializer.startDocument(null, true);
14243            serializer.startTag(null, TAG_DEFAULT_APPS);
14244
14245            synchronized (mPackages) {
14246                mSettings.writeDefaultAppsLPr(serializer, userId);
14247            }
14248
14249            serializer.endTag(null, TAG_DEFAULT_APPS);
14250            serializer.endDocument();
14251            serializer.flush();
14252        } catch (Exception e) {
14253            if (DEBUG_BACKUP) {
14254                Slog.e(TAG, "Unable to write default apps for backup", e);
14255            }
14256            return null;
14257        }
14258
14259        return dataStream.toByteArray();
14260    }
14261
14262    @Override
14263    public void restoreDefaultApps(byte[] backup, int userId) {
14264        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14265            throw new SecurityException("Only the system may call restoreDefaultApps()");
14266        }
14267
14268        try {
14269            final XmlPullParser parser = Xml.newPullParser();
14270            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14271            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14272                    new BlobXmlRestorer() {
14273                        @Override
14274                        public void apply(XmlPullParser parser, int userId)
14275                                throws XmlPullParserException, IOException {
14276                            synchronized (mPackages) {
14277                                mSettings.readDefaultAppsLPw(parser, userId);
14278                            }
14279                        }
14280                    } );
14281        } catch (Exception e) {
14282            if (DEBUG_BACKUP) {
14283                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14284            }
14285        }
14286    }
14287
14288    @Override
14289    public byte[] getIntentFilterVerificationBackup(int userId) {
14290        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14291            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14292        }
14293
14294        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14295        try {
14296            final XmlSerializer serializer = new FastXmlSerializer();
14297            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14298            serializer.startDocument(null, true);
14299            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14300
14301            synchronized (mPackages) {
14302                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14303            }
14304
14305            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14306            serializer.endDocument();
14307            serializer.flush();
14308        } catch (Exception e) {
14309            if (DEBUG_BACKUP) {
14310                Slog.e(TAG, "Unable to write default apps for backup", e);
14311            }
14312            return null;
14313        }
14314
14315        return dataStream.toByteArray();
14316    }
14317
14318    @Override
14319    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14320        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14321            throw new SecurityException("Only the system may call restorePreferredActivities()");
14322        }
14323
14324        try {
14325            final XmlPullParser parser = Xml.newPullParser();
14326            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14327            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14328                    new BlobXmlRestorer() {
14329                        @Override
14330                        public void apply(XmlPullParser parser, int userId)
14331                                throws XmlPullParserException, IOException {
14332                            synchronized (mPackages) {
14333                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14334                                mSettings.writeLPr();
14335                            }
14336                        }
14337                    } );
14338        } catch (Exception e) {
14339            if (DEBUG_BACKUP) {
14340                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14341            }
14342        }
14343    }
14344
14345    @Override
14346    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14347            int sourceUserId, int targetUserId, int flags) {
14348        mContext.enforceCallingOrSelfPermission(
14349                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14350        int callingUid = Binder.getCallingUid();
14351        enforceOwnerRights(ownerPackage, callingUid);
14352        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14353        if (intentFilter.countActions() == 0) {
14354            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14355            return;
14356        }
14357        synchronized (mPackages) {
14358            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14359                    ownerPackage, targetUserId, flags);
14360            CrossProfileIntentResolver resolver =
14361                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14362            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14363            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14364            if (existing != null) {
14365                int size = existing.size();
14366                for (int i = 0; i < size; i++) {
14367                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14368                        return;
14369                    }
14370                }
14371            }
14372            resolver.addFilter(newFilter);
14373            scheduleWritePackageRestrictionsLocked(sourceUserId);
14374        }
14375    }
14376
14377    @Override
14378    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14379        mContext.enforceCallingOrSelfPermission(
14380                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14381        int callingUid = Binder.getCallingUid();
14382        enforceOwnerRights(ownerPackage, callingUid);
14383        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14384        synchronized (mPackages) {
14385            CrossProfileIntentResolver resolver =
14386                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14387            ArraySet<CrossProfileIntentFilter> set =
14388                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14389            for (CrossProfileIntentFilter filter : set) {
14390                if (filter.getOwnerPackage().equals(ownerPackage)) {
14391                    resolver.removeFilter(filter);
14392                }
14393            }
14394            scheduleWritePackageRestrictionsLocked(sourceUserId);
14395        }
14396    }
14397
14398    // Enforcing that callingUid is owning pkg on userId
14399    private void enforceOwnerRights(String pkg, int callingUid) {
14400        // The system owns everything.
14401        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14402            return;
14403        }
14404        int callingUserId = UserHandle.getUserId(callingUid);
14405        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14406        if (pi == null) {
14407            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14408                    + callingUserId);
14409        }
14410        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14411            throw new SecurityException("Calling uid " + callingUid
14412                    + " does not own package " + pkg);
14413        }
14414    }
14415
14416    @Override
14417    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14418        Intent intent = new Intent(Intent.ACTION_MAIN);
14419        intent.addCategory(Intent.CATEGORY_HOME);
14420
14421        final int callingUserId = UserHandle.getCallingUserId();
14422        List<ResolveInfo> list = queryIntentActivities(intent, null,
14423                PackageManager.GET_META_DATA, callingUserId);
14424        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14425                true, false, false, callingUserId);
14426
14427        allHomeCandidates.clear();
14428        if (list != null) {
14429            for (ResolveInfo ri : list) {
14430                allHomeCandidates.add(ri);
14431            }
14432        }
14433        return (preferred == null || preferred.activityInfo == null)
14434                ? null
14435                : new ComponentName(preferred.activityInfo.packageName,
14436                        preferred.activityInfo.name);
14437    }
14438
14439    @Override
14440    public void setApplicationEnabledSetting(String appPackageName,
14441            int newState, int flags, int userId, String callingPackage) {
14442        if (!sUserManager.exists(userId)) return;
14443        if (callingPackage == null) {
14444            callingPackage = Integer.toString(Binder.getCallingUid());
14445        }
14446        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14447    }
14448
14449    @Override
14450    public void setComponentEnabledSetting(ComponentName componentName,
14451            int newState, int flags, int userId) {
14452        if (!sUserManager.exists(userId)) return;
14453        setEnabledSetting(componentName.getPackageName(),
14454                componentName.getClassName(), newState, flags, userId, null);
14455    }
14456
14457    private void setEnabledSetting(final String packageName, String className, int newState,
14458            final int flags, int userId, String callingPackage) {
14459        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14460              || newState == COMPONENT_ENABLED_STATE_ENABLED
14461              || newState == COMPONENT_ENABLED_STATE_DISABLED
14462              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14463              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14464            throw new IllegalArgumentException("Invalid new component state: "
14465                    + newState);
14466        }
14467        PackageSetting pkgSetting;
14468        final int uid = Binder.getCallingUid();
14469        final int permission = mContext.checkCallingOrSelfPermission(
14470                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14471        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14472        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14473        boolean sendNow = false;
14474        boolean isApp = (className == null);
14475        String componentName = isApp ? packageName : className;
14476        int packageUid = -1;
14477        ArrayList<String> components;
14478
14479        // writer
14480        synchronized (mPackages) {
14481            pkgSetting = mSettings.mPackages.get(packageName);
14482            if (pkgSetting == null) {
14483                if (className == null) {
14484                    throw new IllegalArgumentException(
14485                            "Unknown package: " + packageName);
14486                }
14487                throw new IllegalArgumentException(
14488                        "Unknown component: " + packageName
14489                        + "/" + className);
14490            }
14491            // Allow root and verify that userId is not being specified by a different user
14492            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14493                throw new SecurityException(
14494                        "Permission Denial: attempt to change component state from pid="
14495                        + Binder.getCallingPid()
14496                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14497            }
14498            if (className == null) {
14499                // We're dealing with an application/package level state change
14500                if (pkgSetting.getEnabled(userId) == newState) {
14501                    // Nothing to do
14502                    return;
14503                }
14504                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14505                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14506                    // Don't care about who enables an app.
14507                    callingPackage = null;
14508                }
14509                pkgSetting.setEnabled(newState, userId, callingPackage);
14510                // pkgSetting.pkg.mSetEnabled = newState;
14511            } else {
14512                // We're dealing with a component level state change
14513                // First, verify that this is a valid class name.
14514                PackageParser.Package pkg = pkgSetting.pkg;
14515                if (pkg == null || !pkg.hasComponentClassName(className)) {
14516                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14517                        throw new IllegalArgumentException("Component class " + className
14518                                + " does not exist in " + packageName);
14519                    } else {
14520                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14521                                + className + " does not exist in " + packageName);
14522                    }
14523                }
14524                switch (newState) {
14525                case COMPONENT_ENABLED_STATE_ENABLED:
14526                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14527                        return;
14528                    }
14529                    break;
14530                case COMPONENT_ENABLED_STATE_DISABLED:
14531                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14532                        return;
14533                    }
14534                    break;
14535                case COMPONENT_ENABLED_STATE_DEFAULT:
14536                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14537                        return;
14538                    }
14539                    break;
14540                default:
14541                    Slog.e(TAG, "Invalid new component state: " + newState);
14542                    return;
14543                }
14544            }
14545            scheduleWritePackageRestrictionsLocked(userId);
14546            components = mPendingBroadcasts.get(userId, packageName);
14547            final boolean newPackage = components == null;
14548            if (newPackage) {
14549                components = new ArrayList<String>();
14550            }
14551            if (!components.contains(componentName)) {
14552                components.add(componentName);
14553            }
14554            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14555                sendNow = true;
14556                // Purge entry from pending broadcast list if another one exists already
14557                // since we are sending one right away.
14558                mPendingBroadcasts.remove(userId, packageName);
14559            } else {
14560                if (newPackage) {
14561                    mPendingBroadcasts.put(userId, packageName, components);
14562                }
14563                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14564                    // Schedule a message
14565                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14566                }
14567            }
14568        }
14569
14570        long callingId = Binder.clearCallingIdentity();
14571        try {
14572            if (sendNow) {
14573                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14574                sendPackageChangedBroadcast(packageName,
14575                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14576            }
14577        } finally {
14578            Binder.restoreCallingIdentity(callingId);
14579        }
14580    }
14581
14582    private void sendPackageChangedBroadcast(String packageName,
14583            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14584        if (DEBUG_INSTALL)
14585            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14586                    + componentNames);
14587        Bundle extras = new Bundle(4);
14588        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14589        String nameList[] = new String[componentNames.size()];
14590        componentNames.toArray(nameList);
14591        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14592        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14593        extras.putInt(Intent.EXTRA_UID, packageUid);
14594        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14595                new int[] {UserHandle.getUserId(packageUid)});
14596    }
14597
14598    @Override
14599    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14600        if (!sUserManager.exists(userId)) return;
14601        final int uid = Binder.getCallingUid();
14602        final int permission = mContext.checkCallingOrSelfPermission(
14603                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14604        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14605        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14606        // writer
14607        synchronized (mPackages) {
14608            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14609                    allowedByPermission, uid, userId)) {
14610                scheduleWritePackageRestrictionsLocked(userId);
14611            }
14612        }
14613    }
14614
14615    @Override
14616    public String getInstallerPackageName(String packageName) {
14617        // reader
14618        synchronized (mPackages) {
14619            return mSettings.getInstallerPackageNameLPr(packageName);
14620        }
14621    }
14622
14623    @Override
14624    public int getApplicationEnabledSetting(String packageName, int userId) {
14625        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14626        int uid = Binder.getCallingUid();
14627        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14628        // reader
14629        synchronized (mPackages) {
14630            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14631        }
14632    }
14633
14634    @Override
14635    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14636        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14637        int uid = Binder.getCallingUid();
14638        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14639        // reader
14640        synchronized (mPackages) {
14641            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14642        }
14643    }
14644
14645    @Override
14646    public void enterSafeMode() {
14647        enforceSystemOrRoot("Only the system can request entering safe mode");
14648
14649        if (!mSystemReady) {
14650            mSafeMode = true;
14651        }
14652    }
14653
14654    @Override
14655    public void systemReady() {
14656        mSystemReady = true;
14657
14658        // Read the compatibilty setting when the system is ready.
14659        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14660                mContext.getContentResolver(),
14661                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14662        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14663        if (DEBUG_SETTINGS) {
14664            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14665        }
14666
14667        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14668
14669        synchronized (mPackages) {
14670            // Verify that all of the preferred activity components actually
14671            // exist.  It is possible for applications to be updated and at
14672            // that point remove a previously declared activity component that
14673            // had been set as a preferred activity.  We try to clean this up
14674            // the next time we encounter that preferred activity, but it is
14675            // possible for the user flow to never be able to return to that
14676            // situation so here we do a sanity check to make sure we haven't
14677            // left any junk around.
14678            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14679            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14680                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14681                removed.clear();
14682                for (PreferredActivity pa : pir.filterSet()) {
14683                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14684                        removed.add(pa);
14685                    }
14686                }
14687                if (removed.size() > 0) {
14688                    for (int r=0; r<removed.size(); r++) {
14689                        PreferredActivity pa = removed.get(r);
14690                        Slog.w(TAG, "Removing dangling preferred activity: "
14691                                + pa.mPref.mComponent);
14692                        pir.removeFilter(pa);
14693                    }
14694                    mSettings.writePackageRestrictionsLPr(
14695                            mSettings.mPreferredActivities.keyAt(i));
14696                }
14697            }
14698
14699            for (int userId : UserManagerService.getInstance().getUserIds()) {
14700                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14701                    grantPermissionsUserIds = ArrayUtils.appendInt(
14702                            grantPermissionsUserIds, userId);
14703                }
14704            }
14705        }
14706        sUserManager.systemReady();
14707
14708        // If we upgraded grant all default permissions before kicking off.
14709        for (int userId : grantPermissionsUserIds) {
14710            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14711        }
14712
14713        // Kick off any messages waiting for system ready
14714        if (mPostSystemReadyMessages != null) {
14715            for (Message msg : mPostSystemReadyMessages) {
14716                msg.sendToTarget();
14717            }
14718            mPostSystemReadyMessages = null;
14719        }
14720
14721        // Watch for external volumes that come and go over time
14722        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14723        storage.registerListener(mStorageListener);
14724
14725        mInstallerService.systemReady();
14726        mPackageDexOptimizer.systemReady();
14727
14728        MountServiceInternal mountServiceInternal = LocalServices.getService(
14729                MountServiceInternal.class);
14730        mountServiceInternal.addExternalStoragePolicy(
14731                new MountServiceInternal.ExternalStorageMountPolicy() {
14732            @Override
14733            public int getMountMode(int uid, String packageName) {
14734                if (Process.isIsolated(uid)) {
14735                    return Zygote.MOUNT_EXTERNAL_NONE;
14736                }
14737                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14738                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14739                }
14740                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14741                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14742                }
14743                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14744                    return Zygote.MOUNT_EXTERNAL_READ;
14745                }
14746                return Zygote.MOUNT_EXTERNAL_WRITE;
14747            }
14748
14749            @Override
14750            public boolean hasExternalStorage(int uid, String packageName) {
14751                return true;
14752            }
14753        });
14754    }
14755
14756    @Override
14757    public boolean isSafeMode() {
14758        return mSafeMode;
14759    }
14760
14761    @Override
14762    public boolean hasSystemUidErrors() {
14763        return mHasSystemUidErrors;
14764    }
14765
14766    static String arrayToString(int[] array) {
14767        StringBuffer buf = new StringBuffer(128);
14768        buf.append('[');
14769        if (array != null) {
14770            for (int i=0; i<array.length; i++) {
14771                if (i > 0) buf.append(", ");
14772                buf.append(array[i]);
14773            }
14774        }
14775        buf.append(']');
14776        return buf.toString();
14777    }
14778
14779    static class DumpState {
14780        public static final int DUMP_LIBS = 1 << 0;
14781        public static final int DUMP_FEATURES = 1 << 1;
14782        public static final int DUMP_RESOLVERS = 1 << 2;
14783        public static final int DUMP_PERMISSIONS = 1 << 3;
14784        public static final int DUMP_PACKAGES = 1 << 4;
14785        public static final int DUMP_SHARED_USERS = 1 << 5;
14786        public static final int DUMP_MESSAGES = 1 << 6;
14787        public static final int DUMP_PROVIDERS = 1 << 7;
14788        public static final int DUMP_VERIFIERS = 1 << 8;
14789        public static final int DUMP_PREFERRED = 1 << 9;
14790        public static final int DUMP_PREFERRED_XML = 1 << 10;
14791        public static final int DUMP_KEYSETS = 1 << 11;
14792        public static final int DUMP_VERSION = 1 << 12;
14793        public static final int DUMP_INSTALLS = 1 << 13;
14794        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14795        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14796
14797        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14798
14799        private int mTypes;
14800
14801        private int mOptions;
14802
14803        private boolean mTitlePrinted;
14804
14805        private SharedUserSetting mSharedUser;
14806
14807        public boolean isDumping(int type) {
14808            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
14809                return true;
14810            }
14811
14812            return (mTypes & type) != 0;
14813        }
14814
14815        public void setDump(int type) {
14816            mTypes |= type;
14817        }
14818
14819        public boolean isOptionEnabled(int option) {
14820            return (mOptions & option) != 0;
14821        }
14822
14823        public void setOptionEnabled(int option) {
14824            mOptions |= option;
14825        }
14826
14827        public boolean onTitlePrinted() {
14828            final boolean printed = mTitlePrinted;
14829            mTitlePrinted = true;
14830            return printed;
14831        }
14832
14833        public boolean getTitlePrinted() {
14834            return mTitlePrinted;
14835        }
14836
14837        public void setTitlePrinted(boolean enabled) {
14838            mTitlePrinted = enabled;
14839        }
14840
14841        public SharedUserSetting getSharedUser() {
14842            return mSharedUser;
14843        }
14844
14845        public void setSharedUser(SharedUserSetting user) {
14846            mSharedUser = user;
14847        }
14848    }
14849
14850    @Override
14851    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
14852        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
14853                != PackageManager.PERMISSION_GRANTED) {
14854            pw.println("Permission Denial: can't dump ActivityManager from from pid="
14855                    + Binder.getCallingPid()
14856                    + ", uid=" + Binder.getCallingUid()
14857                    + " without permission "
14858                    + android.Manifest.permission.DUMP);
14859            return;
14860        }
14861
14862        DumpState dumpState = new DumpState();
14863        boolean fullPreferred = false;
14864        boolean checkin = false;
14865
14866        String packageName = null;
14867        ArraySet<String> permissionNames = null;
14868
14869        int opti = 0;
14870        while (opti < args.length) {
14871            String opt = args[opti];
14872            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
14873                break;
14874            }
14875            opti++;
14876
14877            if ("-a".equals(opt)) {
14878                // Right now we only know how to print all.
14879            } else if ("-h".equals(opt)) {
14880                pw.println("Package manager dump options:");
14881                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
14882                pw.println("    --checkin: dump for a checkin");
14883                pw.println("    -f: print details of intent filters");
14884                pw.println("    -h: print this help");
14885                pw.println("  cmd may be one of:");
14886                pw.println("    l[ibraries]: list known shared libraries");
14887                pw.println("    f[ibraries]: list device features");
14888                pw.println("    k[eysets]: print known keysets");
14889                pw.println("    r[esolvers]: dump intent resolvers");
14890                pw.println("    perm[issions]: dump permissions");
14891                pw.println("    permission [name ...]: dump declaration and use of given permission");
14892                pw.println("    pref[erred]: print preferred package settings");
14893                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
14894                pw.println("    prov[iders]: dump content providers");
14895                pw.println("    p[ackages]: dump installed packages");
14896                pw.println("    s[hared-users]: dump shared user IDs");
14897                pw.println("    m[essages]: print collected runtime messages");
14898                pw.println("    v[erifiers]: print package verifier info");
14899                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
14900                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
14901                pw.println("    version: print database version info");
14902                pw.println("    write: write current settings now");
14903                pw.println("    installs: details about install sessions");
14904                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
14905                pw.println("    <package.name>: info about given package");
14906                return;
14907            } else if ("--checkin".equals(opt)) {
14908                checkin = true;
14909            } else if ("-f".equals(opt)) {
14910                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14911            } else {
14912                pw.println("Unknown argument: " + opt + "; use -h for help");
14913            }
14914        }
14915
14916        // Is the caller requesting to dump a particular piece of data?
14917        if (opti < args.length) {
14918            String cmd = args[opti];
14919            opti++;
14920            // Is this a package name?
14921            if ("android".equals(cmd) || cmd.contains(".")) {
14922                packageName = cmd;
14923                // When dumping a single package, we always dump all of its
14924                // filter information since the amount of data will be reasonable.
14925                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
14926            } else if ("check-permission".equals(cmd)) {
14927                if (opti >= args.length) {
14928                    pw.println("Error: check-permission missing permission argument");
14929                    return;
14930                }
14931                String perm = args[opti];
14932                opti++;
14933                if (opti >= args.length) {
14934                    pw.println("Error: check-permission missing package argument");
14935                    return;
14936                }
14937                String pkg = args[opti];
14938                opti++;
14939                int user = UserHandle.getUserId(Binder.getCallingUid());
14940                if (opti < args.length) {
14941                    try {
14942                        user = Integer.parseInt(args[opti]);
14943                    } catch (NumberFormatException e) {
14944                        pw.println("Error: check-permission user argument is not a number: "
14945                                + args[opti]);
14946                        return;
14947                    }
14948                }
14949                pw.println(checkPermission(perm, pkg, user));
14950                return;
14951            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
14952                dumpState.setDump(DumpState.DUMP_LIBS);
14953            } else if ("f".equals(cmd) || "features".equals(cmd)) {
14954                dumpState.setDump(DumpState.DUMP_FEATURES);
14955            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
14956                dumpState.setDump(DumpState.DUMP_RESOLVERS);
14957            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
14958                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
14959            } else if ("permission".equals(cmd)) {
14960                if (opti >= args.length) {
14961                    pw.println("Error: permission requires permission name");
14962                    return;
14963                }
14964                permissionNames = new ArraySet<>();
14965                while (opti < args.length) {
14966                    permissionNames.add(args[opti]);
14967                    opti++;
14968                }
14969                dumpState.setDump(DumpState.DUMP_PERMISSIONS
14970                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
14971            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
14972                dumpState.setDump(DumpState.DUMP_PREFERRED);
14973            } else if ("preferred-xml".equals(cmd)) {
14974                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
14975                if (opti < args.length && "--full".equals(args[opti])) {
14976                    fullPreferred = true;
14977                    opti++;
14978                }
14979            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
14980                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
14981            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
14982                dumpState.setDump(DumpState.DUMP_PACKAGES);
14983            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
14984                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
14985            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
14986                dumpState.setDump(DumpState.DUMP_PROVIDERS);
14987            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
14988                dumpState.setDump(DumpState.DUMP_MESSAGES);
14989            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
14990                dumpState.setDump(DumpState.DUMP_VERIFIERS);
14991            } else if ("i".equals(cmd) || "ifv".equals(cmd)
14992                    || "intent-filter-verifiers".equals(cmd)) {
14993                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
14994            } else if ("version".equals(cmd)) {
14995                dumpState.setDump(DumpState.DUMP_VERSION);
14996            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
14997                dumpState.setDump(DumpState.DUMP_KEYSETS);
14998            } else if ("installs".equals(cmd)) {
14999                dumpState.setDump(DumpState.DUMP_INSTALLS);
15000            } else if ("write".equals(cmd)) {
15001                synchronized (mPackages) {
15002                    mSettings.writeLPr();
15003                    pw.println("Settings written.");
15004                    return;
15005                }
15006            }
15007        }
15008
15009        if (checkin) {
15010            pw.println("vers,1");
15011        }
15012
15013        // reader
15014        synchronized (mPackages) {
15015            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15016                if (!checkin) {
15017                    if (dumpState.onTitlePrinted())
15018                        pw.println();
15019                    pw.println("Database versions:");
15020                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15021                }
15022            }
15023
15024            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15025                if (!checkin) {
15026                    if (dumpState.onTitlePrinted())
15027                        pw.println();
15028                    pw.println("Verifiers:");
15029                    pw.print("  Required: ");
15030                    pw.print(mRequiredVerifierPackage);
15031                    pw.print(" (uid=");
15032                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15033                    pw.println(")");
15034                } else if (mRequiredVerifierPackage != null) {
15035                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15036                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15037                }
15038            }
15039
15040            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15041                    packageName == null) {
15042                if (mIntentFilterVerifierComponent != null) {
15043                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15044                    if (!checkin) {
15045                        if (dumpState.onTitlePrinted())
15046                            pw.println();
15047                        pw.println("Intent Filter Verifier:");
15048                        pw.print("  Using: ");
15049                        pw.print(verifierPackageName);
15050                        pw.print(" (uid=");
15051                        pw.print(getPackageUid(verifierPackageName, 0));
15052                        pw.println(")");
15053                    } else if (verifierPackageName != null) {
15054                        pw.print("ifv,"); pw.print(verifierPackageName);
15055                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15056                    }
15057                } else {
15058                    pw.println();
15059                    pw.println("No Intent Filter Verifier available!");
15060                }
15061            }
15062
15063            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15064                boolean printedHeader = false;
15065                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15066                while (it.hasNext()) {
15067                    String name = it.next();
15068                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15069                    if (!checkin) {
15070                        if (!printedHeader) {
15071                            if (dumpState.onTitlePrinted())
15072                                pw.println();
15073                            pw.println("Libraries:");
15074                            printedHeader = true;
15075                        }
15076                        pw.print("  ");
15077                    } else {
15078                        pw.print("lib,");
15079                    }
15080                    pw.print(name);
15081                    if (!checkin) {
15082                        pw.print(" -> ");
15083                    }
15084                    if (ent.path != null) {
15085                        if (!checkin) {
15086                            pw.print("(jar) ");
15087                            pw.print(ent.path);
15088                        } else {
15089                            pw.print(",jar,");
15090                            pw.print(ent.path);
15091                        }
15092                    } else {
15093                        if (!checkin) {
15094                            pw.print("(apk) ");
15095                            pw.print(ent.apk);
15096                        } else {
15097                            pw.print(",apk,");
15098                            pw.print(ent.apk);
15099                        }
15100                    }
15101                    pw.println();
15102                }
15103            }
15104
15105            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15106                if (dumpState.onTitlePrinted())
15107                    pw.println();
15108                if (!checkin) {
15109                    pw.println("Features:");
15110                }
15111                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15112                while (it.hasNext()) {
15113                    String name = it.next();
15114                    if (!checkin) {
15115                        pw.print("  ");
15116                    } else {
15117                        pw.print("feat,");
15118                    }
15119                    pw.println(name);
15120                }
15121            }
15122
15123            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15124                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15125                        : "Activity Resolver Table:", "  ", packageName,
15126                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15127                    dumpState.setTitlePrinted(true);
15128                }
15129                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15130                        : "Receiver Resolver Table:", "  ", packageName,
15131                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15132                    dumpState.setTitlePrinted(true);
15133                }
15134                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15135                        : "Service Resolver Table:", "  ", packageName,
15136                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15137                    dumpState.setTitlePrinted(true);
15138                }
15139                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15140                        : "Provider Resolver Table:", "  ", packageName,
15141                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15142                    dumpState.setTitlePrinted(true);
15143                }
15144            }
15145
15146            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15147                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15148                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15149                    int user = mSettings.mPreferredActivities.keyAt(i);
15150                    if (pir.dump(pw,
15151                            dumpState.getTitlePrinted()
15152                                ? "\nPreferred Activities User " + user + ":"
15153                                : "Preferred Activities User " + user + ":", "  ",
15154                            packageName, true, false)) {
15155                        dumpState.setTitlePrinted(true);
15156                    }
15157                }
15158            }
15159
15160            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15161                pw.flush();
15162                FileOutputStream fout = new FileOutputStream(fd);
15163                BufferedOutputStream str = new BufferedOutputStream(fout);
15164                XmlSerializer serializer = new FastXmlSerializer();
15165                try {
15166                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15167                    serializer.startDocument(null, true);
15168                    serializer.setFeature(
15169                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15170                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15171                    serializer.endDocument();
15172                    serializer.flush();
15173                } catch (IllegalArgumentException e) {
15174                    pw.println("Failed writing: " + e);
15175                } catch (IllegalStateException e) {
15176                    pw.println("Failed writing: " + e);
15177                } catch (IOException e) {
15178                    pw.println("Failed writing: " + e);
15179                }
15180            }
15181
15182            if (!checkin
15183                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15184                    && packageName == null) {
15185                pw.println();
15186                int count = mSettings.mPackages.size();
15187                if (count == 0) {
15188                    pw.println("No applications!");
15189                    pw.println();
15190                } else {
15191                    final String prefix = "  ";
15192                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15193                    if (allPackageSettings.size() == 0) {
15194                        pw.println("No domain preferred apps!");
15195                        pw.println();
15196                    } else {
15197                        pw.println("App verification status:");
15198                        pw.println();
15199                        count = 0;
15200                        for (PackageSetting ps : allPackageSettings) {
15201                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15202                            if (ivi == null || ivi.getPackageName() == null) continue;
15203                            pw.println(prefix + "Package: " + ivi.getPackageName());
15204                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15205                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15206                            pw.println();
15207                            count++;
15208                        }
15209                        if (count == 0) {
15210                            pw.println(prefix + "No app verification established.");
15211                            pw.println();
15212                        }
15213                        for (int userId : sUserManager.getUserIds()) {
15214                            pw.println("App linkages for user " + userId + ":");
15215                            pw.println();
15216                            count = 0;
15217                            for (PackageSetting ps : allPackageSettings) {
15218                                final long status = ps.getDomainVerificationStatusForUser(userId);
15219                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15220                                    continue;
15221                                }
15222                                pw.println(prefix + "Package: " + ps.name);
15223                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15224                                String statusStr = IntentFilterVerificationInfo.
15225                                        getStatusStringFromValue(status);
15226                                pw.println(prefix + "Status:  " + statusStr);
15227                                pw.println();
15228                                count++;
15229                            }
15230                            if (count == 0) {
15231                                pw.println(prefix + "No configured app linkages.");
15232                                pw.println();
15233                            }
15234                        }
15235                    }
15236                }
15237            }
15238
15239            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15240                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15241                if (packageName == null && permissionNames == null) {
15242                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15243                        if (iperm == 0) {
15244                            if (dumpState.onTitlePrinted())
15245                                pw.println();
15246                            pw.println("AppOp Permissions:");
15247                        }
15248                        pw.print("  AppOp Permission ");
15249                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15250                        pw.println(":");
15251                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15252                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15253                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15254                        }
15255                    }
15256                }
15257            }
15258
15259            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15260                boolean printedSomething = false;
15261                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15262                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15263                        continue;
15264                    }
15265                    if (!printedSomething) {
15266                        if (dumpState.onTitlePrinted())
15267                            pw.println();
15268                        pw.println("Registered ContentProviders:");
15269                        printedSomething = true;
15270                    }
15271                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15272                    pw.print("    "); pw.println(p.toString());
15273                }
15274                printedSomething = false;
15275                for (Map.Entry<String, PackageParser.Provider> entry :
15276                        mProvidersByAuthority.entrySet()) {
15277                    PackageParser.Provider p = entry.getValue();
15278                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15279                        continue;
15280                    }
15281                    if (!printedSomething) {
15282                        if (dumpState.onTitlePrinted())
15283                            pw.println();
15284                        pw.println("ContentProvider Authorities:");
15285                        printedSomething = true;
15286                    }
15287                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15288                    pw.print("    "); pw.println(p.toString());
15289                    if (p.info != null && p.info.applicationInfo != null) {
15290                        final String appInfo = p.info.applicationInfo.toString();
15291                        pw.print("      applicationInfo="); pw.println(appInfo);
15292                    }
15293                }
15294            }
15295
15296            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15297                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15298            }
15299
15300            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15301                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15302            }
15303
15304            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15305                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15306            }
15307
15308            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15309                // XXX should handle packageName != null by dumping only install data that
15310                // the given package is involved with.
15311                if (dumpState.onTitlePrinted()) pw.println();
15312                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15313            }
15314
15315            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15316                if (dumpState.onTitlePrinted()) pw.println();
15317                mSettings.dumpReadMessagesLPr(pw, dumpState);
15318
15319                pw.println();
15320                pw.println("Package warning messages:");
15321                BufferedReader in = null;
15322                String line = null;
15323                try {
15324                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15325                    while ((line = in.readLine()) != null) {
15326                        if (line.contains("ignored: updated version")) continue;
15327                        pw.println(line);
15328                    }
15329                } catch (IOException ignored) {
15330                } finally {
15331                    IoUtils.closeQuietly(in);
15332                }
15333            }
15334
15335            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15336                BufferedReader in = null;
15337                String line = null;
15338                try {
15339                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15340                    while ((line = in.readLine()) != null) {
15341                        if (line.contains("ignored: updated version")) continue;
15342                        pw.print("msg,");
15343                        pw.println(line);
15344                    }
15345                } catch (IOException ignored) {
15346                } finally {
15347                    IoUtils.closeQuietly(in);
15348                }
15349            }
15350        }
15351    }
15352
15353    private String dumpDomainString(String packageName) {
15354        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15355        List<IntentFilter> filters = getAllIntentFilters(packageName);
15356
15357        ArraySet<String> result = new ArraySet<>();
15358        if (iviList.size() > 0) {
15359            for (IntentFilterVerificationInfo ivi : iviList) {
15360                for (String host : ivi.getDomains()) {
15361                    result.add(host);
15362                }
15363            }
15364        }
15365        if (filters != null && filters.size() > 0) {
15366            for (IntentFilter filter : filters) {
15367                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15368                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15369                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15370                    result.addAll(filter.getHostsList());
15371                }
15372            }
15373        }
15374
15375        StringBuilder sb = new StringBuilder(result.size() * 16);
15376        for (String domain : result) {
15377            if (sb.length() > 0) sb.append(" ");
15378            sb.append(domain);
15379        }
15380        return sb.toString();
15381    }
15382
15383    // ------- apps on sdcard specific code -------
15384    static final boolean DEBUG_SD_INSTALL = false;
15385
15386    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15387
15388    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15389
15390    private boolean mMediaMounted = false;
15391
15392    static String getEncryptKey() {
15393        try {
15394            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15395                    SD_ENCRYPTION_KEYSTORE_NAME);
15396            if (sdEncKey == null) {
15397                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15398                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15399                if (sdEncKey == null) {
15400                    Slog.e(TAG, "Failed to create encryption keys");
15401                    return null;
15402                }
15403            }
15404            return sdEncKey;
15405        } catch (NoSuchAlgorithmException nsae) {
15406            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15407            return null;
15408        } catch (IOException ioe) {
15409            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15410            return null;
15411        }
15412    }
15413
15414    /*
15415     * Update media status on PackageManager.
15416     */
15417    @Override
15418    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15419        int callingUid = Binder.getCallingUid();
15420        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15421            throw new SecurityException("Media status can only be updated by the system");
15422        }
15423        // reader; this apparently protects mMediaMounted, but should probably
15424        // be a different lock in that case.
15425        synchronized (mPackages) {
15426            Log.i(TAG, "Updating external media status from "
15427                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15428                    + (mediaStatus ? "mounted" : "unmounted"));
15429            if (DEBUG_SD_INSTALL)
15430                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15431                        + ", mMediaMounted=" + mMediaMounted);
15432            if (mediaStatus == mMediaMounted) {
15433                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15434                        : 0, -1);
15435                mHandler.sendMessage(msg);
15436                return;
15437            }
15438            mMediaMounted = mediaStatus;
15439        }
15440        // Queue up an async operation since the package installation may take a
15441        // little while.
15442        mHandler.post(new Runnable() {
15443            public void run() {
15444                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15445            }
15446        });
15447    }
15448
15449    /**
15450     * Called by MountService when the initial ASECs to scan are available.
15451     * Should block until all the ASEC containers are finished being scanned.
15452     */
15453    public void scanAvailableAsecs() {
15454        updateExternalMediaStatusInner(true, false, false);
15455        if (mShouldRestoreconData) {
15456            SELinuxMMAC.setRestoreconDone();
15457            mShouldRestoreconData = false;
15458        }
15459    }
15460
15461    /*
15462     * Collect information of applications on external media, map them against
15463     * existing containers and update information based on current mount status.
15464     * Please note that we always have to report status if reportStatus has been
15465     * set to true especially when unloading packages.
15466     */
15467    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15468            boolean externalStorage) {
15469        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15470        int[] uidArr = EmptyArray.INT;
15471
15472        final String[] list = PackageHelper.getSecureContainerList();
15473        if (ArrayUtils.isEmpty(list)) {
15474            Log.i(TAG, "No secure containers found");
15475        } else {
15476            // Process list of secure containers and categorize them
15477            // as active or stale based on their package internal state.
15478
15479            // reader
15480            synchronized (mPackages) {
15481                for (String cid : list) {
15482                    // Leave stages untouched for now; installer service owns them
15483                    if (PackageInstallerService.isStageName(cid)) continue;
15484
15485                    if (DEBUG_SD_INSTALL)
15486                        Log.i(TAG, "Processing container " + cid);
15487                    String pkgName = getAsecPackageName(cid);
15488                    if (pkgName == null) {
15489                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15490                        continue;
15491                    }
15492                    if (DEBUG_SD_INSTALL)
15493                        Log.i(TAG, "Looking for pkg : " + pkgName);
15494
15495                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15496                    if (ps == null) {
15497                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15498                        continue;
15499                    }
15500
15501                    /*
15502                     * Skip packages that are not external if we're unmounting
15503                     * external storage.
15504                     */
15505                    if (externalStorage && !isMounted && !isExternal(ps)) {
15506                        continue;
15507                    }
15508
15509                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15510                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15511                    // The package status is changed only if the code path
15512                    // matches between settings and the container id.
15513                    if (ps.codePathString != null
15514                            && ps.codePathString.startsWith(args.getCodePath())) {
15515                        if (DEBUG_SD_INSTALL) {
15516                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15517                                    + " at code path: " + ps.codePathString);
15518                        }
15519
15520                        // We do have a valid package installed on sdcard
15521                        processCids.put(args, ps.codePathString);
15522                        final int uid = ps.appId;
15523                        if (uid != -1) {
15524                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15525                        }
15526                    } else {
15527                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15528                                + ps.codePathString);
15529                    }
15530                }
15531            }
15532
15533            Arrays.sort(uidArr);
15534        }
15535
15536        // Process packages with valid entries.
15537        if (isMounted) {
15538            if (DEBUG_SD_INSTALL)
15539                Log.i(TAG, "Loading packages");
15540            loadMediaPackages(processCids, uidArr, externalStorage);
15541            startCleaningPackages();
15542            mInstallerService.onSecureContainersAvailable();
15543        } else {
15544            if (DEBUG_SD_INSTALL)
15545                Log.i(TAG, "Unloading packages");
15546            unloadMediaPackages(processCids, uidArr, reportStatus);
15547        }
15548    }
15549
15550    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15551            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15552        final int size = infos.size();
15553        final String[] packageNames = new String[size];
15554        final int[] packageUids = new int[size];
15555        for (int i = 0; i < size; i++) {
15556            final ApplicationInfo info = infos.get(i);
15557            packageNames[i] = info.packageName;
15558            packageUids[i] = info.uid;
15559        }
15560        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15561                finishedReceiver);
15562    }
15563
15564    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15565            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15566        sendResourcesChangedBroadcast(mediaStatus, replacing,
15567                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15568    }
15569
15570    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15571            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15572        int size = pkgList.length;
15573        if (size > 0) {
15574            // Send broadcasts here
15575            Bundle extras = new Bundle();
15576            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15577            if (uidArr != null) {
15578                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15579            }
15580            if (replacing) {
15581                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15582            }
15583            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15584                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15585            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15586        }
15587    }
15588
15589   /*
15590     * Look at potentially valid container ids from processCids If package
15591     * information doesn't match the one on record or package scanning fails,
15592     * the cid is added to list of removeCids. We currently don't delete stale
15593     * containers.
15594     */
15595    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
15596            boolean externalStorage) {
15597        ArrayList<String> pkgList = new ArrayList<String>();
15598        Set<AsecInstallArgs> keys = processCids.keySet();
15599
15600        for (AsecInstallArgs args : keys) {
15601            String codePath = processCids.get(args);
15602            if (DEBUG_SD_INSTALL)
15603                Log.i(TAG, "Loading container : " + args.cid);
15604            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15605            try {
15606                // Make sure there are no container errors first.
15607                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15608                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15609                            + " when installing from sdcard");
15610                    continue;
15611                }
15612                // Check code path here.
15613                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15614                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15615                            + " does not match one in settings " + codePath);
15616                    continue;
15617                }
15618                // Parse package
15619                int parseFlags = mDefParseFlags;
15620                if (args.isExternalAsec()) {
15621                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15622                }
15623                if (args.isFwdLocked()) {
15624                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15625                }
15626
15627                synchronized (mInstallLock) {
15628                    PackageParser.Package pkg = null;
15629                    try {
15630                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
15631                    } catch (PackageManagerException e) {
15632                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15633                    }
15634                    // Scan the package
15635                    if (pkg != null) {
15636                        /*
15637                         * TODO why is the lock being held? doPostInstall is
15638                         * called in other places without the lock. This needs
15639                         * to be straightened out.
15640                         */
15641                        // writer
15642                        synchronized (mPackages) {
15643                            retCode = PackageManager.INSTALL_SUCCEEDED;
15644                            pkgList.add(pkg.packageName);
15645                            // Post process args
15646                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15647                                    pkg.applicationInfo.uid);
15648                        }
15649                    } else {
15650                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15651                    }
15652                }
15653
15654            } finally {
15655                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15656                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15657                }
15658            }
15659        }
15660        // writer
15661        synchronized (mPackages) {
15662            // If the platform SDK has changed since the last time we booted,
15663            // we need to re-grant app permission to catch any new ones that
15664            // appear. This is really a hack, and means that apps can in some
15665            // cases get permissions that the user didn't initially explicitly
15666            // allow... it would be nice to have some better way to handle
15667            // this situation.
15668            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
15669                    : mSettings.getInternalVersion();
15670            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
15671                    : StorageManager.UUID_PRIVATE_INTERNAL;
15672
15673            int updateFlags = UPDATE_PERMISSIONS_ALL;
15674            if (ver.sdkVersion != mSdkVersion) {
15675                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15676                        + mSdkVersion + "; regranting permissions for external");
15677                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15678            }
15679            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
15680
15681            // Yay, everything is now upgraded
15682            ver.forceCurrent();
15683
15684            // can downgrade to reader
15685            // Persist settings
15686            mSettings.writeLPr();
15687        }
15688        // Send a broadcast to let everyone know we are done processing
15689        if (pkgList.size() > 0) {
15690            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15691        }
15692    }
15693
15694   /*
15695     * Utility method to unload a list of specified containers
15696     */
15697    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15698        // Just unmount all valid containers.
15699        for (AsecInstallArgs arg : cidArgs) {
15700            synchronized (mInstallLock) {
15701                arg.doPostDeleteLI(false);
15702           }
15703       }
15704   }
15705
15706    /*
15707     * Unload packages mounted on external media. This involves deleting package
15708     * data from internal structures, sending broadcasts about diabled packages,
15709     * gc'ing to free up references, unmounting all secure containers
15710     * corresponding to packages on external media, and posting a
15711     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15712     * that we always have to post this message if status has been requested no
15713     * matter what.
15714     */
15715    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15716            final boolean reportStatus) {
15717        if (DEBUG_SD_INSTALL)
15718            Log.i(TAG, "unloading media packages");
15719        ArrayList<String> pkgList = new ArrayList<String>();
15720        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15721        final Set<AsecInstallArgs> keys = processCids.keySet();
15722        for (AsecInstallArgs args : keys) {
15723            String pkgName = args.getPackageName();
15724            if (DEBUG_SD_INSTALL)
15725                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15726            // Delete package internally
15727            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15728            synchronized (mInstallLock) {
15729                boolean res = deletePackageLI(pkgName, null, false, null, null,
15730                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15731                if (res) {
15732                    pkgList.add(pkgName);
15733                } else {
15734                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15735                    failedList.add(args);
15736                }
15737            }
15738        }
15739
15740        // reader
15741        synchronized (mPackages) {
15742            // We didn't update the settings after removing each package;
15743            // write them now for all packages.
15744            mSettings.writeLPr();
15745        }
15746
15747        // We have to absolutely send UPDATED_MEDIA_STATUS only
15748        // after confirming that all the receivers processed the ordered
15749        // broadcast when packages get disabled, force a gc to clean things up.
15750        // and unload all the containers.
15751        if (pkgList.size() > 0) {
15752            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15753                    new IIntentReceiver.Stub() {
15754                public void performReceive(Intent intent, int resultCode, String data,
15755                        Bundle extras, boolean ordered, boolean sticky,
15756                        int sendingUser) throws RemoteException {
15757                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15758                            reportStatus ? 1 : 0, 1, keys);
15759                    mHandler.sendMessage(msg);
15760                }
15761            });
15762        } else {
15763            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15764                    keys);
15765            mHandler.sendMessage(msg);
15766        }
15767    }
15768
15769    private void loadPrivatePackages(final VolumeInfo vol) {
15770        mHandler.post(new Runnable() {
15771            @Override
15772            public void run() {
15773                loadPrivatePackagesInner(vol);
15774            }
15775        });
15776    }
15777
15778    private void loadPrivatePackagesInner(VolumeInfo vol) {
15779        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15780        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15781
15782        final VersionInfo ver;
15783        final List<PackageSetting> packages;
15784        synchronized (mPackages) {
15785            ver = mSettings.findOrCreateVersion(vol.fsUuid);
15786            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15787        }
15788
15789        for (PackageSetting ps : packages) {
15790            synchronized (mInstallLock) {
15791                final PackageParser.Package pkg;
15792                try {
15793                    pkg = scanPackageLI(ps.codePath, parseFlags, SCAN_INITIAL, 0L, null);
15794                    loaded.add(pkg.applicationInfo);
15795                } catch (PackageManagerException e) {
15796                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15797                }
15798
15799                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15800                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15801                }
15802            }
15803        }
15804
15805        synchronized (mPackages) {
15806            int updateFlags = UPDATE_PERMISSIONS_ALL;
15807            if (ver.sdkVersion != mSdkVersion) {
15808                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15809                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
15810                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15811            }
15812            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
15813
15814            // Yay, everything is now upgraded
15815            ver.forceCurrent();
15816
15817            mSettings.writeLPr();
15818        }
15819
15820        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
15821        sendResourcesChangedBroadcast(true, false, loaded, null);
15822    }
15823
15824    private void unloadPrivatePackages(final VolumeInfo vol) {
15825        mHandler.post(new Runnable() {
15826            @Override
15827            public void run() {
15828                unloadPrivatePackagesInner(vol);
15829            }
15830        });
15831    }
15832
15833    private void unloadPrivatePackagesInner(VolumeInfo vol) {
15834        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
15835        synchronized (mInstallLock) {
15836        synchronized (mPackages) {
15837            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15838            for (PackageSetting ps : packages) {
15839                if (ps.pkg == null) continue;
15840
15841                final ApplicationInfo info = ps.pkg.applicationInfo;
15842                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
15843                if (deletePackageLI(ps.name, null, false, null, null,
15844                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
15845                    unloaded.add(info);
15846                } else {
15847                    Slog.w(TAG, "Failed to unload " + ps.codePath);
15848                }
15849            }
15850
15851            mSettings.writeLPr();
15852        }
15853        }
15854
15855        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
15856        sendResourcesChangedBroadcast(false, false, unloaded, null);
15857    }
15858
15859    /**
15860     * Examine all users present on given mounted volume, and destroy data
15861     * belonging to users that are no longer valid, or whose user ID has been
15862     * recycled.
15863     */
15864    private void reconcileUsers(String volumeUuid) {
15865        final File[] files = FileUtils
15866                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
15867        for (File file : files) {
15868            if (!file.isDirectory()) continue;
15869
15870            final int userId;
15871            final UserInfo info;
15872            try {
15873                userId = Integer.parseInt(file.getName());
15874                info = sUserManager.getUserInfo(userId);
15875            } catch (NumberFormatException e) {
15876                Slog.w(TAG, "Invalid user directory " + file);
15877                continue;
15878            }
15879
15880            boolean destroyUser = false;
15881            if (info == null) {
15882                logCriticalInfo(Log.WARN, "Destroying user directory " + file
15883                        + " because no matching user was found");
15884                destroyUser = true;
15885            } else {
15886                try {
15887                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
15888                } catch (IOException e) {
15889                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
15890                            + " because we failed to enforce serial number: " + e);
15891                    destroyUser = true;
15892                }
15893            }
15894
15895            if (destroyUser) {
15896                synchronized (mInstallLock) {
15897                    mInstaller.removeUserDataDirs(volumeUuid, userId);
15898                }
15899            }
15900        }
15901
15902        final UserManager um = mContext.getSystemService(UserManager.class);
15903        for (UserInfo user : um.getUsers()) {
15904            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
15905            if (userDir.exists()) continue;
15906
15907            try {
15908                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
15909                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
15910            } catch (IOException e) {
15911                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
15912            }
15913        }
15914    }
15915
15916    /**
15917     * Examine all apps present on given mounted volume, and destroy apps that
15918     * aren't expected, either due to uninstallation or reinstallation on
15919     * another volume.
15920     */
15921    private void reconcileApps(String volumeUuid) {
15922        final File[] files = FileUtils
15923                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
15924        for (File file : files) {
15925            final boolean isPackage = (isApkFile(file) || file.isDirectory())
15926                    && !PackageInstallerService.isStageName(file.getName());
15927            if (!isPackage) {
15928                // Ignore entries which are not packages
15929                continue;
15930            }
15931
15932            boolean destroyApp = false;
15933            String packageName = null;
15934            try {
15935                final PackageLite pkg = PackageParser.parsePackageLite(file,
15936                        PackageParser.PARSE_MUST_BE_APK);
15937                packageName = pkg.packageName;
15938
15939                synchronized (mPackages) {
15940                    final PackageSetting ps = mSettings.mPackages.get(packageName);
15941                    if (ps == null) {
15942                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
15943                                + volumeUuid + " because we found no install record");
15944                        destroyApp = true;
15945                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
15946                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
15947                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
15948                        destroyApp = true;
15949                    }
15950                }
15951
15952            } catch (PackageParserException e) {
15953                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
15954                destroyApp = true;
15955            }
15956
15957            if (destroyApp) {
15958                synchronized (mInstallLock) {
15959                    if (packageName != null) {
15960                        removeDataDirsLI(volumeUuid, packageName);
15961                    }
15962                    if (file.isDirectory()) {
15963                        mInstaller.rmPackageDir(file.getAbsolutePath());
15964                    } else {
15965                        file.delete();
15966                    }
15967                }
15968            }
15969        }
15970    }
15971
15972    private void unfreezePackage(String packageName) {
15973        synchronized (mPackages) {
15974            final PackageSetting ps = mSettings.mPackages.get(packageName);
15975            if (ps != null) {
15976                ps.frozen = false;
15977            }
15978        }
15979    }
15980
15981    @Override
15982    public int movePackage(final String packageName, final String volumeUuid) {
15983        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
15984
15985        final int moveId = mNextMoveId.getAndIncrement();
15986        try {
15987            movePackageInternal(packageName, volumeUuid, moveId);
15988        } catch (PackageManagerException e) {
15989            Slog.w(TAG, "Failed to move " + packageName, e);
15990            mMoveCallbacks.notifyStatusChanged(moveId,
15991                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
15992        }
15993        return moveId;
15994    }
15995
15996    private void movePackageInternal(final String packageName, final String volumeUuid,
15997            final int moveId) throws PackageManagerException {
15998        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
15999        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16000        final PackageManager pm = mContext.getPackageManager();
16001
16002        final boolean currentAsec;
16003        final String currentVolumeUuid;
16004        final File codeFile;
16005        final String installerPackageName;
16006        final String packageAbiOverride;
16007        final int appId;
16008        final String seinfo;
16009        final String label;
16010
16011        // reader
16012        synchronized (mPackages) {
16013            final PackageParser.Package pkg = mPackages.get(packageName);
16014            final PackageSetting ps = mSettings.mPackages.get(packageName);
16015            if (pkg == null || ps == null) {
16016                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16017            }
16018
16019            if (pkg.applicationInfo.isSystemApp()) {
16020                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16021                        "Cannot move system application");
16022            }
16023
16024            if (pkg.applicationInfo.isExternalAsec()) {
16025                currentAsec = true;
16026                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16027            } else if (pkg.applicationInfo.isForwardLocked()) {
16028                currentAsec = true;
16029                currentVolumeUuid = "forward_locked";
16030            } else {
16031                currentAsec = false;
16032                currentVolumeUuid = ps.volumeUuid;
16033
16034                final File probe = new File(pkg.codePath);
16035                final File probeOat = new File(probe, "oat");
16036                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16037                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16038                            "Move only supported for modern cluster style installs");
16039                }
16040            }
16041
16042            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16043                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16044                        "Package already moved to " + volumeUuid);
16045            }
16046
16047            if (ps.frozen) {
16048                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16049                        "Failed to move already frozen package");
16050            }
16051            ps.frozen = true;
16052
16053            codeFile = new File(pkg.codePath);
16054            installerPackageName = ps.installerPackageName;
16055            packageAbiOverride = ps.cpuAbiOverrideString;
16056            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16057            seinfo = pkg.applicationInfo.seinfo;
16058            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16059        }
16060
16061        // Now that we're guarded by frozen state, kill app during move
16062        final long token = Binder.clearCallingIdentity();
16063        try {
16064            killApplication(packageName, appId, "move pkg");
16065        } finally {
16066            Binder.restoreCallingIdentity(token);
16067        }
16068
16069        final Bundle extras = new Bundle();
16070        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16071        extras.putString(Intent.EXTRA_TITLE, label);
16072        mMoveCallbacks.notifyCreated(moveId, extras);
16073
16074        int installFlags;
16075        final boolean moveCompleteApp;
16076        final File measurePath;
16077
16078        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16079            installFlags = INSTALL_INTERNAL;
16080            moveCompleteApp = !currentAsec;
16081            measurePath = Environment.getDataAppDirectory(volumeUuid);
16082        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16083            installFlags = INSTALL_EXTERNAL;
16084            moveCompleteApp = false;
16085            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16086        } else {
16087            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16088            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16089                    || !volume.isMountedWritable()) {
16090                unfreezePackage(packageName);
16091                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16092                        "Move location not mounted private volume");
16093            }
16094
16095            Preconditions.checkState(!currentAsec);
16096
16097            installFlags = INSTALL_INTERNAL;
16098            moveCompleteApp = true;
16099            measurePath = Environment.getDataAppDirectory(volumeUuid);
16100        }
16101
16102        final PackageStats stats = new PackageStats(null, -1);
16103        synchronized (mInstaller) {
16104            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16105                unfreezePackage(packageName);
16106                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16107                        "Failed to measure package size");
16108            }
16109        }
16110
16111        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16112                + stats.dataSize);
16113
16114        final long startFreeBytes = measurePath.getFreeSpace();
16115        final long sizeBytes;
16116        if (moveCompleteApp) {
16117            sizeBytes = stats.codeSize + stats.dataSize;
16118        } else {
16119            sizeBytes = stats.codeSize;
16120        }
16121
16122        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16123            unfreezePackage(packageName);
16124            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16125                    "Not enough free space to move");
16126        }
16127
16128        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16129
16130        final CountDownLatch installedLatch = new CountDownLatch(1);
16131        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16132            @Override
16133            public void onUserActionRequired(Intent intent) throws RemoteException {
16134                throw new IllegalStateException();
16135            }
16136
16137            @Override
16138            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16139                    Bundle extras) throws RemoteException {
16140                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16141                        + PackageManager.installStatusToString(returnCode, msg));
16142
16143                installedLatch.countDown();
16144
16145                // Regardless of success or failure of the move operation,
16146                // always unfreeze the package
16147                unfreezePackage(packageName);
16148
16149                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16150                switch (status) {
16151                    case PackageInstaller.STATUS_SUCCESS:
16152                        mMoveCallbacks.notifyStatusChanged(moveId,
16153                                PackageManager.MOVE_SUCCEEDED);
16154                        break;
16155                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16156                        mMoveCallbacks.notifyStatusChanged(moveId,
16157                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16158                        break;
16159                    default:
16160                        mMoveCallbacks.notifyStatusChanged(moveId,
16161                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16162                        break;
16163                }
16164            }
16165        };
16166
16167        final MoveInfo move;
16168        if (moveCompleteApp) {
16169            // Kick off a thread to report progress estimates
16170            new Thread() {
16171                @Override
16172                public void run() {
16173                    while (true) {
16174                        try {
16175                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16176                                break;
16177                            }
16178                        } catch (InterruptedException ignored) {
16179                        }
16180
16181                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16182                        final int progress = 10 + (int) MathUtils.constrain(
16183                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16184                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16185                    }
16186                }
16187            }.start();
16188
16189            final String dataAppName = codeFile.getName();
16190            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16191                    dataAppName, appId, seinfo);
16192        } else {
16193            move = null;
16194        }
16195
16196        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16197
16198        final Message msg = mHandler.obtainMessage(INIT_COPY);
16199        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16200        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
16201                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16202        mHandler.sendMessage(msg);
16203    }
16204
16205    @Override
16206    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16207        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16208
16209        final int realMoveId = mNextMoveId.getAndIncrement();
16210        final Bundle extras = new Bundle();
16211        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16212        mMoveCallbacks.notifyCreated(realMoveId, extras);
16213
16214        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16215            @Override
16216            public void onCreated(int moveId, Bundle extras) {
16217                // Ignored
16218            }
16219
16220            @Override
16221            public void onStatusChanged(int moveId, int status, long estMillis) {
16222                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16223            }
16224        };
16225
16226        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16227        storage.setPrimaryStorageUuid(volumeUuid, callback);
16228        return realMoveId;
16229    }
16230
16231    @Override
16232    public int getMoveStatus(int moveId) {
16233        mContext.enforceCallingOrSelfPermission(
16234                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16235        return mMoveCallbacks.mLastStatus.get(moveId);
16236    }
16237
16238    @Override
16239    public void registerMoveCallback(IPackageMoveObserver callback) {
16240        mContext.enforceCallingOrSelfPermission(
16241                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16242        mMoveCallbacks.register(callback);
16243    }
16244
16245    @Override
16246    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16247        mContext.enforceCallingOrSelfPermission(
16248                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16249        mMoveCallbacks.unregister(callback);
16250    }
16251
16252    @Override
16253    public boolean setInstallLocation(int loc) {
16254        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16255                null);
16256        if (getInstallLocation() == loc) {
16257            return true;
16258        }
16259        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16260                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16261            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16262                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16263            return true;
16264        }
16265        return false;
16266   }
16267
16268    @Override
16269    public int getInstallLocation() {
16270        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16271                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16272                PackageHelper.APP_INSTALL_AUTO);
16273    }
16274
16275    /** Called by UserManagerService */
16276    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16277        mDirtyUsers.remove(userHandle);
16278        mSettings.removeUserLPw(userHandle);
16279        mPendingBroadcasts.remove(userHandle);
16280        if (mInstaller != null) {
16281            // Technically, we shouldn't be doing this with the package lock
16282            // held.  However, this is very rare, and there is already so much
16283            // other disk I/O going on, that we'll let it slide for now.
16284            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16285            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16286                final String volumeUuid = vol.getFsUuid();
16287                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16288                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16289            }
16290        }
16291        mUserNeedsBadging.delete(userHandle);
16292        removeUnusedPackagesLILPw(userManager, userHandle);
16293    }
16294
16295    /**
16296     * We're removing userHandle and would like to remove any downloaded packages
16297     * that are no longer in use by any other user.
16298     * @param userHandle the user being removed
16299     */
16300    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16301        final boolean DEBUG_CLEAN_APKS = false;
16302        int [] users = userManager.getUserIdsLPr();
16303        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16304        while (psit.hasNext()) {
16305            PackageSetting ps = psit.next();
16306            if (ps.pkg == null) {
16307                continue;
16308            }
16309            final String packageName = ps.pkg.packageName;
16310            // Skip over if system app
16311            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16312                continue;
16313            }
16314            if (DEBUG_CLEAN_APKS) {
16315                Slog.i(TAG, "Checking package " + packageName);
16316            }
16317            boolean keep = false;
16318            for (int i = 0; i < users.length; i++) {
16319                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16320                    keep = true;
16321                    if (DEBUG_CLEAN_APKS) {
16322                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16323                                + users[i]);
16324                    }
16325                    break;
16326                }
16327            }
16328            if (!keep) {
16329                if (DEBUG_CLEAN_APKS) {
16330                    Slog.i(TAG, "  Removing package " + packageName);
16331                }
16332                mHandler.post(new Runnable() {
16333                    public void run() {
16334                        deletePackageX(packageName, userHandle, 0);
16335                    } //end run
16336                });
16337            }
16338        }
16339    }
16340
16341    /** Called by UserManagerService */
16342    void createNewUserLILPw(int userHandle) {
16343        if (mInstaller != null) {
16344            mInstaller.createUserConfig(userHandle);
16345            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16346            applyFactoryDefaultBrowserLPw(userHandle);
16347            primeDomainVerificationsLPw(userHandle);
16348        }
16349    }
16350
16351    void newUserCreated(final int userHandle) {
16352        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16353    }
16354
16355    @Override
16356    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16357        mContext.enforceCallingOrSelfPermission(
16358                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16359                "Only package verification agents can read the verifier device identity");
16360
16361        synchronized (mPackages) {
16362            return mSettings.getVerifierDeviceIdentityLPw();
16363        }
16364    }
16365
16366    @Override
16367    public void setPermissionEnforced(String permission, boolean enforced) {
16368        // TODO: Now that we no longer change GID for storage, this should to away.
16369        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16370                "setPermissionEnforced");
16371        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16372            synchronized (mPackages) {
16373                if (mSettings.mReadExternalStorageEnforced == null
16374                        || mSettings.mReadExternalStorageEnforced != enforced) {
16375                    mSettings.mReadExternalStorageEnforced = enforced;
16376                    mSettings.writeLPr();
16377                }
16378            }
16379            // kill any non-foreground processes so we restart them and
16380            // grant/revoke the GID.
16381            final IActivityManager am = ActivityManagerNative.getDefault();
16382            if (am != null) {
16383                final long token = Binder.clearCallingIdentity();
16384                try {
16385                    am.killProcessesBelowForeground("setPermissionEnforcement");
16386                } catch (RemoteException e) {
16387                } finally {
16388                    Binder.restoreCallingIdentity(token);
16389                }
16390            }
16391        } else {
16392            throw new IllegalArgumentException("No selective enforcement for " + permission);
16393        }
16394    }
16395
16396    @Override
16397    @Deprecated
16398    public boolean isPermissionEnforced(String permission) {
16399        return true;
16400    }
16401
16402    @Override
16403    public boolean isStorageLow() {
16404        final long token = Binder.clearCallingIdentity();
16405        try {
16406            final DeviceStorageMonitorInternal
16407                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16408            if (dsm != null) {
16409                return dsm.isMemoryLow();
16410            } else {
16411                return false;
16412            }
16413        } finally {
16414            Binder.restoreCallingIdentity(token);
16415        }
16416    }
16417
16418    @Override
16419    public IPackageInstaller getPackageInstaller() {
16420        return mInstallerService;
16421    }
16422
16423    private boolean userNeedsBadging(int userId) {
16424        int index = mUserNeedsBadging.indexOfKey(userId);
16425        if (index < 0) {
16426            final UserInfo userInfo;
16427            final long token = Binder.clearCallingIdentity();
16428            try {
16429                userInfo = sUserManager.getUserInfo(userId);
16430            } finally {
16431                Binder.restoreCallingIdentity(token);
16432            }
16433            final boolean b;
16434            if (userInfo != null && userInfo.isManagedProfile()) {
16435                b = true;
16436            } else {
16437                b = false;
16438            }
16439            mUserNeedsBadging.put(userId, b);
16440            return b;
16441        }
16442        return mUserNeedsBadging.valueAt(index);
16443    }
16444
16445    @Override
16446    public KeySet getKeySetByAlias(String packageName, String alias) {
16447        if (packageName == null || alias == null) {
16448            return null;
16449        }
16450        synchronized(mPackages) {
16451            final PackageParser.Package pkg = mPackages.get(packageName);
16452            if (pkg == null) {
16453                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16454                throw new IllegalArgumentException("Unknown package: " + packageName);
16455            }
16456            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16457            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16458        }
16459    }
16460
16461    @Override
16462    public KeySet getSigningKeySet(String packageName) {
16463        if (packageName == null) {
16464            return null;
16465        }
16466        synchronized(mPackages) {
16467            final PackageParser.Package pkg = mPackages.get(packageName);
16468            if (pkg == null) {
16469                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16470                throw new IllegalArgumentException("Unknown package: " + packageName);
16471            }
16472            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16473                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16474                throw new SecurityException("May not access signing KeySet of other apps.");
16475            }
16476            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16477            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16478        }
16479    }
16480
16481    @Override
16482    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16483        if (packageName == null || ks == null) {
16484            return false;
16485        }
16486        synchronized(mPackages) {
16487            final PackageParser.Package pkg = mPackages.get(packageName);
16488            if (pkg == null) {
16489                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16490                throw new IllegalArgumentException("Unknown package: " + packageName);
16491            }
16492            IBinder ksh = ks.getToken();
16493            if (ksh instanceof KeySetHandle) {
16494                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16495                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16496            }
16497            return false;
16498        }
16499    }
16500
16501    @Override
16502    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16503        if (packageName == null || ks == null) {
16504            return false;
16505        }
16506        synchronized(mPackages) {
16507            final PackageParser.Package pkg = mPackages.get(packageName);
16508            if (pkg == null) {
16509                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16510                throw new IllegalArgumentException("Unknown package: " + packageName);
16511            }
16512            IBinder ksh = ks.getToken();
16513            if (ksh instanceof KeySetHandle) {
16514                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16515                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16516            }
16517            return false;
16518        }
16519    }
16520
16521    public void getUsageStatsIfNoPackageUsageInfo() {
16522        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16523            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16524            if (usm == null) {
16525                throw new IllegalStateException("UsageStatsManager must be initialized");
16526            }
16527            long now = System.currentTimeMillis();
16528            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16529            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16530                String packageName = entry.getKey();
16531                PackageParser.Package pkg = mPackages.get(packageName);
16532                if (pkg == null) {
16533                    continue;
16534                }
16535                UsageStats usage = entry.getValue();
16536                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16537                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16538            }
16539        }
16540    }
16541
16542    /**
16543     * Check and throw if the given before/after packages would be considered a
16544     * downgrade.
16545     */
16546    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16547            throws PackageManagerException {
16548        if (after.versionCode < before.mVersionCode) {
16549            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16550                    "Update version code " + after.versionCode + " is older than current "
16551                    + before.mVersionCode);
16552        } else if (after.versionCode == before.mVersionCode) {
16553            if (after.baseRevisionCode < before.baseRevisionCode) {
16554                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16555                        "Update base revision code " + after.baseRevisionCode
16556                        + " is older than current " + before.baseRevisionCode);
16557            }
16558
16559            if (!ArrayUtils.isEmpty(after.splitNames)) {
16560                for (int i = 0; i < after.splitNames.length; i++) {
16561                    final String splitName = after.splitNames[i];
16562                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16563                    if (j != -1) {
16564                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16565                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16566                                    "Update split " + splitName + " revision code "
16567                                    + after.splitRevisionCodes[i] + " is older than current "
16568                                    + before.splitRevisionCodes[j]);
16569                        }
16570                    }
16571                }
16572            }
16573        }
16574    }
16575
16576    private static class MoveCallbacks extends Handler {
16577        private static final int MSG_CREATED = 1;
16578        private static final int MSG_STATUS_CHANGED = 2;
16579
16580        private final RemoteCallbackList<IPackageMoveObserver>
16581                mCallbacks = new RemoteCallbackList<>();
16582
16583        private final SparseIntArray mLastStatus = new SparseIntArray();
16584
16585        public MoveCallbacks(Looper looper) {
16586            super(looper);
16587        }
16588
16589        public void register(IPackageMoveObserver callback) {
16590            mCallbacks.register(callback);
16591        }
16592
16593        public void unregister(IPackageMoveObserver callback) {
16594            mCallbacks.unregister(callback);
16595        }
16596
16597        @Override
16598        public void handleMessage(Message msg) {
16599            final SomeArgs args = (SomeArgs) msg.obj;
16600            final int n = mCallbacks.beginBroadcast();
16601            for (int i = 0; i < n; i++) {
16602                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16603                try {
16604                    invokeCallback(callback, msg.what, args);
16605                } catch (RemoteException ignored) {
16606                }
16607            }
16608            mCallbacks.finishBroadcast();
16609            args.recycle();
16610        }
16611
16612        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16613                throws RemoteException {
16614            switch (what) {
16615                case MSG_CREATED: {
16616                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16617                    break;
16618                }
16619                case MSG_STATUS_CHANGED: {
16620                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16621                    break;
16622                }
16623            }
16624        }
16625
16626        private void notifyCreated(int moveId, Bundle extras) {
16627            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16628
16629            final SomeArgs args = SomeArgs.obtain();
16630            args.argi1 = moveId;
16631            args.arg2 = extras;
16632            obtainMessage(MSG_CREATED, args).sendToTarget();
16633        }
16634
16635        private void notifyStatusChanged(int moveId, int status) {
16636            notifyStatusChanged(moveId, status, -1);
16637        }
16638
16639        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16640            Slog.v(TAG, "Move " + moveId + " status " + status);
16641
16642            final SomeArgs args = SomeArgs.obtain();
16643            args.argi1 = moveId;
16644            args.argi2 = status;
16645            args.arg3 = estMillis;
16646            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16647
16648            synchronized (mLastStatus) {
16649                mLastStatus.put(moveId, status);
16650            }
16651        }
16652    }
16653
16654    private final class OnPermissionChangeListeners extends Handler {
16655        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16656
16657        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16658                new RemoteCallbackList<>();
16659
16660        public OnPermissionChangeListeners(Looper looper) {
16661            super(looper);
16662        }
16663
16664        @Override
16665        public void handleMessage(Message msg) {
16666            switch (msg.what) {
16667                case MSG_ON_PERMISSIONS_CHANGED: {
16668                    final int uid = msg.arg1;
16669                    handleOnPermissionsChanged(uid);
16670                } break;
16671            }
16672        }
16673
16674        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16675            mPermissionListeners.register(listener);
16676
16677        }
16678
16679        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16680            mPermissionListeners.unregister(listener);
16681        }
16682
16683        public void onPermissionsChanged(int uid) {
16684            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16685                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16686            }
16687        }
16688
16689        private void handleOnPermissionsChanged(int uid) {
16690            final int count = mPermissionListeners.beginBroadcast();
16691            try {
16692                for (int i = 0; i < count; i++) {
16693                    IOnPermissionsChangeListener callback = mPermissionListeners
16694                            .getBroadcastItem(i);
16695                    try {
16696                        callback.onPermissionsChanged(uid);
16697                    } catch (RemoteException e) {
16698                        Log.e(TAG, "Permission listener is dead", e);
16699                    }
16700                }
16701            } finally {
16702                mPermissionListeners.finishBroadcast();
16703            }
16704        }
16705    }
16706
16707    private class PackageManagerInternalImpl extends PackageManagerInternal {
16708        @Override
16709        public void setLocationPackagesProvider(PackagesProvider provider) {
16710            synchronized (mPackages) {
16711                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16712            }
16713        }
16714
16715        @Override
16716        public void setImePackagesProvider(PackagesProvider provider) {
16717            synchronized (mPackages) {
16718                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16719            }
16720        }
16721
16722        @Override
16723        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16724            synchronized (mPackages) {
16725                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16726            }
16727        }
16728
16729        @Override
16730        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16731            synchronized (mPackages) {
16732                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16733            }
16734        }
16735
16736        @Override
16737        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16738            synchronized (mPackages) {
16739                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16740            }
16741        }
16742
16743        @Override
16744        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16745            synchronized (mPackages) {
16746                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16747            }
16748        }
16749
16750        @Override
16751        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16752            synchronized (mPackages) {
16753                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16754            }
16755        }
16756
16757        @Override
16758        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16759            synchronized (mPackages) {
16760                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16761                        packageName, userId);
16762            }
16763        }
16764
16765        @Override
16766        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16767            synchronized (mPackages) {
16768                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16769                        packageName, userId);
16770            }
16771        }
16772        @Override
16773        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16774            synchronized (mPackages) {
16775                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16776                        packageName, userId);
16777            }
16778        }
16779    }
16780
16781    @Override
16782    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16783        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16784        synchronized (mPackages) {
16785            final long identity = Binder.clearCallingIdentity();
16786            try {
16787                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16788                        packageNames, userId);
16789            } finally {
16790                Binder.restoreCallingIdentity(identity);
16791            }
16792        }
16793    }
16794
16795    private static void enforceSystemOrPhoneCaller(String tag) {
16796        int callingUid = Binder.getCallingUid();
16797        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16798            throw new SecurityException(
16799                    "Cannot call " + tag + " from UID " + callingUid);
16800        }
16801    }
16802}
16803