PackageManagerService.java revision 008672f62d15bac2b26502f20688da92d5ad3292
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.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
71import static android.system.OsConstants.O_CREAT;
72import static android.system.OsConstants.O_RDWR;
73import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
74import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
75import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
76import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
77import static com.android.internal.util.ArrayUtils.appendInt;
78import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
79import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
80import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
81import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
82import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
83import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
84import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
85import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
86import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
87
88import android.Manifest;
89import android.app.ActivityManager;
90import android.app.ActivityManagerNative;
91import android.app.AppGlobals;
92import android.app.IActivityManager;
93import android.app.admin.IDevicePolicyManager;
94import android.app.backup.IBackupManager;
95import android.app.usage.UsageStats;
96import android.app.usage.UsageStatsManager;
97import android.content.BroadcastReceiver;
98import android.content.ComponentName;
99import android.content.Context;
100import android.content.IIntentReceiver;
101import android.content.Intent;
102import android.content.IntentFilter;
103import android.content.IntentSender;
104import android.content.IntentSender.SendIntentException;
105import android.content.ServiceConnection;
106import android.content.pm.ActivityInfo;
107import android.content.pm.ApplicationInfo;
108import android.content.pm.FeatureInfo;
109import android.content.pm.IOnPermissionsChangeListener;
110import android.content.pm.IPackageDataObserver;
111import android.content.pm.IPackageDeleteObserver;
112import android.content.pm.IPackageDeleteObserver2;
113import android.content.pm.IPackageInstallObserver2;
114import android.content.pm.IPackageInstaller;
115import android.content.pm.IPackageManager;
116import android.content.pm.IPackageMoveObserver;
117import android.content.pm.IPackageStatsObserver;
118import android.content.pm.InstrumentationInfo;
119import android.content.pm.IntentFilterVerificationInfo;
120import android.content.pm.KeySet;
121import android.content.pm.ManifestDigest;
122import android.content.pm.PackageCleanItem;
123import android.content.pm.PackageInfo;
124import android.content.pm.PackageInfoLite;
125import android.content.pm.PackageInstaller;
126import android.content.pm.PackageManager;
127import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
128import android.content.pm.PackageManagerInternal;
129import android.content.pm.PackageParser;
130import android.content.pm.PackageParser.ActivityIntentInfo;
131import android.content.pm.PackageParser.PackageLite;
132import android.content.pm.PackageParser.PackageParserException;
133import android.content.pm.PackageStats;
134import android.content.pm.PackageUserState;
135import android.content.pm.ParceledListSlice;
136import android.content.pm.PermissionGroupInfo;
137import android.content.pm.PermissionInfo;
138import android.content.pm.ProviderInfo;
139import android.content.pm.ResolveInfo;
140import android.content.pm.ServiceInfo;
141import android.content.pm.Signature;
142import android.content.pm.UserInfo;
143import android.content.pm.VerificationParams;
144import android.content.pm.VerifierDeviceIdentity;
145import android.content.pm.VerifierInfo;
146import android.content.res.Resources;
147import android.hardware.display.DisplayManager;
148import android.net.Uri;
149import android.os.Debug;
150import android.os.Binder;
151import android.os.Build;
152import android.os.Bundle;
153import android.os.Environment;
154import android.os.Environment.UserEnvironment;
155import android.os.FileUtils;
156import android.os.Handler;
157import android.os.IBinder;
158import android.os.Looper;
159import android.os.Message;
160import android.os.Parcel;
161import android.os.ParcelFileDescriptor;
162import android.os.Process;
163import android.os.RemoteCallbackList;
164import android.os.RemoteException;
165import android.os.SELinux;
166import android.os.ServiceManager;
167import android.os.SystemClock;
168import android.os.SystemProperties;
169import android.os.Trace;
170import android.os.UserHandle;
171import android.os.UserManager;
172import android.os.storage.IMountService;
173import android.os.storage.MountServiceInternal;
174import android.os.storage.StorageEventListener;
175import android.os.storage.StorageManager;
176import android.os.storage.VolumeInfo;
177import android.os.storage.VolumeRecord;
178import android.security.KeyStore;
179import android.security.SystemKeyStore;
180import android.system.ErrnoException;
181import android.system.Os;
182import android.system.StructStat;
183import android.text.TextUtils;
184import android.text.format.DateUtils;
185import android.util.ArrayMap;
186import android.util.ArraySet;
187import android.util.AtomicFile;
188import android.util.DisplayMetrics;
189import android.util.EventLog;
190import android.util.ExceptionUtils;
191import android.util.Log;
192import android.util.LogPrinter;
193import android.util.MathUtils;
194import android.util.PrintStreamPrinter;
195import android.util.Slog;
196import android.util.SparseArray;
197import android.util.SparseBooleanArray;
198import android.util.SparseIntArray;
199import android.util.Xml;
200import android.view.Display;
201
202import dalvik.system.DexFile;
203import dalvik.system.VMRuntime;
204
205import libcore.io.IoUtils;
206import libcore.util.EmptyArray;
207
208import com.android.internal.R;
209import com.android.internal.annotations.GuardedBy;
210import com.android.internal.app.IMediaContainerService;
211import com.android.internal.app.ResolverActivity;
212import com.android.internal.content.NativeLibraryHelper;
213import com.android.internal.content.PackageHelper;
214import com.android.internal.os.IParcelFileDescriptorFactory;
215import com.android.internal.os.SomeArgs;
216import com.android.internal.os.Zygote;
217import com.android.internal.util.ArrayUtils;
218import com.android.internal.util.FastPrintWriter;
219import com.android.internal.util.FastXmlSerializer;
220import com.android.internal.util.IndentingPrintWriter;
221import com.android.internal.util.Preconditions;
222import com.android.server.EventLogTags;
223import com.android.server.FgThread;
224import com.android.server.IntentResolver;
225import com.android.server.LocalServices;
226import com.android.server.ServiceThread;
227import com.android.server.SystemConfig;
228import com.android.server.Watchdog;
229import com.android.server.pm.PermissionsState.PermissionState;
230import com.android.server.pm.Settings.DatabaseVersion;
231import com.android.server.pm.Settings.VersionInfo;
232import com.android.server.storage.DeviceStorageMonitorInternal;
233
234import org.xmlpull.v1.XmlPullParser;
235import org.xmlpull.v1.XmlPullParserException;
236import org.xmlpull.v1.XmlSerializer;
237
238import java.io.BufferedInputStream;
239import java.io.BufferedOutputStream;
240import java.io.BufferedReader;
241import java.io.ByteArrayInputStream;
242import java.io.ByteArrayOutputStream;
243import java.io.File;
244import java.io.FileDescriptor;
245import java.io.FileNotFoundException;
246import java.io.FileOutputStream;
247import java.io.FileReader;
248import java.io.FilenameFilter;
249import java.io.IOException;
250import java.io.InputStream;
251import java.io.PrintWriter;
252import java.nio.charset.StandardCharsets;
253import java.security.NoSuchAlgorithmException;
254import java.security.PublicKey;
255import java.security.cert.CertificateEncodingException;
256import java.security.cert.CertificateException;
257import java.text.SimpleDateFormat;
258import java.util.ArrayList;
259import java.util.Arrays;
260import java.util.Collection;
261import java.util.Collections;
262import java.util.Comparator;
263import java.util.Date;
264import java.util.Iterator;
265import java.util.List;
266import java.util.Map;
267import java.util.Objects;
268import java.util.Set;
269import java.util.concurrent.CountDownLatch;
270import java.util.concurrent.TimeUnit;
271import java.util.concurrent.atomic.AtomicBoolean;
272import java.util.concurrent.atomic.AtomicInteger;
273import java.util.concurrent.atomic.AtomicLong;
274
275/**
276 * Keep track of all those .apks everywhere.
277 *
278 * This is very central to the platform's security; please run the unit
279 * tests whenever making modifications here:
280 *
281runtest -c android.content.pm.PackageManagerTests frameworks-core
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.SYSTEM)) {
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                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1151                                System.identityHashCode(mHandler));
1152                        // If this is the only one pending we might
1153                        // have to bind to the service again.
1154                        if (!connectToService()) {
1155                            Slog.e(TAG, "Failed to bind to media container service");
1156                            params.serviceError();
1157                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1158                                    System.identityHashCode(mHandler));
1159                            if (params.traceMethod != null) {
1160                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1161                                        params.traceCookie);
1162                            }
1163                            return;
1164                        } else {
1165                            // Once we bind to the service, the first
1166                            // pending request will be processed.
1167                            mPendingInstalls.add(idx, params);
1168                        }
1169                    } else {
1170                        mPendingInstalls.add(idx, params);
1171                        // Already bound to the service. Just make
1172                        // sure we trigger off processing the first request.
1173                        if (idx == 0) {
1174                            mHandler.sendEmptyMessage(MCS_BOUND);
1175                        }
1176                    }
1177                    break;
1178                }
1179                case MCS_BOUND: {
1180                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1181                    if (msg.obj != null) {
1182                        mContainerService = (IMediaContainerService) msg.obj;
1183                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1184                                System.identityHashCode(mHandler));
1185                    }
1186                    if (mContainerService == null) {
1187                        if (!mBound) {
1188                            // Something seriously wrong since we are not bound and we are not
1189                            // waiting for connection. Bail out.
1190                            Slog.e(TAG, "Cannot bind to media container service");
1191                            for (HandlerParams params : mPendingInstalls) {
1192                                // Indicate service bind error
1193                                params.serviceError();
1194                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1195                                        System.identityHashCode(params));
1196                                if (params.traceMethod != null) {
1197                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1198                                            params.traceMethod, params.traceCookie);
1199                                }
1200                                return;
1201                            }
1202                            mPendingInstalls.clear();
1203                        } else {
1204                            Slog.w(TAG, "Waiting to connect to media container service");
1205                        }
1206                    } else if (mPendingInstalls.size() > 0) {
1207                        HandlerParams params = mPendingInstalls.get(0);
1208                        if (params != null) {
1209                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1210                                    System.identityHashCode(params));
1211                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1212                            if (params.startCopy()) {
1213                                // We are done...  look for more work or to
1214                                // go idle.
1215                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1216                                        "Checking for more work or unbind...");
1217                                // Delete pending install
1218                                if (mPendingInstalls.size() > 0) {
1219                                    mPendingInstalls.remove(0);
1220                                }
1221                                if (mPendingInstalls.size() == 0) {
1222                                    if (mBound) {
1223                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1224                                                "Posting delayed MCS_UNBIND");
1225                                        removeMessages(MCS_UNBIND);
1226                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1227                                        // Unbind after a little delay, to avoid
1228                                        // continual thrashing.
1229                                        sendMessageDelayed(ubmsg, 10000);
1230                                    }
1231                                } else {
1232                                    // There are more pending requests in queue.
1233                                    // Just post MCS_BOUND message to trigger processing
1234                                    // of next pending install.
1235                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1236                                            "Posting MCS_BOUND for next work");
1237                                    mHandler.sendEmptyMessage(MCS_BOUND);
1238                                }
1239                            }
1240                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1241                        }
1242                    } else {
1243                        // Should never happen ideally.
1244                        Slog.w(TAG, "Empty queue");
1245                    }
1246                    break;
1247                }
1248                case MCS_RECONNECT: {
1249                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1250                    if (mPendingInstalls.size() > 0) {
1251                        if (mBound) {
1252                            disconnectService();
1253                        }
1254                        if (!connectToService()) {
1255                            Slog.e(TAG, "Failed to bind to media container service");
1256                            for (HandlerParams params : mPendingInstalls) {
1257                                // Indicate service bind error
1258                                params.serviceError();
1259                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1260                                        System.identityHashCode(params));
1261                            }
1262                            mPendingInstalls.clear();
1263                        }
1264                    }
1265                    break;
1266                }
1267                case MCS_UNBIND: {
1268                    // If there is no actual work left, then time to unbind.
1269                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1270
1271                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1272                        if (mBound) {
1273                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1274
1275                            disconnectService();
1276                        }
1277                    } else if (mPendingInstalls.size() > 0) {
1278                        // There are more pending requests in queue.
1279                        // Just post MCS_BOUND message to trigger processing
1280                        // of next pending install.
1281                        mHandler.sendEmptyMessage(MCS_BOUND);
1282                    }
1283
1284                    break;
1285                }
1286                case MCS_GIVE_UP: {
1287                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1288                    HandlerParams params = mPendingInstalls.remove(0);
1289                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1290                            System.identityHashCode(params));
1291                    break;
1292                }
1293                case SEND_PENDING_BROADCAST: {
1294                    String packages[];
1295                    ArrayList<String> components[];
1296                    int size = 0;
1297                    int uids[];
1298                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1299                    synchronized (mPackages) {
1300                        if (mPendingBroadcasts == null) {
1301                            return;
1302                        }
1303                        size = mPendingBroadcasts.size();
1304                        if (size <= 0) {
1305                            // Nothing to be done. Just return
1306                            return;
1307                        }
1308                        packages = new String[size];
1309                        components = new ArrayList[size];
1310                        uids = new int[size];
1311                        int i = 0;  // filling out the above arrays
1312
1313                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1314                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1315                            Iterator<Map.Entry<String, ArrayList<String>>> it
1316                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1317                                            .entrySet().iterator();
1318                            while (it.hasNext() && i < size) {
1319                                Map.Entry<String, ArrayList<String>> ent = it.next();
1320                                packages[i] = ent.getKey();
1321                                components[i] = ent.getValue();
1322                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1323                                uids[i] = (ps != null)
1324                                        ? UserHandle.getUid(packageUserId, ps.appId)
1325                                        : -1;
1326                                i++;
1327                            }
1328                        }
1329                        size = i;
1330                        mPendingBroadcasts.clear();
1331                    }
1332                    // Send broadcasts
1333                    for (int i = 0; i < size; i++) {
1334                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1335                    }
1336                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1337                    break;
1338                }
1339                case START_CLEANING_PACKAGE: {
1340                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1341                    final String packageName = (String)msg.obj;
1342                    final int userId = msg.arg1;
1343                    final boolean andCode = msg.arg2 != 0;
1344                    synchronized (mPackages) {
1345                        if (userId == UserHandle.USER_ALL) {
1346                            int[] users = sUserManager.getUserIds();
1347                            for (int user : users) {
1348                                mSettings.addPackageToCleanLPw(
1349                                        new PackageCleanItem(user, packageName, andCode));
1350                            }
1351                        } else {
1352                            mSettings.addPackageToCleanLPw(
1353                                    new PackageCleanItem(userId, packageName, andCode));
1354                        }
1355                    }
1356                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1357                    startCleaningPackages();
1358                } break;
1359                case POST_INSTALL: {
1360                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1361                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1362                    mRunningInstalls.delete(msg.arg1);
1363                    boolean deleteOld = false;
1364
1365                    if (data != null) {
1366                        InstallArgs args = data.args;
1367                        PackageInstalledInfo res = data.res;
1368
1369                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1370                            final String packageName = res.pkg.applicationInfo.packageName;
1371                            res.removedInfo.sendBroadcast(false, true, false);
1372                            Bundle extras = new Bundle(1);
1373                            extras.putInt(Intent.EXTRA_UID, res.uid);
1374
1375                            // Now that we successfully installed the package, grant runtime
1376                            // permissions if requested before broadcasting the install.
1377                            if ((args.installFlags
1378                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1379                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1380                                        args.installGrantPermissions);
1381                            }
1382
1383                            // Determine the set of users who are adding this
1384                            // package for the first time vs. those who are seeing
1385                            // an update.
1386                            int[] firstUsers;
1387                            int[] updateUsers = new int[0];
1388                            if (res.origUsers == null || res.origUsers.length == 0) {
1389                                firstUsers = res.newUsers;
1390                            } else {
1391                                firstUsers = new int[0];
1392                                for (int i=0; i<res.newUsers.length; i++) {
1393                                    int user = res.newUsers[i];
1394                                    boolean isNew = true;
1395                                    for (int j=0; j<res.origUsers.length; j++) {
1396                                        if (res.origUsers[j] == user) {
1397                                            isNew = false;
1398                                            break;
1399                                        }
1400                                    }
1401                                    if (isNew) {
1402                                        int[] newFirst = new int[firstUsers.length+1];
1403                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1404                                                firstUsers.length);
1405                                        newFirst[firstUsers.length] = user;
1406                                        firstUsers = newFirst;
1407                                    } else {
1408                                        int[] newUpdate = new int[updateUsers.length+1];
1409                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1410                                                updateUsers.length);
1411                                        newUpdate[updateUsers.length] = user;
1412                                        updateUsers = newUpdate;
1413                                    }
1414                                }
1415                            }
1416                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1417                                    packageName, extras, null, null, firstUsers);
1418                            final boolean update = res.removedInfo.removedPackage != null;
1419                            if (update) {
1420                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1421                            }
1422                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1423                                    packageName, extras, null, null, updateUsers);
1424                            if (update) {
1425                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1426                                        packageName, extras, null, null, updateUsers);
1427                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1428                                        null, null, packageName, null, updateUsers);
1429
1430                                // treat asec-hosted packages like removable media on upgrade
1431                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1432                                    if (DEBUG_INSTALL) {
1433                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1434                                                + " is ASEC-hosted -> AVAILABLE");
1435                                    }
1436                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1437                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1438                                    pkgList.add(packageName);
1439                                    sendResourcesChangedBroadcast(true, true,
1440                                            pkgList,uidArray, null);
1441                                }
1442                            }
1443                            if (res.removedInfo.args != null) {
1444                                // Remove the replaced package's older resources safely now
1445                                deleteOld = true;
1446                            }
1447
1448                            // If this app is a browser and it's newly-installed for some
1449                            // users, clear any default-browser state in those users
1450                            if (firstUsers.length > 0) {
1451                                // the app's nature doesn't depend on the user, so we can just
1452                                // check its browser nature in any user and generalize.
1453                                if (packageIsBrowser(packageName, firstUsers[0])) {
1454                                    synchronized (mPackages) {
1455                                        for (int userId : firstUsers) {
1456                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1457                                        }
1458                                    }
1459                                }
1460                            }
1461                            // Log current value of "unknown sources" setting
1462                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1463                                getUnknownSourcesSettings());
1464                        }
1465                        // Force a gc to clear up things
1466                        Runtime.getRuntime().gc();
1467                        // We delete after a gc for applications  on sdcard.
1468                        if (deleteOld) {
1469                            synchronized (mInstallLock) {
1470                                res.removedInfo.args.doPostDeleteLI(true);
1471                            }
1472                        }
1473                        if (args.observer != null) {
1474                            try {
1475                                Bundle extras = extrasForInstallResult(res);
1476                                args.observer.onPackageInstalled(res.name, res.returnCode,
1477                                        res.returnMsg, extras);
1478                            } catch (RemoteException e) {
1479                                Slog.i(TAG, "Observer no longer exists.");
1480                            }
1481                        }
1482                        if (args.traceMethod != null) {
1483                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1484                                    args.traceCookie);
1485                        }
1486                        return;
1487                    } else {
1488                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1489                    }
1490
1491                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1492                } break;
1493                case UPDATED_MEDIA_STATUS: {
1494                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1495                    boolean reportStatus = msg.arg1 == 1;
1496                    boolean doGc = msg.arg2 == 1;
1497                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1498                    if (doGc) {
1499                        // Force a gc to clear up stale containers.
1500                        Runtime.getRuntime().gc();
1501                    }
1502                    if (msg.obj != null) {
1503                        @SuppressWarnings("unchecked")
1504                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1505                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1506                        // Unload containers
1507                        unloadAllContainers(args);
1508                    }
1509                    if (reportStatus) {
1510                        try {
1511                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1512                            PackageHelper.getMountService().finishMediaUpdate();
1513                        } catch (RemoteException e) {
1514                            Log.e(TAG, "MountService not running?");
1515                        }
1516                    }
1517                } break;
1518                case WRITE_SETTINGS: {
1519                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1520                    synchronized (mPackages) {
1521                        removeMessages(WRITE_SETTINGS);
1522                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1523                        mSettings.writeLPr();
1524                        mDirtyUsers.clear();
1525                    }
1526                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1527                } break;
1528                case WRITE_PACKAGE_RESTRICTIONS: {
1529                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1530                    synchronized (mPackages) {
1531                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1532                        for (int userId : mDirtyUsers) {
1533                            mSettings.writePackageRestrictionsLPr(userId);
1534                        }
1535                        mDirtyUsers.clear();
1536                    }
1537                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1538                } break;
1539                case CHECK_PENDING_VERIFICATION: {
1540                    final int verificationId = msg.arg1;
1541                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1542
1543                    if ((state != null) && !state.timeoutExtended()) {
1544                        final InstallArgs args = state.getInstallArgs();
1545                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1546
1547                        Slog.i(TAG, "Verification timed out for " + originUri);
1548                        mPendingVerification.remove(verificationId);
1549
1550                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1551
1552                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1553                            Slog.i(TAG, "Continuing with installation of " + originUri);
1554                            state.setVerifierResponse(Binder.getCallingUid(),
1555                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1556                            broadcastPackageVerified(verificationId, originUri,
1557                                    PackageManager.VERIFICATION_ALLOW,
1558                                    state.getInstallArgs().getUser());
1559                            try {
1560                                ret = args.copyApk(mContainerService, true);
1561                            } catch (RemoteException e) {
1562                                Slog.e(TAG, "Could not contact the ContainerService");
1563                            }
1564                        } else {
1565                            broadcastPackageVerified(verificationId, originUri,
1566                                    PackageManager.VERIFICATION_REJECT,
1567                                    state.getInstallArgs().getUser());
1568                        }
1569
1570                        Trace.asyncTraceEnd(
1571                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1572
1573                        processPendingInstall(args, ret);
1574                        mHandler.sendEmptyMessage(MCS_UNBIND);
1575                    }
1576                    break;
1577                }
1578                case PACKAGE_VERIFIED: {
1579                    final int verificationId = msg.arg1;
1580
1581                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1582                    if (state == null) {
1583                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1584                        break;
1585                    }
1586
1587                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1588
1589                    state.setVerifierResponse(response.callerUid, response.code);
1590
1591                    if (state.isVerificationComplete()) {
1592                        mPendingVerification.remove(verificationId);
1593
1594                        final InstallArgs args = state.getInstallArgs();
1595                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1596
1597                        int ret;
1598                        if (state.isInstallAllowed()) {
1599                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1600                            broadcastPackageVerified(verificationId, originUri,
1601                                    response.code, state.getInstallArgs().getUser());
1602                            try {
1603                                ret = args.copyApk(mContainerService, true);
1604                            } catch (RemoteException e) {
1605                                Slog.e(TAG, "Could not contact the ContainerService");
1606                            }
1607                        } else {
1608                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1609                        }
1610
1611                        Trace.asyncTraceEnd(
1612                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1613
1614                        processPendingInstall(args, ret);
1615                        mHandler.sendEmptyMessage(MCS_UNBIND);
1616                    }
1617
1618                    break;
1619                }
1620                case START_INTENT_FILTER_VERIFICATIONS: {
1621                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1622                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1623                            params.replacing, params.pkg);
1624                    break;
1625                }
1626                case INTENT_FILTER_VERIFIED: {
1627                    final int verificationId = msg.arg1;
1628
1629                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1630                            verificationId);
1631                    if (state == null) {
1632                        Slog.w(TAG, "Invalid IntentFilter verification token "
1633                                + verificationId + " received");
1634                        break;
1635                    }
1636
1637                    final int userId = state.getUserId();
1638
1639                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1640                            "Processing IntentFilter verification with token:"
1641                            + verificationId + " and userId:" + userId);
1642
1643                    final IntentFilterVerificationResponse response =
1644                            (IntentFilterVerificationResponse) msg.obj;
1645
1646                    state.setVerifierResponse(response.callerUid, response.code);
1647
1648                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1649                            "IntentFilter verification with token:" + verificationId
1650                            + " and userId:" + userId
1651                            + " is settings verifier response with response code:"
1652                            + response.code);
1653
1654                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1655                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1656                                + response.getFailedDomainsString());
1657                    }
1658
1659                    if (state.isVerificationComplete()) {
1660                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1661                    } else {
1662                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1663                                "IntentFilter verification with token:" + verificationId
1664                                + " was not said to be complete");
1665                    }
1666
1667                    break;
1668                }
1669            }
1670        }
1671    }
1672
1673    private StorageEventListener mStorageListener = new StorageEventListener() {
1674        @Override
1675        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1676            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1677                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1678                    final String volumeUuid = vol.getFsUuid();
1679
1680                    // Clean up any users or apps that were removed or recreated
1681                    // while this volume was missing
1682                    reconcileUsers(volumeUuid);
1683                    reconcileApps(volumeUuid);
1684
1685                    // Clean up any install sessions that expired or were
1686                    // cancelled while this volume was missing
1687                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1688
1689                    loadPrivatePackages(vol);
1690
1691                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1692                    unloadPrivatePackages(vol);
1693                }
1694            }
1695
1696            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1697                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1698                    updateExternalMediaStatus(true, false);
1699                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1700                    updateExternalMediaStatus(false, false);
1701                }
1702            }
1703        }
1704
1705        @Override
1706        public void onVolumeForgotten(String fsUuid) {
1707            if (TextUtils.isEmpty(fsUuid)) {
1708                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1709                return;
1710            }
1711
1712            // Remove any apps installed on the forgotten volume
1713            synchronized (mPackages) {
1714                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1715                for (PackageSetting ps : packages) {
1716                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1717                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1718                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1719                }
1720
1721                mSettings.onVolumeForgotten(fsUuid);
1722                mSettings.writeLPr();
1723            }
1724        }
1725    };
1726
1727    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1728            String[] grantedPermissions) {
1729        if (userId >= UserHandle.USER_SYSTEM) {
1730            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1731        } else if (userId == UserHandle.USER_ALL) {
1732            final int[] userIds;
1733            synchronized (mPackages) {
1734                userIds = UserManagerService.getInstance().getUserIds();
1735            }
1736            for (int someUserId : userIds) {
1737                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1738            }
1739        }
1740
1741        // We could have touched GID membership, so flush out packages.list
1742        synchronized (mPackages) {
1743            mSettings.writePackageListLPr();
1744        }
1745    }
1746
1747    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1748            String[] grantedPermissions) {
1749        SettingBase sb = (SettingBase) pkg.mExtras;
1750        if (sb == null) {
1751            return;
1752        }
1753
1754        PermissionsState permissionsState = sb.getPermissionsState();
1755
1756        for (String permission : pkg.requestedPermissions) {
1757            BasePermission bp = mSettings.mPermissions.get(permission);
1758            if (bp != null && bp.isRuntime() && (grantedPermissions == null
1759                    || ArrayUtils.contains(grantedPermissions, permission))) {
1760                permissionsState.grantRuntimePermission(bp, userId);
1761            }
1762        }
1763    }
1764
1765    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1766        Bundle extras = null;
1767        switch (res.returnCode) {
1768            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1769                extras = new Bundle();
1770                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1771                        res.origPermission);
1772                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1773                        res.origPackage);
1774                break;
1775            }
1776            case PackageManager.INSTALL_SUCCEEDED: {
1777                extras = new Bundle();
1778                extras.putBoolean(Intent.EXTRA_REPLACING,
1779                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1780                break;
1781            }
1782        }
1783        return extras;
1784    }
1785
1786    void scheduleWriteSettingsLocked() {
1787        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1788            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1789        }
1790    }
1791
1792    void scheduleWritePackageRestrictionsLocked(int userId) {
1793        if (!sUserManager.exists(userId)) return;
1794        mDirtyUsers.add(userId);
1795        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1796            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1797        }
1798    }
1799
1800    public static PackageManagerService main(Context context, Installer installer,
1801            boolean factoryTest, boolean onlyCore) {
1802        PackageManagerService m = new PackageManagerService(context, installer,
1803                factoryTest, onlyCore);
1804        ServiceManager.addService("package", m);
1805        return m;
1806    }
1807
1808    static String[] splitString(String str, char sep) {
1809        int count = 1;
1810        int i = 0;
1811        while ((i=str.indexOf(sep, i)) >= 0) {
1812            count++;
1813            i++;
1814        }
1815
1816        String[] res = new String[count];
1817        i=0;
1818        count = 0;
1819        int lastI=0;
1820        while ((i=str.indexOf(sep, i)) >= 0) {
1821            res[count] = str.substring(lastI, i);
1822            count++;
1823            i++;
1824            lastI = i;
1825        }
1826        res[count] = str.substring(lastI, str.length());
1827        return res;
1828    }
1829
1830    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1831        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1832                Context.DISPLAY_SERVICE);
1833        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1834    }
1835
1836    public PackageManagerService(Context context, Installer installer,
1837            boolean factoryTest, boolean onlyCore) {
1838        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1839                SystemClock.uptimeMillis());
1840
1841        if (mSdkVersion <= 0) {
1842            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1843        }
1844
1845        mContext = context;
1846        mFactoryTest = factoryTest;
1847        mOnlyCore = onlyCore;
1848        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1849        mMetrics = new DisplayMetrics();
1850        mSettings = new Settings(mPackages);
1851        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1852                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1853        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1854                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1855        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1856                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1857        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1858                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1859        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1860                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1861        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1862                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1863
1864        // TODO: add a property to control this?
1865        long dexOptLRUThresholdInMinutes;
1866        if (mLazyDexOpt) {
1867            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1868        } else {
1869            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1870        }
1871        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1872
1873        String separateProcesses = SystemProperties.get("debug.separate_processes");
1874        if (separateProcesses != null && separateProcesses.length() > 0) {
1875            if ("*".equals(separateProcesses)) {
1876                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1877                mSeparateProcesses = null;
1878                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1879            } else {
1880                mDefParseFlags = 0;
1881                mSeparateProcesses = separateProcesses.split(",");
1882                Slog.w(TAG, "Running with debug.separate_processes: "
1883                        + separateProcesses);
1884            }
1885        } else {
1886            mDefParseFlags = 0;
1887            mSeparateProcesses = null;
1888        }
1889
1890        mInstaller = installer;
1891        mPackageDexOptimizer = new PackageDexOptimizer(this);
1892        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1893
1894        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1895                FgThread.get().getLooper());
1896
1897        getDefaultDisplayMetrics(context, mMetrics);
1898
1899        SystemConfig systemConfig = SystemConfig.getInstance();
1900        mGlobalGids = systemConfig.getGlobalGids();
1901        mSystemPermissions = systemConfig.getSystemPermissions();
1902        mAvailableFeatures = systemConfig.getAvailableFeatures();
1903
1904        synchronized (mInstallLock) {
1905        // writer
1906        synchronized (mPackages) {
1907            mHandlerThread = new ServiceThread(TAG,
1908                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1909            mHandlerThread.start();
1910            mHandler = new PackageHandler(mHandlerThread.getLooper());
1911            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1912
1913            File dataDir = Environment.getDataDirectory();
1914            mAppDataDir = new File(dataDir, "data");
1915            mAppInstallDir = new File(dataDir, "app");
1916            mAppLib32InstallDir = new File(dataDir, "app-lib");
1917            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1918            mUserAppDataDir = new File(dataDir, "user");
1919            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1920
1921            sUserManager = new UserManagerService(context, this,
1922                    mInstallLock, mPackages);
1923
1924            // Propagate permission configuration in to package manager.
1925            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1926                    = systemConfig.getPermissions();
1927            for (int i=0; i<permConfig.size(); i++) {
1928                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1929                BasePermission bp = mSettings.mPermissions.get(perm.name);
1930                if (bp == null) {
1931                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1932                    mSettings.mPermissions.put(perm.name, bp);
1933                }
1934                if (perm.gids != null) {
1935                    bp.setGids(perm.gids, perm.perUser);
1936                }
1937            }
1938
1939            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1940            for (int i=0; i<libConfig.size(); i++) {
1941                mSharedLibraries.put(libConfig.keyAt(i),
1942                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1943            }
1944
1945            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1946
1947            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
1948
1949            String customResolverActivity = Resources.getSystem().getString(
1950                    R.string.config_customResolverActivity);
1951            if (TextUtils.isEmpty(customResolverActivity)) {
1952                customResolverActivity = null;
1953            } else {
1954                mCustomResolverComponentName = ComponentName.unflattenFromString(
1955                        customResolverActivity);
1956            }
1957
1958            long startTime = SystemClock.uptimeMillis();
1959
1960            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1961                    startTime);
1962
1963            // Set flag to monitor and not change apk file paths when
1964            // scanning install directories.
1965            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
1966
1967            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1968
1969            /**
1970             * Add everything in the in the boot class path to the
1971             * list of process files because dexopt will have been run
1972             * if necessary during zygote startup.
1973             */
1974            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1975            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1976
1977            if (bootClassPath != null) {
1978                String[] bootClassPathElements = splitString(bootClassPath, ':');
1979                for (String element : bootClassPathElements) {
1980                    alreadyDexOpted.add(element);
1981                }
1982            } else {
1983                Slog.w(TAG, "No BOOTCLASSPATH found!");
1984            }
1985
1986            if (systemServerClassPath != null) {
1987                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1988                for (String element : systemServerClassPathElements) {
1989                    alreadyDexOpted.add(element);
1990                }
1991            } else {
1992                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1993            }
1994
1995            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1996            final String[] dexCodeInstructionSets =
1997                    getDexCodeInstructionSets(
1998                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1999
2000            /**
2001             * Ensure all external libraries have had dexopt run on them.
2002             */
2003            if (mSharedLibraries.size() > 0) {
2004                // NOTE: For now, we're compiling these system "shared libraries"
2005                // (and framework jars) into all available architectures. It's possible
2006                // to compile them only when we come across an app that uses them (there's
2007                // already logic for that in scanPackageLI) but that adds some complexity.
2008                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2009                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2010                        final String lib = libEntry.path;
2011                        if (lib == null) {
2012                            continue;
2013                        }
2014
2015                        try {
2016                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2017                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2018                                alreadyDexOpted.add(lib);
2019                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2020                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2021                            }
2022                        } catch (FileNotFoundException e) {
2023                            Slog.w(TAG, "Library not found: " + lib);
2024                        } catch (IOException e) {
2025                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2026                                    + e.getMessage());
2027                        }
2028                    }
2029                }
2030            }
2031
2032            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2033
2034            // Gross hack for now: we know this file doesn't contain any
2035            // code, so don't dexopt it to avoid the resulting log spew.
2036            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
2037
2038            // Gross hack for now: we know this file is only part of
2039            // the boot class path for art, so don't dexopt it to
2040            // avoid the resulting log spew.
2041            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
2042
2043            /**
2044             * There are a number of commands implemented in Java, which
2045             * we currently need to do the dexopt on so that they can be
2046             * run from a non-root shell.
2047             */
2048            String[] frameworkFiles = frameworkDir.list();
2049            if (frameworkFiles != null) {
2050                // TODO: We could compile these only for the most preferred ABI. We should
2051                // first double check that the dex files for these commands are not referenced
2052                // by other system apps.
2053                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2054                    for (int i=0; i<frameworkFiles.length; i++) {
2055                        File libPath = new File(frameworkDir, frameworkFiles[i]);
2056                        String path = libPath.getPath();
2057                        // Skip the file if we already did it.
2058                        if (alreadyDexOpted.contains(path)) {
2059                            continue;
2060                        }
2061                        // Skip the file if it is not a type we want to dexopt.
2062                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
2063                            continue;
2064                        }
2065                        try {
2066                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
2067                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2068                                mInstaller.dexopt(path, Process.SYSTEM_UID, dexCodeInstructionSet,
2069                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2070                            }
2071                        } catch (FileNotFoundException e) {
2072                            Slog.w(TAG, "Jar not found: " + path);
2073                        } catch (IOException e) {
2074                            Slog.w(TAG, "Exception reading jar: " + path, e);
2075                        }
2076                    }
2077                }
2078            }
2079
2080            final VersionInfo ver = mSettings.getInternalVersion();
2081            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2082            // when upgrading from pre-M, promote system app permissions from install to runtime
2083            mPromoteSystemApps =
2084                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2085
2086            // save off the names of pre-existing system packages prior to scanning; we don't
2087            // want to automatically grant runtime permissions for new system apps
2088            if (mPromoteSystemApps) {
2089                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2090                while (pkgSettingIter.hasNext()) {
2091                    PackageSetting ps = pkgSettingIter.next();
2092                    if (isSystemApp(ps)) {
2093                        mExistingSystemPackages.add(ps.name);
2094                    }
2095                }
2096            }
2097
2098            // Collect vendor overlay packages.
2099            // (Do this before scanning any apps.)
2100            // For security and version matching reason, only consider
2101            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2102            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2103            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2104                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2105
2106            // Find base frameworks (resource packages without code).
2107            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2108                    | PackageParser.PARSE_IS_SYSTEM_DIR
2109                    | PackageParser.PARSE_IS_PRIVILEGED,
2110                    scanFlags | SCAN_NO_DEX, 0);
2111
2112            // Collected privileged system packages.
2113            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2114            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2115                    | PackageParser.PARSE_IS_SYSTEM_DIR
2116                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2117
2118            // Collect ordinary system packages.
2119            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2120            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2121                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2122
2123            // Collect all vendor packages.
2124            File vendorAppDir = new File("/vendor/app");
2125            try {
2126                vendorAppDir = vendorAppDir.getCanonicalFile();
2127            } catch (IOException e) {
2128                // failed to look up canonical path, continue with original one
2129            }
2130            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2131                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2132
2133            // Collect all OEM packages.
2134            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2135            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2136                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2137
2138            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2139            mInstaller.moveFiles();
2140
2141            // Prune any system packages that no longer exist.
2142            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2143            if (!mOnlyCore) {
2144                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2145                while (psit.hasNext()) {
2146                    PackageSetting ps = psit.next();
2147
2148                    /*
2149                     * If this is not a system app, it can't be a
2150                     * disable system app.
2151                     */
2152                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2153                        continue;
2154                    }
2155
2156                    /*
2157                     * If the package is scanned, it's not erased.
2158                     */
2159                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2160                    if (scannedPkg != null) {
2161                        /*
2162                         * If the system app is both scanned and in the
2163                         * disabled packages list, then it must have been
2164                         * added via OTA. Remove it from the currently
2165                         * scanned package so the previously user-installed
2166                         * application can be scanned.
2167                         */
2168                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2169                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2170                                    + ps.name + "; removing system app.  Last known codePath="
2171                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2172                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2173                                    + scannedPkg.mVersionCode);
2174                            removePackageLI(ps, true);
2175                            mExpectingBetter.put(ps.name, ps.codePath);
2176                        }
2177
2178                        continue;
2179                    }
2180
2181                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2182                        psit.remove();
2183                        logCriticalInfo(Log.WARN, "System package " + ps.name
2184                                + " no longer exists; wiping its data");
2185                        removeDataDirsLI(null, ps.name);
2186                    } else {
2187                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2188                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2189                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2190                        }
2191                    }
2192                }
2193            }
2194
2195            //look for any incomplete package installations
2196            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2197            //clean up list
2198            for(int i = 0; i < deletePkgsList.size(); i++) {
2199                //clean up here
2200                cleanupInstallFailedPackage(deletePkgsList.get(i));
2201            }
2202            //delete tmp files
2203            deleteTempPackageFiles();
2204
2205            // Remove any shared userIDs that have no associated packages
2206            mSettings.pruneSharedUsersLPw();
2207
2208            if (!mOnlyCore) {
2209                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2210                        SystemClock.uptimeMillis());
2211                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2212
2213                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2214                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2215
2216                /**
2217                 * Remove disable package settings for any updated system
2218                 * apps that were removed via an OTA. If they're not a
2219                 * previously-updated app, remove them completely.
2220                 * Otherwise, just revoke their system-level permissions.
2221                 */
2222                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2223                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2224                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2225
2226                    String msg;
2227                    if (deletedPkg == null) {
2228                        msg = "Updated system package " + deletedAppName
2229                                + " no longer exists; wiping its data";
2230                        removeDataDirsLI(null, deletedAppName);
2231                    } else {
2232                        msg = "Updated system app + " + deletedAppName
2233                                + " no longer present; removing system privileges for "
2234                                + deletedAppName;
2235
2236                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2237
2238                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2239                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2240                    }
2241                    logCriticalInfo(Log.WARN, msg);
2242                }
2243
2244                /**
2245                 * Make sure all system apps that we expected to appear on
2246                 * the userdata partition actually showed up. If they never
2247                 * appeared, crawl back and revive the system version.
2248                 */
2249                for (int i = 0; i < mExpectingBetter.size(); i++) {
2250                    final String packageName = mExpectingBetter.keyAt(i);
2251                    if (!mPackages.containsKey(packageName)) {
2252                        final File scanFile = mExpectingBetter.valueAt(i);
2253
2254                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2255                                + " but never showed up; reverting to system");
2256
2257                        final int reparseFlags;
2258                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2259                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2260                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2261                                    | PackageParser.PARSE_IS_PRIVILEGED;
2262                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2263                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2264                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2265                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2266                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2267                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2268                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2269                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2270                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2271                        } else {
2272                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2273                            continue;
2274                        }
2275
2276                        mSettings.enableSystemPackageLPw(packageName);
2277
2278                        try {
2279                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, UserHandle.SYSTEM);
2280                        } catch (PackageManagerException e) {
2281                            Slog.e(TAG, "Failed to parse original system package: "
2282                                    + e.getMessage());
2283                        }
2284                    }
2285                }
2286            }
2287            mExpectingBetter.clear();
2288
2289            // Now that we know all of the shared libraries, update all clients to have
2290            // the correct library paths.
2291            updateAllSharedLibrariesLPw();
2292
2293            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2294                // NOTE: We ignore potential failures here during a system scan (like
2295                // the rest of the commands above) because there's precious little we
2296                // can do about it. A settings error is reported, though.
2297                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2298                        false /* force dexopt */, false /* defer dexopt */,
2299                        false /* boot complete */);
2300            }
2301
2302            // Now that we know all the packages we are keeping,
2303            // read and update their last usage times.
2304            mPackageUsage.readLP();
2305
2306            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2307                    SystemClock.uptimeMillis());
2308            Slog.i(TAG, "Time to scan packages: "
2309                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2310                    + " seconds");
2311
2312            // If the platform SDK has changed since the last time we booted,
2313            // we need to re-grant app permission to catch any new ones that
2314            // appear.  This is really a hack, and means that apps can in some
2315            // cases get permissions that the user didn't initially explicitly
2316            // allow...  it would be nice to have some better way to handle
2317            // this situation.
2318            int updateFlags = UPDATE_PERMISSIONS_ALL;
2319            if (ver.sdkVersion != mSdkVersion) {
2320                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2321                        + mSdkVersion + "; regranting permissions for internal storage");
2322                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2323            }
2324            updatePermissionsLPw(null, null, updateFlags);
2325            ver.sdkVersion = mSdkVersion;
2326
2327            // If this is the first boot or an update from pre-M, and it is a normal
2328            // boot, then we need to initialize the default preferred apps across
2329            // all defined users.
2330            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2331                for (UserInfo user : sUserManager.getUsers(true)) {
2332                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2333                    applyFactoryDefaultBrowserLPw(user.id);
2334                    primeDomainVerificationsLPw(user.id);
2335                }
2336            }
2337
2338            // If this is first boot after an OTA, and a normal boot, then
2339            // we need to clear code cache directories.
2340            if (mIsUpgrade && !onlyCore) {
2341                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2342                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2343                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2344                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2345                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2346                    }
2347                }
2348                ver.fingerprint = Build.FINGERPRINT;
2349            }
2350
2351            checkDefaultBrowser();
2352
2353            // clear only after permissions and other defaults have been updated
2354            mExistingSystemPackages.clear();
2355            mPromoteSystemApps = false;
2356
2357            // All the changes are done during package scanning.
2358            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2359
2360            // can downgrade to reader
2361            mSettings.writeLPr();
2362
2363            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2364                    SystemClock.uptimeMillis());
2365
2366            mRequiredVerifierPackage = getRequiredVerifierLPr();
2367            mRequiredInstallerPackage = getRequiredInstallerLPr();
2368
2369            mInstallerService = new PackageInstallerService(context, this);
2370
2371            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2372            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2373                    mIntentFilterVerifierComponent);
2374
2375        } // synchronized (mPackages)
2376        } // synchronized (mInstallLock)
2377
2378        // Now after opening every single application zip, make sure they
2379        // are all flushed.  Not really needed, but keeps things nice and
2380        // tidy.
2381        Runtime.getRuntime().gc();
2382
2383        // Expose private service for system components to use.
2384        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2385    }
2386
2387    @Override
2388    public boolean isFirstBoot() {
2389        return !mRestoredSettings;
2390    }
2391
2392    @Override
2393    public boolean isOnlyCoreApps() {
2394        return mOnlyCore;
2395    }
2396
2397    @Override
2398    public boolean isUpgrade() {
2399        return mIsUpgrade;
2400    }
2401
2402    private String getRequiredVerifierLPr() {
2403        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2404        // We only care about verifier that's installed under system user.
2405        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2406                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2407
2408        String requiredVerifier = null;
2409
2410        final int N = receivers.size();
2411        for (int i = 0; i < N; i++) {
2412            final ResolveInfo info = receivers.get(i);
2413
2414            if (info.activityInfo == null) {
2415                continue;
2416            }
2417
2418            final String packageName = info.activityInfo.packageName;
2419
2420            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2421                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2422                continue;
2423            }
2424
2425            if (requiredVerifier != null) {
2426                throw new RuntimeException("There can be only one required verifier");
2427            }
2428
2429            requiredVerifier = packageName;
2430        }
2431
2432        return requiredVerifier;
2433    }
2434
2435    private String getRequiredInstallerLPr() {
2436        Intent installerIntent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2437        installerIntent.addCategory(Intent.CATEGORY_DEFAULT);
2438        installerIntent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2439
2440        final List<ResolveInfo> installers = queryIntentActivities(installerIntent,
2441                PACKAGE_MIME_TYPE, 0, UserHandle.USER_SYSTEM);
2442
2443        String requiredInstaller = null;
2444
2445        final int N = installers.size();
2446        for (int i = 0; i < N; i++) {
2447            final ResolveInfo info = installers.get(i);
2448            final String packageName = info.activityInfo.packageName;
2449
2450            if (!info.activityInfo.applicationInfo.isSystemApp()) {
2451                continue;
2452            }
2453
2454            if (requiredInstaller != null) {
2455                throw new RuntimeException("There must be one required installer");
2456            }
2457
2458            requiredInstaller = packageName;
2459        }
2460
2461        if (requiredInstaller == null) {
2462            throw new RuntimeException("There must be one required installer");
2463        }
2464
2465        return requiredInstaller;
2466    }
2467
2468    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2469        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2470        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2471                PackageManager.GET_DISABLED_COMPONENTS, UserHandle.USER_SYSTEM);
2472
2473        ComponentName verifierComponentName = null;
2474
2475        int priority = -1000;
2476        final int N = receivers.size();
2477        for (int i = 0; i < N; i++) {
2478            final ResolveInfo info = receivers.get(i);
2479
2480            if (info.activityInfo == null) {
2481                continue;
2482            }
2483
2484            final String packageName = info.activityInfo.packageName;
2485
2486            final PackageSetting ps = mSettings.mPackages.get(packageName);
2487            if (ps == null) {
2488                continue;
2489            }
2490
2491            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2492                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2493                continue;
2494            }
2495
2496            // Select the IntentFilterVerifier with the highest priority
2497            if (priority < info.priority) {
2498                priority = info.priority;
2499                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2500                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Selecting IntentFilterVerifier: "
2501                        + verifierComponentName + " with priority: " + info.priority);
2502            }
2503        }
2504
2505        return verifierComponentName;
2506    }
2507
2508    private void primeDomainVerificationsLPw(int userId) {
2509        if (DEBUG_DOMAIN_VERIFICATION) {
2510            Slog.d(TAG, "Priming domain verifications in user " + userId);
2511        }
2512
2513        SystemConfig systemConfig = SystemConfig.getInstance();
2514        ArraySet<String> packages = systemConfig.getLinkedApps();
2515        ArraySet<String> domains = new ArraySet<String>();
2516
2517        for (String packageName : packages) {
2518            PackageParser.Package pkg = mPackages.get(packageName);
2519            if (pkg != null) {
2520                if (!pkg.isSystemApp()) {
2521                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2522                    continue;
2523                }
2524
2525                domains.clear();
2526                for (PackageParser.Activity a : pkg.activities) {
2527                    for (ActivityIntentInfo filter : a.intents) {
2528                        if (hasValidDomains(filter)) {
2529                            domains.addAll(filter.getHostsList());
2530                        }
2531                    }
2532                }
2533
2534                if (domains.size() > 0) {
2535                    if (DEBUG_DOMAIN_VERIFICATION) {
2536                        Slog.v(TAG, "      + " + packageName);
2537                    }
2538                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2539                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2540                    // and then 'always' in the per-user state actually used for intent resolution.
2541                    final IntentFilterVerificationInfo ivi;
2542                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2543                            new ArrayList<String>(domains));
2544                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2545                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2546                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2547                } else {
2548                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2549                            + "' does not handle web links");
2550                }
2551            } else {
2552                Slog.w(TAG, "Unknown package '" + packageName + "' in sysconfig <app-link>");
2553            }
2554        }
2555
2556        scheduleWritePackageRestrictionsLocked(userId);
2557        scheduleWriteSettingsLocked();
2558    }
2559
2560    private void applyFactoryDefaultBrowserLPw(int userId) {
2561        // The default browser app's package name is stored in a string resource,
2562        // with a product-specific overlay used for vendor customization.
2563        String browserPkg = mContext.getResources().getString(
2564                com.android.internal.R.string.default_browser);
2565        if (!TextUtils.isEmpty(browserPkg)) {
2566            // non-empty string => required to be a known package
2567            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2568            if (ps == null) {
2569                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2570                browserPkg = null;
2571            } else {
2572                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2573            }
2574        }
2575
2576        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2577        // default.  If there's more than one, just leave everything alone.
2578        if (browserPkg == null) {
2579            calculateDefaultBrowserLPw(userId);
2580        }
2581    }
2582
2583    private void calculateDefaultBrowserLPw(int userId) {
2584        List<String> allBrowsers = resolveAllBrowserApps(userId);
2585        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2586        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2587    }
2588
2589    private List<String> resolveAllBrowserApps(int userId) {
2590        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2591        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2592                PackageManager.MATCH_ALL, userId);
2593
2594        final int count = list.size();
2595        List<String> result = new ArrayList<String>(count);
2596        for (int i=0; i<count; i++) {
2597            ResolveInfo info = list.get(i);
2598            if (info.activityInfo == null
2599                    || !info.handleAllWebDataURI
2600                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2601                    || result.contains(info.activityInfo.packageName)) {
2602                continue;
2603            }
2604            result.add(info.activityInfo.packageName);
2605        }
2606
2607        return result;
2608    }
2609
2610    private boolean packageIsBrowser(String packageName, int userId) {
2611        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2612                PackageManager.MATCH_ALL, userId);
2613        final int N = list.size();
2614        for (int i = 0; i < N; i++) {
2615            ResolveInfo info = list.get(i);
2616            if (packageName.equals(info.activityInfo.packageName)) {
2617                return true;
2618            }
2619        }
2620        return false;
2621    }
2622
2623    private void checkDefaultBrowser() {
2624        final int myUserId = UserHandle.myUserId();
2625        final String packageName = getDefaultBrowserPackageName(myUserId);
2626        if (packageName != null) {
2627            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2628            if (info == null) {
2629                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2630                synchronized (mPackages) {
2631                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2632                }
2633            }
2634        }
2635    }
2636
2637    @Override
2638    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2639            throws RemoteException {
2640        try {
2641            return super.onTransact(code, data, reply, flags);
2642        } catch (RuntimeException e) {
2643            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2644                Slog.wtf(TAG, "Package Manager Crash", e);
2645            }
2646            throw e;
2647        }
2648    }
2649
2650    void cleanupInstallFailedPackage(PackageSetting ps) {
2651        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2652
2653        removeDataDirsLI(ps.volumeUuid, ps.name);
2654        if (ps.codePath != null) {
2655            if (ps.codePath.isDirectory()) {
2656                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2657            } else {
2658                ps.codePath.delete();
2659            }
2660        }
2661        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2662            if (ps.resourcePath.isDirectory()) {
2663                FileUtils.deleteContents(ps.resourcePath);
2664            }
2665            ps.resourcePath.delete();
2666        }
2667        mSettings.removePackageLPw(ps.name);
2668    }
2669
2670    static int[] appendInts(int[] cur, int[] add) {
2671        if (add == null) return cur;
2672        if (cur == null) return add;
2673        final int N = add.length;
2674        for (int i=0; i<N; i++) {
2675            cur = appendInt(cur, add[i]);
2676        }
2677        return cur;
2678    }
2679
2680    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2681        if (!sUserManager.exists(userId)) return null;
2682        final PackageSetting ps = (PackageSetting) p.mExtras;
2683        if (ps == null) {
2684            return null;
2685        }
2686
2687        final PermissionsState permissionsState = ps.getPermissionsState();
2688
2689        final int[] gids = permissionsState.computeGids(userId);
2690        final Set<String> permissions = permissionsState.getPermissions(userId);
2691        final PackageUserState state = ps.readUserState(userId);
2692
2693        return PackageParser.generatePackageInfo(p, gids, flags,
2694                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2695    }
2696
2697    @Override
2698    public boolean isPackageFrozen(String packageName) {
2699        synchronized (mPackages) {
2700            final PackageSetting ps = mSettings.mPackages.get(packageName);
2701            if (ps != null) {
2702                return ps.frozen;
2703            }
2704        }
2705        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2706        return true;
2707    }
2708
2709    @Override
2710    public boolean isPackageAvailable(String packageName, int userId) {
2711        if (!sUserManager.exists(userId)) return false;
2712        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2713        synchronized (mPackages) {
2714            PackageParser.Package p = mPackages.get(packageName);
2715            if (p != null) {
2716                final PackageSetting ps = (PackageSetting) p.mExtras;
2717                if (ps != null) {
2718                    final PackageUserState state = ps.readUserState(userId);
2719                    if (state != null) {
2720                        return PackageParser.isAvailable(state);
2721                    }
2722                }
2723            }
2724        }
2725        return false;
2726    }
2727
2728    @Override
2729    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2730        if (!sUserManager.exists(userId)) return null;
2731        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2732        // reader
2733        synchronized (mPackages) {
2734            PackageParser.Package p = mPackages.get(packageName);
2735            if (DEBUG_PACKAGE_INFO)
2736                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2737            if (p != null) {
2738                return generatePackageInfo(p, flags, userId);
2739            }
2740            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2741                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2742            }
2743        }
2744        return null;
2745    }
2746
2747    @Override
2748    public String[] currentToCanonicalPackageNames(String[] names) {
2749        String[] out = new String[names.length];
2750        // reader
2751        synchronized (mPackages) {
2752            for (int i=names.length-1; i>=0; i--) {
2753                PackageSetting ps = mSettings.mPackages.get(names[i]);
2754                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2755            }
2756        }
2757        return out;
2758    }
2759
2760    @Override
2761    public String[] canonicalToCurrentPackageNames(String[] names) {
2762        String[] out = new String[names.length];
2763        // reader
2764        synchronized (mPackages) {
2765            for (int i=names.length-1; i>=0; i--) {
2766                String cur = mSettings.mRenamedPackages.get(names[i]);
2767                out[i] = cur != null ? cur : names[i];
2768            }
2769        }
2770        return out;
2771    }
2772
2773    @Override
2774    public int getPackageUid(String packageName, int userId) {
2775        if (!sUserManager.exists(userId)) return -1;
2776        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2777
2778        // reader
2779        synchronized (mPackages) {
2780            PackageParser.Package p = mPackages.get(packageName);
2781            if(p != null) {
2782                return UserHandle.getUid(userId, p.applicationInfo.uid);
2783            }
2784            PackageSetting ps = mSettings.mPackages.get(packageName);
2785            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2786                return -1;
2787            }
2788            return UserHandle.getUid(userId, ps.pkg.applicationInfo.uid);
2789        }
2790    }
2791
2792    @Override
2793    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2794        if (!sUserManager.exists(userId)) {
2795            return null;
2796        }
2797
2798        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2799                "getPackageGids");
2800
2801        // reader
2802        synchronized (mPackages) {
2803            PackageParser.Package p = mPackages.get(packageName);
2804            if (DEBUG_PACKAGE_INFO) {
2805                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2806            }
2807            if (p != null) {
2808                PackageSetting ps = (PackageSetting) p.mExtras;
2809                return ps.getPermissionsState().computeGids(userId);
2810            }
2811        }
2812
2813        return null;
2814    }
2815
2816    static PermissionInfo generatePermissionInfo(
2817            BasePermission bp, int flags) {
2818        if (bp.perm != null) {
2819            return PackageParser.generatePermissionInfo(bp.perm, flags);
2820        }
2821        PermissionInfo pi = new PermissionInfo();
2822        pi.name = bp.name;
2823        pi.packageName = bp.sourcePackage;
2824        pi.nonLocalizedLabel = bp.name;
2825        pi.protectionLevel = bp.protectionLevel;
2826        return pi;
2827    }
2828
2829    @Override
2830    public PermissionInfo getPermissionInfo(String name, int flags) {
2831        // reader
2832        synchronized (mPackages) {
2833            final BasePermission p = mSettings.mPermissions.get(name);
2834            if (p != null) {
2835                return generatePermissionInfo(p, flags);
2836            }
2837            return null;
2838        }
2839    }
2840
2841    @Override
2842    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2843        // reader
2844        synchronized (mPackages) {
2845            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2846            for (BasePermission p : mSettings.mPermissions.values()) {
2847                if (group == null) {
2848                    if (p.perm == null || p.perm.info.group == null) {
2849                        out.add(generatePermissionInfo(p, flags));
2850                    }
2851                } else {
2852                    if (p.perm != null && group.equals(p.perm.info.group)) {
2853                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2854                    }
2855                }
2856            }
2857
2858            if (out.size() > 0) {
2859                return out;
2860            }
2861            return mPermissionGroups.containsKey(group) ? out : null;
2862        }
2863    }
2864
2865    @Override
2866    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2867        // reader
2868        synchronized (mPackages) {
2869            return PackageParser.generatePermissionGroupInfo(
2870                    mPermissionGroups.get(name), flags);
2871        }
2872    }
2873
2874    @Override
2875    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2876        // reader
2877        synchronized (mPackages) {
2878            final int N = mPermissionGroups.size();
2879            ArrayList<PermissionGroupInfo> out
2880                    = new ArrayList<PermissionGroupInfo>(N);
2881            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2882                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2883            }
2884            return out;
2885        }
2886    }
2887
2888    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2889            int userId) {
2890        if (!sUserManager.exists(userId)) return null;
2891        PackageSetting ps = mSettings.mPackages.get(packageName);
2892        if (ps != null) {
2893            if (ps.pkg == null) {
2894                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2895                        flags, userId);
2896                if (pInfo != null) {
2897                    return pInfo.applicationInfo;
2898                }
2899                return null;
2900            }
2901            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2902                    ps.readUserState(userId), userId);
2903        }
2904        return null;
2905    }
2906
2907    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2908            int userId) {
2909        if (!sUserManager.exists(userId)) return null;
2910        PackageSetting ps = mSettings.mPackages.get(packageName);
2911        if (ps != null) {
2912            PackageParser.Package pkg = ps.pkg;
2913            if (pkg == null) {
2914                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2915                    return null;
2916                }
2917                // Only data remains, so we aren't worried about code paths
2918                pkg = new PackageParser.Package(packageName);
2919                pkg.applicationInfo.packageName = packageName;
2920                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2921                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2922                pkg.applicationInfo.dataDir = Environment
2923                        .getDataUserPackageDirectory(ps.volumeUuid, userId, packageName)
2924                        .getAbsolutePath();
2925                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2926                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2927            }
2928            return generatePackageInfo(pkg, flags, userId);
2929        }
2930        return null;
2931    }
2932
2933    @Override
2934    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2935        if (!sUserManager.exists(userId)) return null;
2936        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2937        // writer
2938        synchronized (mPackages) {
2939            PackageParser.Package p = mPackages.get(packageName);
2940            if (DEBUG_PACKAGE_INFO) Log.v(
2941                    TAG, "getApplicationInfo " + packageName
2942                    + ": " + p);
2943            if (p != null) {
2944                PackageSetting ps = mSettings.mPackages.get(packageName);
2945                if (ps == null) return null;
2946                // Note: isEnabledLP() does not apply here - always return info
2947                return PackageParser.generateApplicationInfo(
2948                        p, flags, ps.readUserState(userId), userId);
2949            }
2950            if ("android".equals(packageName)||"system".equals(packageName)) {
2951                return mAndroidApplication;
2952            }
2953            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2954                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2955            }
2956        }
2957        return null;
2958    }
2959
2960    @Override
2961    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2962            final IPackageDataObserver observer) {
2963        mContext.enforceCallingOrSelfPermission(
2964                android.Manifest.permission.CLEAR_APP_CACHE, null);
2965        // Queue up an async operation since clearing cache may take a little while.
2966        mHandler.post(new Runnable() {
2967            public void run() {
2968                mHandler.removeCallbacks(this);
2969                int retCode = -1;
2970                synchronized (mInstallLock) {
2971                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2972                    if (retCode < 0) {
2973                        Slog.w(TAG, "Couldn't clear application caches");
2974                    }
2975                }
2976                if (observer != null) {
2977                    try {
2978                        observer.onRemoveCompleted(null, (retCode >= 0));
2979                    } catch (RemoteException e) {
2980                        Slog.w(TAG, "RemoveException when invoking call back");
2981                    }
2982                }
2983            }
2984        });
2985    }
2986
2987    @Override
2988    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2989            final IntentSender pi) {
2990        mContext.enforceCallingOrSelfPermission(
2991                android.Manifest.permission.CLEAR_APP_CACHE, null);
2992        // Queue up an async operation since clearing cache may take a little while.
2993        mHandler.post(new Runnable() {
2994            public void run() {
2995                mHandler.removeCallbacks(this);
2996                int retCode = -1;
2997                synchronized (mInstallLock) {
2998                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2999                    if (retCode < 0) {
3000                        Slog.w(TAG, "Couldn't clear application caches");
3001                    }
3002                }
3003                if(pi != null) {
3004                    try {
3005                        // Callback via pending intent
3006                        int code = (retCode >= 0) ? 1 : 0;
3007                        pi.sendIntent(null, code, null,
3008                                null, null);
3009                    } catch (SendIntentException e1) {
3010                        Slog.i(TAG, "Failed to send pending intent");
3011                    }
3012                }
3013            }
3014        });
3015    }
3016
3017    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3018        synchronized (mInstallLock) {
3019            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3020                throw new IOException("Failed to free enough space");
3021            }
3022        }
3023    }
3024
3025    @Override
3026    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3027        if (!sUserManager.exists(userId)) return null;
3028        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3029        synchronized (mPackages) {
3030            PackageParser.Activity a = mActivities.mActivities.get(component);
3031
3032            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3033            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3034                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3035                if (ps == null) return null;
3036                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3037                        userId);
3038            }
3039            if (mResolveComponentName.equals(component)) {
3040                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3041                        new PackageUserState(), userId);
3042            }
3043        }
3044        return null;
3045    }
3046
3047    @Override
3048    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3049            String resolvedType) {
3050        synchronized (mPackages) {
3051            if (component.equals(mResolveComponentName)) {
3052                // The resolver supports EVERYTHING!
3053                return true;
3054            }
3055            PackageParser.Activity a = mActivities.mActivities.get(component);
3056            if (a == null) {
3057                return false;
3058            }
3059            for (int i=0; i<a.intents.size(); i++) {
3060                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3061                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3062                    return true;
3063                }
3064            }
3065            return false;
3066        }
3067    }
3068
3069    @Override
3070    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3071        if (!sUserManager.exists(userId)) return null;
3072        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3073        synchronized (mPackages) {
3074            PackageParser.Activity a = mReceivers.mActivities.get(component);
3075            if (DEBUG_PACKAGE_INFO) Log.v(
3076                TAG, "getReceiverInfo " + component + ": " + a);
3077            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
3078                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3079                if (ps == null) return null;
3080                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3081                        userId);
3082            }
3083        }
3084        return null;
3085    }
3086
3087    @Override
3088    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3089        if (!sUserManager.exists(userId)) return null;
3090        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3091        synchronized (mPackages) {
3092            PackageParser.Service s = mServices.mServices.get(component);
3093            if (DEBUG_PACKAGE_INFO) Log.v(
3094                TAG, "getServiceInfo " + component + ": " + s);
3095            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
3096                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3097                if (ps == null) return null;
3098                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3099                        userId);
3100            }
3101        }
3102        return null;
3103    }
3104
3105    @Override
3106    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3107        if (!sUserManager.exists(userId)) return null;
3108        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3109        synchronized (mPackages) {
3110            PackageParser.Provider p = mProviders.mProviders.get(component);
3111            if (DEBUG_PACKAGE_INFO) Log.v(
3112                TAG, "getProviderInfo " + component + ": " + p);
3113            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
3114                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3115                if (ps == null) return null;
3116                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3117                        userId);
3118            }
3119        }
3120        return null;
3121    }
3122
3123    @Override
3124    public String[] getSystemSharedLibraryNames() {
3125        Set<String> libSet;
3126        synchronized (mPackages) {
3127            libSet = mSharedLibraries.keySet();
3128            int size = libSet.size();
3129            if (size > 0) {
3130                String[] libs = new String[size];
3131                libSet.toArray(libs);
3132                return libs;
3133            }
3134        }
3135        return null;
3136    }
3137
3138    /**
3139     * @hide
3140     */
3141    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3142        synchronized (mPackages) {
3143            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3144            if (lib != null && lib.apk != null) {
3145                return mPackages.get(lib.apk);
3146            }
3147        }
3148        return null;
3149    }
3150
3151    @Override
3152    public FeatureInfo[] getSystemAvailableFeatures() {
3153        Collection<FeatureInfo> featSet;
3154        synchronized (mPackages) {
3155            featSet = mAvailableFeatures.values();
3156            int size = featSet.size();
3157            if (size > 0) {
3158                FeatureInfo[] features = new FeatureInfo[size+1];
3159                featSet.toArray(features);
3160                FeatureInfo fi = new FeatureInfo();
3161                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3162                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3163                features[size] = fi;
3164                return features;
3165            }
3166        }
3167        return null;
3168    }
3169
3170    @Override
3171    public boolean hasSystemFeature(String name) {
3172        synchronized (mPackages) {
3173            return mAvailableFeatures.containsKey(name);
3174        }
3175    }
3176
3177    private void checkValidCaller(int uid, int userId) {
3178        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
3179            return;
3180
3181        throw new SecurityException("Caller uid=" + uid
3182                + " is not privileged to communicate with user=" + userId);
3183    }
3184
3185    @Override
3186    public int checkPermission(String permName, String pkgName, int userId) {
3187        if (!sUserManager.exists(userId)) {
3188            return PackageManager.PERMISSION_DENIED;
3189        }
3190
3191        synchronized (mPackages) {
3192            final PackageParser.Package p = mPackages.get(pkgName);
3193            if (p != null && p.mExtras != null) {
3194                final PackageSetting ps = (PackageSetting) p.mExtras;
3195                final PermissionsState permissionsState = ps.getPermissionsState();
3196                if (permissionsState.hasPermission(permName, userId)) {
3197                    return PackageManager.PERMISSION_GRANTED;
3198                }
3199                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3200                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3201                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3202                    return PackageManager.PERMISSION_GRANTED;
3203                }
3204            }
3205        }
3206
3207        return PackageManager.PERMISSION_DENIED;
3208    }
3209
3210    @Override
3211    public int checkUidPermission(String permName, int uid) {
3212        final int userId = UserHandle.getUserId(uid);
3213
3214        if (!sUserManager.exists(userId)) {
3215            return PackageManager.PERMISSION_DENIED;
3216        }
3217
3218        synchronized (mPackages) {
3219            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3220            if (obj != null) {
3221                final SettingBase ps = (SettingBase) obj;
3222                final PermissionsState permissionsState = ps.getPermissionsState();
3223                if (permissionsState.hasPermission(permName, userId)) {
3224                    return PackageManager.PERMISSION_GRANTED;
3225                }
3226                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3227                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3228                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3229                    return PackageManager.PERMISSION_GRANTED;
3230                }
3231            } else {
3232                ArraySet<String> perms = mSystemPermissions.get(uid);
3233                if (perms != null) {
3234                    if (perms.contains(permName)) {
3235                        return PackageManager.PERMISSION_GRANTED;
3236                    }
3237                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3238                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3239                        return PackageManager.PERMISSION_GRANTED;
3240                    }
3241                }
3242            }
3243        }
3244
3245        return PackageManager.PERMISSION_DENIED;
3246    }
3247
3248    @Override
3249    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3250        if (UserHandle.getCallingUserId() != userId) {
3251            mContext.enforceCallingPermission(
3252                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3253                    "isPermissionRevokedByPolicy for user " + userId);
3254        }
3255
3256        if (checkPermission(permission, packageName, userId)
3257                == PackageManager.PERMISSION_GRANTED) {
3258            return false;
3259        }
3260
3261        final long identity = Binder.clearCallingIdentity();
3262        try {
3263            final int flags = getPermissionFlags(permission, packageName, userId);
3264            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3265        } finally {
3266            Binder.restoreCallingIdentity(identity);
3267        }
3268    }
3269
3270    @Override
3271    public String getPermissionControllerPackageName() {
3272        synchronized (mPackages) {
3273            return mRequiredInstallerPackage;
3274        }
3275    }
3276
3277    /**
3278     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3279     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3280     * @param checkShell TODO(yamasani):
3281     * @param message the message to log on security exception
3282     */
3283    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3284            boolean checkShell, String message) {
3285        if (userId < 0) {
3286            throw new IllegalArgumentException("Invalid userId " + userId);
3287        }
3288        if (checkShell) {
3289            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3290        }
3291        if (userId == UserHandle.getUserId(callingUid)) return;
3292        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3293            if (requireFullPermission) {
3294                mContext.enforceCallingOrSelfPermission(
3295                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3296            } else {
3297                try {
3298                    mContext.enforceCallingOrSelfPermission(
3299                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3300                } catch (SecurityException se) {
3301                    mContext.enforceCallingOrSelfPermission(
3302                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3303                }
3304            }
3305        }
3306    }
3307
3308    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3309        if (callingUid == Process.SHELL_UID) {
3310            if (userHandle >= 0
3311                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3312                throw new SecurityException("Shell does not have permission to access user "
3313                        + userHandle);
3314            } else if (userHandle < 0) {
3315                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3316                        + Debug.getCallers(3));
3317            }
3318        }
3319    }
3320
3321    private BasePermission findPermissionTreeLP(String permName) {
3322        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3323            if (permName.startsWith(bp.name) &&
3324                    permName.length() > bp.name.length() &&
3325                    permName.charAt(bp.name.length()) == '.') {
3326                return bp;
3327            }
3328        }
3329        return null;
3330    }
3331
3332    private BasePermission checkPermissionTreeLP(String permName) {
3333        if (permName != null) {
3334            BasePermission bp = findPermissionTreeLP(permName);
3335            if (bp != null) {
3336                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3337                    return bp;
3338                }
3339                throw new SecurityException("Calling uid "
3340                        + Binder.getCallingUid()
3341                        + " is not allowed to add to permission tree "
3342                        + bp.name + " owned by uid " + bp.uid);
3343            }
3344        }
3345        throw new SecurityException("No permission tree found for " + permName);
3346    }
3347
3348    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3349        if (s1 == null) {
3350            return s2 == null;
3351        }
3352        if (s2 == null) {
3353            return false;
3354        }
3355        if (s1.getClass() != s2.getClass()) {
3356            return false;
3357        }
3358        return s1.equals(s2);
3359    }
3360
3361    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3362        if (pi1.icon != pi2.icon) return false;
3363        if (pi1.logo != pi2.logo) return false;
3364        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3365        if (!compareStrings(pi1.name, pi2.name)) return false;
3366        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3367        // We'll take care of setting this one.
3368        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3369        // These are not currently stored in settings.
3370        //if (!compareStrings(pi1.group, pi2.group)) return false;
3371        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3372        //if (pi1.labelRes != pi2.labelRes) return false;
3373        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3374        return true;
3375    }
3376
3377    int permissionInfoFootprint(PermissionInfo info) {
3378        int size = info.name.length();
3379        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3380        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3381        return size;
3382    }
3383
3384    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3385        int size = 0;
3386        for (BasePermission perm : mSettings.mPermissions.values()) {
3387            if (perm.uid == tree.uid) {
3388                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3389            }
3390        }
3391        return size;
3392    }
3393
3394    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3395        // We calculate the max size of permissions defined by this uid and throw
3396        // if that plus the size of 'info' would exceed our stated maximum.
3397        if (tree.uid != Process.SYSTEM_UID) {
3398            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3399            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3400                throw new SecurityException("Permission tree size cap exceeded");
3401            }
3402        }
3403    }
3404
3405    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3406        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3407            throw new SecurityException("Label must be specified in permission");
3408        }
3409        BasePermission tree = checkPermissionTreeLP(info.name);
3410        BasePermission bp = mSettings.mPermissions.get(info.name);
3411        boolean added = bp == null;
3412        boolean changed = true;
3413        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3414        if (added) {
3415            enforcePermissionCapLocked(info, tree);
3416            bp = new BasePermission(info.name, tree.sourcePackage,
3417                    BasePermission.TYPE_DYNAMIC);
3418        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3419            throw new SecurityException(
3420                    "Not allowed to modify non-dynamic permission "
3421                    + info.name);
3422        } else {
3423            if (bp.protectionLevel == fixedLevel
3424                    && bp.perm.owner.equals(tree.perm.owner)
3425                    && bp.uid == tree.uid
3426                    && comparePermissionInfos(bp.perm.info, info)) {
3427                changed = false;
3428            }
3429        }
3430        bp.protectionLevel = fixedLevel;
3431        info = new PermissionInfo(info);
3432        info.protectionLevel = fixedLevel;
3433        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3434        bp.perm.info.packageName = tree.perm.info.packageName;
3435        bp.uid = tree.uid;
3436        if (added) {
3437            mSettings.mPermissions.put(info.name, bp);
3438        }
3439        if (changed) {
3440            if (!async) {
3441                mSettings.writeLPr();
3442            } else {
3443                scheduleWriteSettingsLocked();
3444            }
3445        }
3446        return added;
3447    }
3448
3449    @Override
3450    public boolean addPermission(PermissionInfo info) {
3451        synchronized (mPackages) {
3452            return addPermissionLocked(info, false);
3453        }
3454    }
3455
3456    @Override
3457    public boolean addPermissionAsync(PermissionInfo info) {
3458        synchronized (mPackages) {
3459            return addPermissionLocked(info, true);
3460        }
3461    }
3462
3463    @Override
3464    public void removePermission(String name) {
3465        synchronized (mPackages) {
3466            checkPermissionTreeLP(name);
3467            BasePermission bp = mSettings.mPermissions.get(name);
3468            if (bp != null) {
3469                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3470                    throw new SecurityException(
3471                            "Not allowed to modify non-dynamic permission "
3472                            + name);
3473                }
3474                mSettings.mPermissions.remove(name);
3475                mSettings.writeLPr();
3476            }
3477        }
3478    }
3479
3480    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3481            BasePermission bp) {
3482        int index = pkg.requestedPermissions.indexOf(bp.name);
3483        if (index == -1) {
3484            throw new SecurityException("Package " + pkg.packageName
3485                    + " has not requested permission " + bp.name);
3486        }
3487        if (!bp.isRuntime() && !bp.isDevelopment()) {
3488            throw new SecurityException("Permission " + bp.name
3489                    + " is not a changeable permission type");
3490        }
3491    }
3492
3493    @Override
3494    public void grantRuntimePermission(String packageName, String name, final int userId) {
3495        if (!sUserManager.exists(userId)) {
3496            Log.e(TAG, "No such user:" + userId);
3497            return;
3498        }
3499
3500        mContext.enforceCallingOrSelfPermission(
3501                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3502                "grantRuntimePermission");
3503
3504        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3505                "grantRuntimePermission");
3506
3507        final int uid;
3508        final SettingBase sb;
3509
3510        synchronized (mPackages) {
3511            final PackageParser.Package pkg = mPackages.get(packageName);
3512            if (pkg == null) {
3513                throw new IllegalArgumentException("Unknown package: " + packageName);
3514            }
3515
3516            final BasePermission bp = mSettings.mPermissions.get(name);
3517            if (bp == null) {
3518                throw new IllegalArgumentException("Unknown permission: " + name);
3519            }
3520
3521            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3522
3523            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3524            sb = (SettingBase) pkg.mExtras;
3525            if (sb == null) {
3526                throw new IllegalArgumentException("Unknown package: " + packageName);
3527            }
3528
3529            final PermissionsState permissionsState = sb.getPermissionsState();
3530
3531            final int flags = permissionsState.getPermissionFlags(name, userId);
3532            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3533                throw new SecurityException("Cannot grant system fixed permission: "
3534                        + name + " for package: " + packageName);
3535            }
3536
3537            if (bp.isDevelopment()) {
3538                // Development permissions must be handled specially, since they are not
3539                // normal runtime permissions.  For now they apply to all users.
3540                if (permissionsState.grantInstallPermission(bp) !=
3541                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3542                    scheduleWriteSettingsLocked();
3543                }
3544                return;
3545            }
3546
3547            final int result = permissionsState.grantRuntimePermission(bp, userId);
3548            switch (result) {
3549                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3550                    return;
3551                }
3552
3553                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3554                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3555                    mHandler.post(new Runnable() {
3556                        @Override
3557                        public void run() {
3558                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3559                        }
3560                    });
3561                } break;
3562            }
3563
3564            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3565
3566            // Not critical if that is lost - app has to request again.
3567            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3568        }
3569
3570        // Only need to do this if user is initialized. Otherwise it's a new user
3571        // and there are no processes running as the user yet and there's no need
3572        // to make an expensive call to remount processes for the changed permissions.
3573        if (READ_EXTERNAL_STORAGE.equals(name)
3574                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3575            final long token = Binder.clearCallingIdentity();
3576            try {
3577                if (sUserManager.isInitialized(userId)) {
3578                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3579                            MountServiceInternal.class);
3580                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3581                }
3582            } finally {
3583                Binder.restoreCallingIdentity(token);
3584            }
3585        }
3586    }
3587
3588    @Override
3589    public void revokeRuntimePermission(String packageName, String name, int userId) {
3590        if (!sUserManager.exists(userId)) {
3591            Log.e(TAG, "No such user:" + userId);
3592            return;
3593        }
3594
3595        mContext.enforceCallingOrSelfPermission(
3596                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3597                "revokeRuntimePermission");
3598
3599        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3600                "revokeRuntimePermission");
3601
3602        final int appId;
3603
3604        synchronized (mPackages) {
3605            final PackageParser.Package pkg = mPackages.get(packageName);
3606            if (pkg == null) {
3607                throw new IllegalArgumentException("Unknown package: " + packageName);
3608            }
3609
3610            final BasePermission bp = mSettings.mPermissions.get(name);
3611            if (bp == null) {
3612                throw new IllegalArgumentException("Unknown permission: " + name);
3613            }
3614
3615            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3616
3617            SettingBase sb = (SettingBase) pkg.mExtras;
3618            if (sb == null) {
3619                throw new IllegalArgumentException("Unknown package: " + packageName);
3620            }
3621
3622            final PermissionsState permissionsState = sb.getPermissionsState();
3623
3624            final int flags = permissionsState.getPermissionFlags(name, userId);
3625            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3626                throw new SecurityException("Cannot revoke system fixed permission: "
3627                        + name + " for package: " + packageName);
3628            }
3629
3630            if (bp.isDevelopment()) {
3631                // Development permissions must be handled specially, since they are not
3632                // normal runtime permissions.  For now they apply to all users.
3633                if (permissionsState.revokeInstallPermission(bp) !=
3634                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3635                    scheduleWriteSettingsLocked();
3636                }
3637                return;
3638            }
3639
3640            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3641                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3642                return;
3643            }
3644
3645            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3646
3647            // Critical, after this call app should never have the permission.
3648            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3649
3650            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3651        }
3652
3653        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3654    }
3655
3656    @Override
3657    public void resetRuntimePermissions() {
3658        mContext.enforceCallingOrSelfPermission(
3659                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3660                "revokeRuntimePermission");
3661
3662        int callingUid = Binder.getCallingUid();
3663        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3664            mContext.enforceCallingOrSelfPermission(
3665                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3666                    "resetRuntimePermissions");
3667        }
3668
3669        synchronized (mPackages) {
3670            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3671            for (int userId : UserManagerService.getInstance().getUserIds()) {
3672                final int packageCount = mPackages.size();
3673                for (int i = 0; i < packageCount; i++) {
3674                    PackageParser.Package pkg = mPackages.valueAt(i);
3675                    if (!(pkg.mExtras instanceof PackageSetting)) {
3676                        continue;
3677                    }
3678                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3679                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3680                }
3681            }
3682        }
3683    }
3684
3685    @Override
3686    public int getPermissionFlags(String name, String packageName, int userId) {
3687        if (!sUserManager.exists(userId)) {
3688            return 0;
3689        }
3690
3691        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3692
3693        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3694                "getPermissionFlags");
3695
3696        synchronized (mPackages) {
3697            final PackageParser.Package pkg = mPackages.get(packageName);
3698            if (pkg == null) {
3699                throw new IllegalArgumentException("Unknown package: " + packageName);
3700            }
3701
3702            final BasePermission bp = mSettings.mPermissions.get(name);
3703            if (bp == null) {
3704                throw new IllegalArgumentException("Unknown permission: " + name);
3705            }
3706
3707            SettingBase sb = (SettingBase) pkg.mExtras;
3708            if (sb == null) {
3709                throw new IllegalArgumentException("Unknown package: " + packageName);
3710            }
3711
3712            PermissionsState permissionsState = sb.getPermissionsState();
3713            return permissionsState.getPermissionFlags(name, userId);
3714        }
3715    }
3716
3717    @Override
3718    public void updatePermissionFlags(String name, String packageName, int flagMask,
3719            int flagValues, int userId) {
3720        if (!sUserManager.exists(userId)) {
3721            return;
3722        }
3723
3724        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3725
3726        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3727                "updatePermissionFlags");
3728
3729        // Only the system can change these flags and nothing else.
3730        if (getCallingUid() != Process.SYSTEM_UID) {
3731            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3732            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3733            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3734            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3735        }
3736
3737        synchronized (mPackages) {
3738            final PackageParser.Package pkg = mPackages.get(packageName);
3739            if (pkg == null) {
3740                throw new IllegalArgumentException("Unknown package: " + packageName);
3741            }
3742
3743            final BasePermission bp = mSettings.mPermissions.get(name);
3744            if (bp == null) {
3745                throw new IllegalArgumentException("Unknown permission: " + name);
3746            }
3747
3748            SettingBase sb = (SettingBase) pkg.mExtras;
3749            if (sb == null) {
3750                throw new IllegalArgumentException("Unknown package: " + packageName);
3751            }
3752
3753            PermissionsState permissionsState = sb.getPermissionsState();
3754
3755            // Only the package manager can change flags for system component permissions.
3756            final int flags = permissionsState.getPermissionFlags(bp.name, userId);
3757            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3758                return;
3759            }
3760
3761            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3762
3763            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3764                // Install and runtime permissions are stored in different places,
3765                // so figure out what permission changed and persist the change.
3766                if (permissionsState.getInstallPermissionState(name) != null) {
3767                    scheduleWriteSettingsLocked();
3768                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3769                        || hadState) {
3770                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3771                }
3772            }
3773        }
3774    }
3775
3776    /**
3777     * Update the permission flags for all packages and runtime permissions of a user in order
3778     * to allow device or profile owner to remove POLICY_FIXED.
3779     */
3780    @Override
3781    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3782        if (!sUserManager.exists(userId)) {
3783            return;
3784        }
3785
3786        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3787
3788        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3789                "updatePermissionFlagsForAllApps");
3790
3791        // Only the system can change system fixed flags.
3792        if (getCallingUid() != Process.SYSTEM_UID) {
3793            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3794            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3795        }
3796
3797        synchronized (mPackages) {
3798            boolean changed = false;
3799            final int packageCount = mPackages.size();
3800            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3801                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3802                SettingBase sb = (SettingBase) pkg.mExtras;
3803                if (sb == null) {
3804                    continue;
3805                }
3806                PermissionsState permissionsState = sb.getPermissionsState();
3807                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
3808                        userId, flagMask, flagValues);
3809            }
3810            if (changed) {
3811                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3812            }
3813        }
3814    }
3815
3816    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
3817        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
3818                != PackageManager.PERMISSION_GRANTED
3819            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
3820                != PackageManager.PERMISSION_GRANTED) {
3821            throw new SecurityException(message + " requires "
3822                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
3823                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
3824        }
3825    }
3826
3827    @Override
3828    public boolean shouldShowRequestPermissionRationale(String permissionName,
3829            String packageName, int userId) {
3830        if (UserHandle.getCallingUserId() != userId) {
3831            mContext.enforceCallingPermission(
3832                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3833                    "canShowRequestPermissionRationale for user " + userId);
3834        }
3835
3836        final int uid = getPackageUid(packageName, userId);
3837        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
3838            return false;
3839        }
3840
3841        if (checkPermission(permissionName, packageName, userId)
3842                == PackageManager.PERMISSION_GRANTED) {
3843            return false;
3844        }
3845
3846        final int flags;
3847
3848        final long identity = Binder.clearCallingIdentity();
3849        try {
3850            flags = getPermissionFlags(permissionName,
3851                    packageName, userId);
3852        } finally {
3853            Binder.restoreCallingIdentity(identity);
3854        }
3855
3856        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
3857                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
3858                | PackageManager.FLAG_PERMISSION_USER_FIXED;
3859
3860        if ((flags & fixedFlags) != 0) {
3861            return false;
3862        }
3863
3864        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
3865    }
3866
3867    @Override
3868    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3869        mContext.enforceCallingOrSelfPermission(
3870                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
3871                "addOnPermissionsChangeListener");
3872
3873        synchronized (mPackages) {
3874            mOnPermissionChangeListeners.addListenerLocked(listener);
3875        }
3876    }
3877
3878    @Override
3879    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
3880        synchronized (mPackages) {
3881            mOnPermissionChangeListeners.removeListenerLocked(listener);
3882        }
3883    }
3884
3885    @Override
3886    public boolean isProtectedBroadcast(String actionName) {
3887        synchronized (mPackages) {
3888            return mProtectedBroadcasts.contains(actionName);
3889        }
3890    }
3891
3892    @Override
3893    public int checkSignatures(String pkg1, String pkg2) {
3894        synchronized (mPackages) {
3895            final PackageParser.Package p1 = mPackages.get(pkg1);
3896            final PackageParser.Package p2 = mPackages.get(pkg2);
3897            if (p1 == null || p1.mExtras == null
3898                    || p2 == null || p2.mExtras == null) {
3899                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3900            }
3901            return compareSignatures(p1.mSignatures, p2.mSignatures);
3902        }
3903    }
3904
3905    @Override
3906    public int checkUidSignatures(int uid1, int uid2) {
3907        // Map to base uids.
3908        uid1 = UserHandle.getAppId(uid1);
3909        uid2 = UserHandle.getAppId(uid2);
3910        // reader
3911        synchronized (mPackages) {
3912            Signature[] s1;
3913            Signature[] s2;
3914            Object obj = mSettings.getUserIdLPr(uid1);
3915            if (obj != null) {
3916                if (obj instanceof SharedUserSetting) {
3917                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3918                } else if (obj instanceof PackageSetting) {
3919                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3920                } else {
3921                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3922                }
3923            } else {
3924                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3925            }
3926            obj = mSettings.getUserIdLPr(uid2);
3927            if (obj != null) {
3928                if (obj instanceof SharedUserSetting) {
3929                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3930                } else if (obj instanceof PackageSetting) {
3931                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3932                } else {
3933                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3934                }
3935            } else {
3936                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3937            }
3938            return compareSignatures(s1, s2);
3939        }
3940    }
3941
3942    private void killUid(int appId, int userId, String reason) {
3943        final long identity = Binder.clearCallingIdentity();
3944        try {
3945            IActivityManager am = ActivityManagerNative.getDefault();
3946            if (am != null) {
3947                try {
3948                    am.killUid(appId, userId, reason);
3949                } catch (RemoteException e) {
3950                    /* ignore - same process */
3951                }
3952            }
3953        } finally {
3954            Binder.restoreCallingIdentity(identity);
3955        }
3956    }
3957
3958    /**
3959     * Compares two sets of signatures. Returns:
3960     * <br />
3961     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3962     * <br />
3963     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3964     * <br />
3965     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3966     * <br />
3967     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3968     * <br />
3969     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3970     */
3971    static int compareSignatures(Signature[] s1, Signature[] s2) {
3972        if (s1 == null) {
3973            return s2 == null
3974                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3975                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3976        }
3977
3978        if (s2 == null) {
3979            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3980        }
3981
3982        if (s1.length != s2.length) {
3983            return PackageManager.SIGNATURE_NO_MATCH;
3984        }
3985
3986        // Since both signature sets are of size 1, we can compare without HashSets.
3987        if (s1.length == 1) {
3988            return s1[0].equals(s2[0]) ?
3989                    PackageManager.SIGNATURE_MATCH :
3990                    PackageManager.SIGNATURE_NO_MATCH;
3991        }
3992
3993        ArraySet<Signature> set1 = new ArraySet<Signature>();
3994        for (Signature sig : s1) {
3995            set1.add(sig);
3996        }
3997        ArraySet<Signature> set2 = new ArraySet<Signature>();
3998        for (Signature sig : s2) {
3999            set2.add(sig);
4000        }
4001        // Make sure s2 contains all signatures in s1.
4002        if (set1.equals(set2)) {
4003            return PackageManager.SIGNATURE_MATCH;
4004        }
4005        return PackageManager.SIGNATURE_NO_MATCH;
4006    }
4007
4008    /**
4009     * If the database version for this type of package (internal storage or
4010     * external storage) is less than the version where package signatures
4011     * were updated, return true.
4012     */
4013    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4014        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4015        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4016    }
4017
4018    /**
4019     * Used for backward compatibility to make sure any packages with
4020     * certificate chains get upgraded to the new style. {@code existingSigs}
4021     * will be in the old format (since they were stored on disk from before the
4022     * system upgrade) and {@code scannedSigs} will be in the newer format.
4023     */
4024    private int compareSignaturesCompat(PackageSignatures existingSigs,
4025            PackageParser.Package scannedPkg) {
4026        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4027            return PackageManager.SIGNATURE_NO_MATCH;
4028        }
4029
4030        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4031        for (Signature sig : existingSigs.mSignatures) {
4032            existingSet.add(sig);
4033        }
4034        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4035        for (Signature sig : scannedPkg.mSignatures) {
4036            try {
4037                Signature[] chainSignatures = sig.getChainSignatures();
4038                for (Signature chainSig : chainSignatures) {
4039                    scannedCompatSet.add(chainSig);
4040                }
4041            } catch (CertificateEncodingException e) {
4042                scannedCompatSet.add(sig);
4043            }
4044        }
4045        /*
4046         * Make sure the expanded scanned set contains all signatures in the
4047         * existing one.
4048         */
4049        if (scannedCompatSet.equals(existingSet)) {
4050            // Migrate the old signatures to the new scheme.
4051            existingSigs.assignSignatures(scannedPkg.mSignatures);
4052            // The new KeySets will be re-added later in the scanning process.
4053            synchronized (mPackages) {
4054                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4055            }
4056            return PackageManager.SIGNATURE_MATCH;
4057        }
4058        return PackageManager.SIGNATURE_NO_MATCH;
4059    }
4060
4061    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4062        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4063        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4064    }
4065
4066    private int compareSignaturesRecover(PackageSignatures existingSigs,
4067            PackageParser.Package scannedPkg) {
4068        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4069            return PackageManager.SIGNATURE_NO_MATCH;
4070        }
4071
4072        String msg = null;
4073        try {
4074            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4075                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4076                        + scannedPkg.packageName);
4077                return PackageManager.SIGNATURE_MATCH;
4078            }
4079        } catch (CertificateException e) {
4080            msg = e.getMessage();
4081        }
4082
4083        logCriticalInfo(Log.INFO,
4084                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4085        return PackageManager.SIGNATURE_NO_MATCH;
4086    }
4087
4088    @Override
4089    public String[] getPackagesForUid(int uid) {
4090        uid = UserHandle.getAppId(uid);
4091        // reader
4092        synchronized (mPackages) {
4093            Object obj = mSettings.getUserIdLPr(uid);
4094            if (obj instanceof SharedUserSetting) {
4095                final SharedUserSetting sus = (SharedUserSetting) obj;
4096                final int N = sus.packages.size();
4097                final String[] res = new String[N];
4098                final Iterator<PackageSetting> it = sus.packages.iterator();
4099                int i = 0;
4100                while (it.hasNext()) {
4101                    res[i++] = it.next().name;
4102                }
4103                return res;
4104            } else if (obj instanceof PackageSetting) {
4105                final PackageSetting ps = (PackageSetting) obj;
4106                return new String[] { ps.name };
4107            }
4108        }
4109        return null;
4110    }
4111
4112    @Override
4113    public String getNameForUid(int uid) {
4114        // reader
4115        synchronized (mPackages) {
4116            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4117            if (obj instanceof SharedUserSetting) {
4118                final SharedUserSetting sus = (SharedUserSetting) obj;
4119                return sus.name + ":" + sus.userId;
4120            } else if (obj instanceof PackageSetting) {
4121                final PackageSetting ps = (PackageSetting) obj;
4122                return ps.name;
4123            }
4124        }
4125        return null;
4126    }
4127
4128    @Override
4129    public int getUidForSharedUser(String sharedUserName) {
4130        if(sharedUserName == null) {
4131            return -1;
4132        }
4133        // reader
4134        synchronized (mPackages) {
4135            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4136            if (suid == null) {
4137                return -1;
4138            }
4139            return suid.userId;
4140        }
4141    }
4142
4143    @Override
4144    public int getFlagsForUid(int uid) {
4145        synchronized (mPackages) {
4146            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4147            if (obj instanceof SharedUserSetting) {
4148                final SharedUserSetting sus = (SharedUserSetting) obj;
4149                return sus.pkgFlags;
4150            } else if (obj instanceof PackageSetting) {
4151                final PackageSetting ps = (PackageSetting) obj;
4152                return ps.pkgFlags;
4153            }
4154        }
4155        return 0;
4156    }
4157
4158    @Override
4159    public int getPrivateFlagsForUid(int uid) {
4160        synchronized (mPackages) {
4161            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4162            if (obj instanceof SharedUserSetting) {
4163                final SharedUserSetting sus = (SharedUserSetting) obj;
4164                return sus.pkgPrivateFlags;
4165            } else if (obj instanceof PackageSetting) {
4166                final PackageSetting ps = (PackageSetting) obj;
4167                return ps.pkgPrivateFlags;
4168            }
4169        }
4170        return 0;
4171    }
4172
4173    @Override
4174    public boolean isUidPrivileged(int uid) {
4175        uid = UserHandle.getAppId(uid);
4176        // reader
4177        synchronized (mPackages) {
4178            Object obj = mSettings.getUserIdLPr(uid);
4179            if (obj instanceof SharedUserSetting) {
4180                final SharedUserSetting sus = (SharedUserSetting) obj;
4181                final Iterator<PackageSetting> it = sus.packages.iterator();
4182                while (it.hasNext()) {
4183                    if (it.next().isPrivileged()) {
4184                        return true;
4185                    }
4186                }
4187            } else if (obj instanceof PackageSetting) {
4188                final PackageSetting ps = (PackageSetting) obj;
4189                return ps.isPrivileged();
4190            }
4191        }
4192        return false;
4193    }
4194
4195    @Override
4196    public String[] getAppOpPermissionPackages(String permissionName) {
4197        synchronized (mPackages) {
4198            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4199            if (pkgs == null) {
4200                return null;
4201            }
4202            return pkgs.toArray(new String[pkgs.size()]);
4203        }
4204    }
4205
4206    @Override
4207    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4208            int flags, int userId) {
4209        if (!sUserManager.exists(userId)) return null;
4210        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4211        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4212        return chooseBestActivity(intent, resolvedType, flags, query, userId);
4213    }
4214
4215    @Override
4216    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4217            IntentFilter filter, int match, ComponentName activity) {
4218        final int userId = UserHandle.getCallingUserId();
4219        if (DEBUG_PREFERRED) {
4220            Log.v(TAG, "setLastChosenActivity intent=" + intent
4221                + " resolvedType=" + resolvedType
4222                + " flags=" + flags
4223                + " filter=" + filter
4224                + " match=" + match
4225                + " activity=" + activity);
4226            filter.dump(new PrintStreamPrinter(System.out), "    ");
4227        }
4228        intent.setComponent(null);
4229        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4230        // Find any earlier preferred or last chosen entries and nuke them
4231        findPreferredActivity(intent, resolvedType,
4232                flags, query, 0, false, true, false, userId);
4233        // Add the new activity as the last chosen for this filter
4234        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4235                "Setting last chosen");
4236    }
4237
4238    @Override
4239    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4240        final int userId = UserHandle.getCallingUserId();
4241        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4242        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4243        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4244                false, false, false, userId);
4245    }
4246
4247    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4248            int flags, List<ResolveInfo> query, int userId) {
4249        if (query != null) {
4250            final int N = query.size();
4251            if (N == 1) {
4252                return query.get(0);
4253            } else if (N > 1) {
4254                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4255                // If there is more than one activity with the same priority,
4256                // then let the user decide between them.
4257                ResolveInfo r0 = query.get(0);
4258                ResolveInfo r1 = query.get(1);
4259                if (DEBUG_INTENT_MATCHING || debug) {
4260                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4261                            + r1.activityInfo.name + "=" + r1.priority);
4262                }
4263                // If the first activity has a higher priority, or a different
4264                // default, then it is always desireable to pick it.
4265                if (r0.priority != r1.priority
4266                        || r0.preferredOrder != r1.preferredOrder
4267                        || r0.isDefault != r1.isDefault) {
4268                    return query.get(0);
4269                }
4270                // If we have saved a preference for a preferred activity for
4271                // this Intent, use that.
4272                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4273                        flags, query, r0.priority, true, false, debug, userId);
4274                if (ri != null) {
4275                    return ri;
4276                }
4277                ri = new ResolveInfo(mResolveInfo);
4278                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4279                ri.activityInfo.applicationInfo = new ApplicationInfo(
4280                        ri.activityInfo.applicationInfo);
4281                if (userId != 0) {
4282                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4283                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4284                }
4285                // Make sure that the resolver is displayable in car mode
4286                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4287                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4288                return ri;
4289            }
4290        }
4291        return null;
4292    }
4293
4294    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4295            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4296        final int N = query.size();
4297        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4298                .get(userId);
4299        // Get the list of persistent preferred activities that handle the intent
4300        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4301        List<PersistentPreferredActivity> pprefs = ppir != null
4302                ? ppir.queryIntent(intent, resolvedType,
4303                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4304                : null;
4305        if (pprefs != null && pprefs.size() > 0) {
4306            final int M = pprefs.size();
4307            for (int i=0; i<M; i++) {
4308                final PersistentPreferredActivity ppa = pprefs.get(i);
4309                if (DEBUG_PREFERRED || debug) {
4310                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4311                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4312                            + "\n  component=" + ppa.mComponent);
4313                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4314                }
4315                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4316                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4317                if (DEBUG_PREFERRED || debug) {
4318                    Slog.v(TAG, "Found persistent preferred activity:");
4319                    if (ai != null) {
4320                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4321                    } else {
4322                        Slog.v(TAG, "  null");
4323                    }
4324                }
4325                if (ai == null) {
4326                    // This previously registered persistent preferred activity
4327                    // component is no longer known. Ignore it and do NOT remove it.
4328                    continue;
4329                }
4330                for (int j=0; j<N; j++) {
4331                    final ResolveInfo ri = query.get(j);
4332                    if (!ri.activityInfo.applicationInfo.packageName
4333                            .equals(ai.applicationInfo.packageName)) {
4334                        continue;
4335                    }
4336                    if (!ri.activityInfo.name.equals(ai.name)) {
4337                        continue;
4338                    }
4339                    //  Found a persistent preference that can handle the intent.
4340                    if (DEBUG_PREFERRED || debug) {
4341                        Slog.v(TAG, "Returning persistent preferred activity: " +
4342                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4343                    }
4344                    return ri;
4345                }
4346            }
4347        }
4348        return null;
4349    }
4350
4351    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4352            List<ResolveInfo> query, int priority, boolean always,
4353            boolean removeMatches, boolean debug, int userId) {
4354        if (!sUserManager.exists(userId)) return null;
4355        // writer
4356        synchronized (mPackages) {
4357            if (intent.getSelector() != null) {
4358                intent = intent.getSelector();
4359            }
4360            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4361
4362            // Try to find a matching persistent preferred activity.
4363            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4364                    debug, userId);
4365
4366            // If a persistent preferred activity matched, use it.
4367            if (pri != null) {
4368                return pri;
4369            }
4370
4371            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4372            // Get the list of preferred activities that handle the intent
4373            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4374            List<PreferredActivity> prefs = pir != null
4375                    ? pir.queryIntent(intent, resolvedType,
4376                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4377                    : null;
4378            if (prefs != null && prefs.size() > 0) {
4379                boolean changed = false;
4380                try {
4381                    // First figure out how good the original match set is.
4382                    // We will only allow preferred activities that came
4383                    // from the same match quality.
4384                    int match = 0;
4385
4386                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4387
4388                    final int N = query.size();
4389                    for (int j=0; j<N; j++) {
4390                        final ResolveInfo ri = query.get(j);
4391                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4392                                + ": 0x" + Integer.toHexString(match));
4393                        if (ri.match > match) {
4394                            match = ri.match;
4395                        }
4396                    }
4397
4398                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4399                            + Integer.toHexString(match));
4400
4401                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4402                    final int M = prefs.size();
4403                    for (int i=0; i<M; i++) {
4404                        final PreferredActivity pa = prefs.get(i);
4405                        if (DEBUG_PREFERRED || debug) {
4406                            Slog.v(TAG, "Checking PreferredActivity ds="
4407                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4408                                    + "\n  component=" + pa.mPref.mComponent);
4409                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4410                        }
4411                        if (pa.mPref.mMatch != match) {
4412                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4413                                    + Integer.toHexString(pa.mPref.mMatch));
4414                            continue;
4415                        }
4416                        // If it's not an "always" type preferred activity and that's what we're
4417                        // looking for, skip it.
4418                        if (always && !pa.mPref.mAlways) {
4419                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4420                            continue;
4421                        }
4422                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4423                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
4424                        if (DEBUG_PREFERRED || debug) {
4425                            Slog.v(TAG, "Found preferred activity:");
4426                            if (ai != null) {
4427                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4428                            } else {
4429                                Slog.v(TAG, "  null");
4430                            }
4431                        }
4432                        if (ai == null) {
4433                            // This previously registered preferred activity
4434                            // component is no longer known.  Most likely an update
4435                            // to the app was installed and in the new version this
4436                            // component no longer exists.  Clean it up by removing
4437                            // it from the preferred activities list, and skip it.
4438                            Slog.w(TAG, "Removing dangling preferred activity: "
4439                                    + pa.mPref.mComponent);
4440                            pir.removeFilter(pa);
4441                            changed = true;
4442                            continue;
4443                        }
4444                        for (int j=0; j<N; j++) {
4445                            final ResolveInfo ri = query.get(j);
4446                            if (!ri.activityInfo.applicationInfo.packageName
4447                                    .equals(ai.applicationInfo.packageName)) {
4448                                continue;
4449                            }
4450                            if (!ri.activityInfo.name.equals(ai.name)) {
4451                                continue;
4452                            }
4453
4454                            if (removeMatches) {
4455                                pir.removeFilter(pa);
4456                                changed = true;
4457                                if (DEBUG_PREFERRED) {
4458                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4459                                }
4460                                break;
4461                            }
4462
4463                            // Okay we found a previously set preferred or last chosen app.
4464                            // If the result set is different from when this
4465                            // was created, we need to clear it and re-ask the
4466                            // user their preference, if we're looking for an "always" type entry.
4467                            if (always && !pa.mPref.sameSet(query)) {
4468                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4469                                        + intent + " type " + resolvedType);
4470                                if (DEBUG_PREFERRED) {
4471                                    Slog.v(TAG, "Removing preferred activity since set changed "
4472                                            + pa.mPref.mComponent);
4473                                }
4474                                pir.removeFilter(pa);
4475                                // Re-add the filter as a "last chosen" entry (!always)
4476                                PreferredActivity lastChosen = new PreferredActivity(
4477                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4478                                pir.addFilter(lastChosen);
4479                                changed = true;
4480                                return null;
4481                            }
4482
4483                            // Yay! Either the set matched or we're looking for the last chosen
4484                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4485                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4486                            return ri;
4487                        }
4488                    }
4489                } finally {
4490                    if (changed) {
4491                        if (DEBUG_PREFERRED) {
4492                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4493                        }
4494                        scheduleWritePackageRestrictionsLocked(userId);
4495                    }
4496                }
4497            }
4498        }
4499        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4500        return null;
4501    }
4502
4503    /*
4504     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4505     */
4506    @Override
4507    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4508            int targetUserId) {
4509        mContext.enforceCallingOrSelfPermission(
4510                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4511        List<CrossProfileIntentFilter> matches =
4512                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4513        if (matches != null) {
4514            int size = matches.size();
4515            for (int i = 0; i < size; i++) {
4516                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4517            }
4518        }
4519        if (hasWebURI(intent)) {
4520            // cross-profile app linking works only towards the parent.
4521            final UserInfo parent = getProfileParent(sourceUserId);
4522            synchronized(mPackages) {
4523                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4524                        intent, resolvedType, 0, sourceUserId, parent.id);
4525                return xpDomainInfo != null;
4526            }
4527        }
4528        return false;
4529    }
4530
4531    private UserInfo getProfileParent(int userId) {
4532        final long identity = Binder.clearCallingIdentity();
4533        try {
4534            return sUserManager.getProfileParent(userId);
4535        } finally {
4536            Binder.restoreCallingIdentity(identity);
4537        }
4538    }
4539
4540    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4541            String resolvedType, int userId) {
4542        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4543        if (resolver != null) {
4544            return resolver.queryIntent(intent, resolvedType, false, userId);
4545        }
4546        return null;
4547    }
4548
4549    @Override
4550    public List<ResolveInfo> queryIntentActivities(Intent intent,
4551            String resolvedType, int flags, int userId) {
4552        if (!sUserManager.exists(userId)) return Collections.emptyList();
4553        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4554        ComponentName comp = intent.getComponent();
4555        if (comp == null) {
4556            if (intent.getSelector() != null) {
4557                intent = intent.getSelector();
4558                comp = intent.getComponent();
4559            }
4560        }
4561
4562        if (comp != null) {
4563            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4564            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4565            if (ai != null) {
4566                final ResolveInfo ri = new ResolveInfo();
4567                ri.activityInfo = ai;
4568                list.add(ri);
4569            }
4570            return list;
4571        }
4572
4573        // reader
4574        synchronized (mPackages) {
4575            final String pkgName = intent.getPackage();
4576            if (pkgName == null) {
4577                List<CrossProfileIntentFilter> matchingFilters =
4578                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4579                // Check for results that need to skip the current profile.
4580                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4581                        resolvedType, flags, userId);
4582                if (xpResolveInfo != null) {
4583                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4584                    result.add(xpResolveInfo);
4585                    return filterIfNotSystemUser(result, userId);
4586                }
4587
4588                // Check for results in the current profile.
4589                List<ResolveInfo> result = mActivities.queryIntent(
4590                        intent, resolvedType, flags, userId);
4591
4592                // Check for cross profile results.
4593                xpResolveInfo = queryCrossProfileIntents(
4594                        matchingFilters, intent, resolvedType, flags, userId);
4595                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4596                    result.add(xpResolveInfo);
4597                    Collections.sort(result, mResolvePrioritySorter);
4598                }
4599                result = filterIfNotSystemUser(result, userId);
4600                if (hasWebURI(intent)) {
4601                    CrossProfileDomainInfo xpDomainInfo = null;
4602                    final UserInfo parent = getProfileParent(userId);
4603                    if (parent != null) {
4604                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4605                                flags, userId, parent.id);
4606                    }
4607                    if (xpDomainInfo != null) {
4608                        if (xpResolveInfo != null) {
4609                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4610                            // in the result.
4611                            result.remove(xpResolveInfo);
4612                        }
4613                        if (result.size() == 0) {
4614                            result.add(xpDomainInfo.resolveInfo);
4615                            return result;
4616                        }
4617                    } else if (result.size() <= 1) {
4618                        return result;
4619                    }
4620                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4621                            xpDomainInfo, userId);
4622                    Collections.sort(result, mResolvePrioritySorter);
4623                }
4624                return result;
4625            }
4626            final PackageParser.Package pkg = mPackages.get(pkgName);
4627            if (pkg != null) {
4628                return filterIfNotSystemUser(
4629                        mActivities.queryIntentForPackage(
4630                                intent, resolvedType, flags, pkg.activities, userId),
4631                        userId);
4632            }
4633            return new ArrayList<ResolveInfo>();
4634        }
4635    }
4636
4637    private static class CrossProfileDomainInfo {
4638        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4639        ResolveInfo resolveInfo;
4640        /* Best domain verification status of the activities found in the other profile */
4641        int bestDomainVerificationStatus;
4642    }
4643
4644    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4645            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4646        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4647                sourceUserId)) {
4648            return null;
4649        }
4650        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4651                resolvedType, flags, parentUserId);
4652
4653        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4654            return null;
4655        }
4656        CrossProfileDomainInfo result = null;
4657        int size = resultTargetUser.size();
4658        for (int i = 0; i < size; i++) {
4659            ResolveInfo riTargetUser = resultTargetUser.get(i);
4660            // Intent filter verification is only for filters that specify a host. So don't return
4661            // those that handle all web uris.
4662            if (riTargetUser.handleAllWebDataURI) {
4663                continue;
4664            }
4665            String packageName = riTargetUser.activityInfo.packageName;
4666            PackageSetting ps = mSettings.mPackages.get(packageName);
4667            if (ps == null) {
4668                continue;
4669            }
4670            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4671            int status = (int)(verificationState >> 32);
4672            if (result == null) {
4673                result = new CrossProfileDomainInfo();
4674                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
4675                        sourceUserId, parentUserId);
4676                result.bestDomainVerificationStatus = status;
4677            } else {
4678                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
4679                        result.bestDomainVerificationStatus);
4680            }
4681        }
4682        // Don't consider matches with status NEVER across profiles.
4683        if (result != null && result.bestDomainVerificationStatus
4684                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4685            return null;
4686        }
4687        return result;
4688    }
4689
4690    /**
4691     * Verification statuses are ordered from the worse to the best, except for
4692     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
4693     */
4694    private int bestDomainVerificationStatus(int status1, int status2) {
4695        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4696            return status2;
4697        }
4698        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4699            return status1;
4700        }
4701        return (int) MathUtils.max(status1, status2);
4702    }
4703
4704    private boolean isUserEnabled(int userId) {
4705        long callingId = Binder.clearCallingIdentity();
4706        try {
4707            UserInfo userInfo = sUserManager.getUserInfo(userId);
4708            return userInfo != null && userInfo.isEnabled();
4709        } finally {
4710            Binder.restoreCallingIdentity(callingId);
4711        }
4712    }
4713
4714    /**
4715     * Filter out activities with systemUserOnly flag set, when current user is not System.
4716     *
4717     * @return filtered list
4718     */
4719    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
4720        if (userId == UserHandle.USER_SYSTEM) {
4721            return resolveInfos;
4722        }
4723        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4724            ResolveInfo info = resolveInfos.get(i);
4725            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
4726                resolveInfos.remove(i);
4727            }
4728        }
4729        return resolveInfos;
4730    }
4731
4732    private static boolean hasWebURI(Intent intent) {
4733        if (intent.getData() == null) {
4734            return false;
4735        }
4736        final String scheme = intent.getScheme();
4737        if (TextUtils.isEmpty(scheme)) {
4738            return false;
4739        }
4740        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4741    }
4742
4743    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
4744            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
4745            int userId) {
4746        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
4747
4748        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4749            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
4750                    candidates.size());
4751        }
4752
4753        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4754        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
4755        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4756        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
4757        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4758        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4759
4760        synchronized (mPackages) {
4761            final int count = candidates.size();
4762            // First, try to use linked apps. Partition the candidates into four lists:
4763            // one for the final results, one for the "do not use ever", one for "undefined status"
4764            // and finally one for "browser app type".
4765            for (int n=0; n<count; n++) {
4766                ResolveInfo info = candidates.get(n);
4767                String packageName = info.activityInfo.packageName;
4768                PackageSetting ps = mSettings.mPackages.get(packageName);
4769                if (ps != null) {
4770                    // Add to the special match all list (Browser use case)
4771                    if (info.handleAllWebDataURI) {
4772                        matchAllList.add(info);
4773                        continue;
4774                    }
4775                    // Try to get the status from User settings first
4776                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4777                    int status = (int)(packedStatus >> 32);
4778                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
4779                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4780                        if (DEBUG_DOMAIN_VERIFICATION) {
4781                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
4782                                    + " : linkgen=" + linkGeneration);
4783                        }
4784                        // Use link-enabled generation as preferredOrder, i.e.
4785                        // prefer newly-enabled over earlier-enabled.
4786                        info.preferredOrder = linkGeneration;
4787                        alwaysList.add(info);
4788                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4789                        if (DEBUG_DOMAIN_VERIFICATION) {
4790                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
4791                        }
4792                        neverList.add(info);
4793                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4794                        if (DEBUG_DOMAIN_VERIFICATION) {
4795                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
4796                        }
4797                        alwaysAskList.add(info);
4798                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
4799                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
4800                        if (DEBUG_DOMAIN_VERIFICATION) {
4801                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
4802                        }
4803                        undefinedList.add(info);
4804                    }
4805                }
4806            }
4807
4808            // We'll want to include browser possibilities in a few cases
4809            boolean includeBrowser = false;
4810
4811            // First try to add the "always" resolution(s) for the current user, if any
4812            if (alwaysList.size() > 0) {
4813                result.addAll(alwaysList);
4814            // if there is an "always" for the parent user, add it.
4815            } else if (xpDomainInfo != null && xpDomainInfo.bestDomainVerificationStatus
4816                    == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4817                result.add(xpDomainInfo.resolveInfo);
4818            } else {
4819                // Add all undefined apps as we want them to appear in the disambiguation dialog.
4820                result.addAll(undefinedList);
4821                if (xpDomainInfo != null && (
4822                        xpDomainInfo.bestDomainVerificationStatus
4823                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
4824                        || xpDomainInfo.bestDomainVerificationStatus
4825                        == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK)) {
4826                    result.add(xpDomainInfo.resolveInfo);
4827                }
4828                includeBrowser = true;
4829            }
4830
4831            // The presence of any 'always ask' alternatives means we'll also offer browsers.
4832            // If there were 'always' entries their preferred order has been set, so we also
4833            // back that off to make the alternatives equivalent
4834            if (alwaysAskList.size() > 0) {
4835                for (ResolveInfo i : result) {
4836                    i.preferredOrder = 0;
4837                }
4838                result.addAll(alwaysAskList);
4839                includeBrowser = true;
4840            }
4841
4842            if (includeBrowser) {
4843                // Also add browsers (all of them or only the default one)
4844                if (DEBUG_DOMAIN_VERIFICATION) {
4845                    Slog.v(TAG, "   ...including browsers in candidate set");
4846                }
4847                if ((matchFlags & MATCH_ALL) != 0) {
4848                    result.addAll(matchAllList);
4849                } else {
4850                    // Browser/generic handling case.  If there's a default browser, go straight
4851                    // to that (but only if there is no other higher-priority match).
4852                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
4853                    int maxMatchPrio = 0;
4854                    ResolveInfo defaultBrowserMatch = null;
4855                    final int numCandidates = matchAllList.size();
4856                    for (int n = 0; n < numCandidates; n++) {
4857                        ResolveInfo info = matchAllList.get(n);
4858                        // track the highest overall match priority...
4859                        if (info.priority > maxMatchPrio) {
4860                            maxMatchPrio = info.priority;
4861                        }
4862                        // ...and the highest-priority default browser match
4863                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4864                            if (defaultBrowserMatch == null
4865                                    || (defaultBrowserMatch.priority < info.priority)) {
4866                                if (debug) {
4867                                    Slog.v(TAG, "Considering default browser match " + info);
4868                                }
4869                                defaultBrowserMatch = info;
4870                            }
4871                        }
4872                    }
4873                    if (defaultBrowserMatch != null
4874                            && defaultBrowserMatch.priority >= maxMatchPrio
4875                            && !TextUtils.isEmpty(defaultBrowserPackageName))
4876                    {
4877                        if (debug) {
4878                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
4879                        }
4880                        result.add(defaultBrowserMatch);
4881                    } else {
4882                        result.addAll(matchAllList);
4883                    }
4884                }
4885
4886                // If there is nothing selected, add all candidates and remove the ones that the user
4887                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
4888                if (result.size() == 0) {
4889                    result.addAll(candidates);
4890                    result.removeAll(neverList);
4891                }
4892            }
4893        }
4894        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
4895            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
4896                    result.size());
4897            for (ResolveInfo info : result) {
4898                Slog.v(TAG, "  + " + info.activityInfo);
4899            }
4900        }
4901        return result;
4902    }
4903
4904    // Returns a packed value as a long:
4905    //
4906    // high 'int'-sized word: link status: undefined/ask/never/always.
4907    // low 'int'-sized word: relative priority among 'always' results.
4908    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4909        long result = ps.getDomainVerificationStatusForUser(userId);
4910        // if none available, get the master status
4911        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4912            if (ps.getIntentFilterVerificationInfo() != null) {
4913                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
4914            }
4915        }
4916        return result;
4917    }
4918
4919    private ResolveInfo querySkipCurrentProfileIntents(
4920            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4921            int flags, int sourceUserId) {
4922        if (matchingFilters != null) {
4923            int size = matchingFilters.size();
4924            for (int i = 0; i < size; i ++) {
4925                CrossProfileIntentFilter filter = matchingFilters.get(i);
4926                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4927                    // Checking if there are activities in the target user that can handle the
4928                    // intent.
4929                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
4930                            resolvedType, flags, sourceUserId);
4931                    if (resolveInfo != null) {
4932                        return resolveInfo;
4933                    }
4934                }
4935            }
4936        }
4937        return null;
4938    }
4939
4940    // Return matching ResolveInfo if any for skip current profile intent filters.
4941    private ResolveInfo queryCrossProfileIntents(
4942            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4943            int flags, int sourceUserId) {
4944        if (matchingFilters != null) {
4945            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4946            // match the same intent. For performance reasons, it is better not to
4947            // run queryIntent twice for the same userId
4948            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4949            int size = matchingFilters.size();
4950            for (int i = 0; i < size; i++) {
4951                CrossProfileIntentFilter filter = matchingFilters.get(i);
4952                int targetUserId = filter.getTargetUserId();
4953                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4954                        && !alreadyTriedUserIds.get(targetUserId)) {
4955                    // Checking if there are activities in the target user that can handle the
4956                    // intent.
4957                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
4958                            resolvedType, flags, sourceUserId);
4959                    if (resolveInfo != null) return resolveInfo;
4960                    alreadyTriedUserIds.put(targetUserId, true);
4961                }
4962            }
4963        }
4964        return null;
4965    }
4966
4967    /**
4968     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
4969     * will forward the intent to the filter's target user.
4970     * Otherwise, returns null.
4971     */
4972    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
4973            String resolvedType, int flags, int sourceUserId) {
4974        int targetUserId = filter.getTargetUserId();
4975        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4976                resolvedType, flags, targetUserId);
4977        if (resultTargetUser != null && !resultTargetUser.isEmpty()
4978                && isUserEnabled(targetUserId)) {
4979            return createForwardingResolveInfoUnchecked(filter, sourceUserId, targetUserId);
4980        }
4981        return null;
4982    }
4983
4984    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
4985            int sourceUserId, int targetUserId) {
4986        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4987        long ident = Binder.clearCallingIdentity();
4988        boolean targetIsProfile;
4989        try {
4990            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
4991        } finally {
4992            Binder.restoreCallingIdentity(ident);
4993        }
4994        String className;
4995        if (targetIsProfile) {
4996            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4997        } else {
4998            className = FORWARD_INTENT_TO_PARENT;
4999        }
5000        ComponentName forwardingActivityComponentName = new ComponentName(
5001                mAndroidApplication.packageName, className);
5002        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5003                sourceUserId);
5004        if (!targetIsProfile) {
5005            forwardingActivityInfo.showUserIcon = targetUserId;
5006            forwardingResolveInfo.noResourceId = true;
5007        }
5008        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5009        forwardingResolveInfo.priority = 0;
5010        forwardingResolveInfo.preferredOrder = 0;
5011        forwardingResolveInfo.match = 0;
5012        forwardingResolveInfo.isDefault = true;
5013        forwardingResolveInfo.filter = filter;
5014        forwardingResolveInfo.targetUserId = targetUserId;
5015        return forwardingResolveInfo;
5016    }
5017
5018    @Override
5019    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5020            Intent[] specifics, String[] specificTypes, Intent intent,
5021            String resolvedType, int flags, int userId) {
5022        if (!sUserManager.exists(userId)) return Collections.emptyList();
5023        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5024                false, "query intent activity options");
5025        final String resultsAction = intent.getAction();
5026
5027        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5028                | PackageManager.GET_RESOLVED_FILTER, userId);
5029
5030        if (DEBUG_INTENT_MATCHING) {
5031            Log.v(TAG, "Query " + intent + ": " + results);
5032        }
5033
5034        int specificsPos = 0;
5035        int N;
5036
5037        // todo: note that the algorithm used here is O(N^2).  This
5038        // isn't a problem in our current environment, but if we start running
5039        // into situations where we have more than 5 or 10 matches then this
5040        // should probably be changed to something smarter...
5041
5042        // First we go through and resolve each of the specific items
5043        // that were supplied, taking care of removing any corresponding
5044        // duplicate items in the generic resolve list.
5045        if (specifics != null) {
5046            for (int i=0; i<specifics.length; i++) {
5047                final Intent sintent = specifics[i];
5048                if (sintent == null) {
5049                    continue;
5050                }
5051
5052                if (DEBUG_INTENT_MATCHING) {
5053                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5054                }
5055
5056                String action = sintent.getAction();
5057                if (resultsAction != null && resultsAction.equals(action)) {
5058                    // If this action was explicitly requested, then don't
5059                    // remove things that have it.
5060                    action = null;
5061                }
5062
5063                ResolveInfo ri = null;
5064                ActivityInfo ai = null;
5065
5066                ComponentName comp = sintent.getComponent();
5067                if (comp == null) {
5068                    ri = resolveIntent(
5069                        sintent,
5070                        specificTypes != null ? specificTypes[i] : null,
5071                            flags, userId);
5072                    if (ri == null) {
5073                        continue;
5074                    }
5075                    if (ri == mResolveInfo) {
5076                        // ACK!  Must do something better with this.
5077                    }
5078                    ai = ri.activityInfo;
5079                    comp = new ComponentName(ai.applicationInfo.packageName,
5080                            ai.name);
5081                } else {
5082                    ai = getActivityInfo(comp, flags, userId);
5083                    if (ai == null) {
5084                        continue;
5085                    }
5086                }
5087
5088                // Look for any generic query activities that are duplicates
5089                // of this specific one, and remove them from the results.
5090                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5091                N = results.size();
5092                int j;
5093                for (j=specificsPos; j<N; j++) {
5094                    ResolveInfo sri = results.get(j);
5095                    if ((sri.activityInfo.name.equals(comp.getClassName())
5096                            && sri.activityInfo.applicationInfo.packageName.equals(
5097                                    comp.getPackageName()))
5098                        || (action != null && sri.filter.matchAction(action))) {
5099                        results.remove(j);
5100                        if (DEBUG_INTENT_MATCHING) Log.v(
5101                            TAG, "Removing duplicate item from " + j
5102                            + " due to specific " + specificsPos);
5103                        if (ri == null) {
5104                            ri = sri;
5105                        }
5106                        j--;
5107                        N--;
5108                    }
5109                }
5110
5111                // Add this specific item to its proper place.
5112                if (ri == null) {
5113                    ri = new ResolveInfo();
5114                    ri.activityInfo = ai;
5115                }
5116                results.add(specificsPos, ri);
5117                ri.specificIndex = i;
5118                specificsPos++;
5119            }
5120        }
5121
5122        // Now we go through the remaining generic results and remove any
5123        // duplicate actions that are found here.
5124        N = results.size();
5125        for (int i=specificsPos; i<N-1; i++) {
5126            final ResolveInfo rii = results.get(i);
5127            if (rii.filter == null) {
5128                continue;
5129            }
5130
5131            // Iterate over all of the actions of this result's intent
5132            // filter...  typically this should be just one.
5133            final Iterator<String> it = rii.filter.actionsIterator();
5134            if (it == null) {
5135                continue;
5136            }
5137            while (it.hasNext()) {
5138                final String action = it.next();
5139                if (resultsAction != null && resultsAction.equals(action)) {
5140                    // If this action was explicitly requested, then don't
5141                    // remove things that have it.
5142                    continue;
5143                }
5144                for (int j=i+1; j<N; j++) {
5145                    final ResolveInfo rij = results.get(j);
5146                    if (rij.filter != null && rij.filter.hasAction(action)) {
5147                        results.remove(j);
5148                        if (DEBUG_INTENT_MATCHING) Log.v(
5149                            TAG, "Removing duplicate item from " + j
5150                            + " due to action " + action + " at " + i);
5151                        j--;
5152                        N--;
5153                    }
5154                }
5155            }
5156
5157            // If the caller didn't request filter information, drop it now
5158            // so we don't have to marshall/unmarshall it.
5159            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5160                rii.filter = null;
5161            }
5162        }
5163
5164        // Filter out the caller activity if so requested.
5165        if (caller != null) {
5166            N = results.size();
5167            for (int i=0; i<N; i++) {
5168                ActivityInfo ainfo = results.get(i).activityInfo;
5169                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5170                        && caller.getClassName().equals(ainfo.name)) {
5171                    results.remove(i);
5172                    break;
5173                }
5174            }
5175        }
5176
5177        // If the caller didn't request filter information,
5178        // drop them now so we don't have to
5179        // marshall/unmarshall it.
5180        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5181            N = results.size();
5182            for (int i=0; i<N; i++) {
5183                results.get(i).filter = null;
5184            }
5185        }
5186
5187        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5188        return results;
5189    }
5190
5191    @Override
5192    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5193            int userId) {
5194        if (!sUserManager.exists(userId)) return Collections.emptyList();
5195        ComponentName comp = intent.getComponent();
5196        if (comp == null) {
5197            if (intent.getSelector() != null) {
5198                intent = intent.getSelector();
5199                comp = intent.getComponent();
5200            }
5201        }
5202        if (comp != null) {
5203            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5204            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5205            if (ai != null) {
5206                ResolveInfo ri = new ResolveInfo();
5207                ri.activityInfo = ai;
5208                list.add(ri);
5209            }
5210            return list;
5211        }
5212
5213        // reader
5214        synchronized (mPackages) {
5215            String pkgName = intent.getPackage();
5216            if (pkgName == null) {
5217                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5218            }
5219            final PackageParser.Package pkg = mPackages.get(pkgName);
5220            if (pkg != null) {
5221                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5222                        userId);
5223            }
5224            return null;
5225        }
5226    }
5227
5228    @Override
5229    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5230        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5231        if (!sUserManager.exists(userId)) return null;
5232        if (query != null) {
5233            if (query.size() >= 1) {
5234                // If there is more than one service with the same priority,
5235                // just arbitrarily pick the first one.
5236                return query.get(0);
5237            }
5238        }
5239        return null;
5240    }
5241
5242    @Override
5243    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5244            int userId) {
5245        if (!sUserManager.exists(userId)) return Collections.emptyList();
5246        ComponentName comp = intent.getComponent();
5247        if (comp == null) {
5248            if (intent.getSelector() != null) {
5249                intent = intent.getSelector();
5250                comp = intent.getComponent();
5251            }
5252        }
5253        if (comp != null) {
5254            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5255            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5256            if (si != null) {
5257                final ResolveInfo ri = new ResolveInfo();
5258                ri.serviceInfo = si;
5259                list.add(ri);
5260            }
5261            return list;
5262        }
5263
5264        // reader
5265        synchronized (mPackages) {
5266            String pkgName = intent.getPackage();
5267            if (pkgName == null) {
5268                return mServices.queryIntent(intent, resolvedType, flags, userId);
5269            }
5270            final PackageParser.Package pkg = mPackages.get(pkgName);
5271            if (pkg != null) {
5272                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5273                        userId);
5274            }
5275            return null;
5276        }
5277    }
5278
5279    @Override
5280    public List<ResolveInfo> queryIntentContentProviders(
5281            Intent intent, String resolvedType, int flags, int userId) {
5282        if (!sUserManager.exists(userId)) return Collections.emptyList();
5283        ComponentName comp = intent.getComponent();
5284        if (comp == null) {
5285            if (intent.getSelector() != null) {
5286                intent = intent.getSelector();
5287                comp = intent.getComponent();
5288            }
5289        }
5290        if (comp != null) {
5291            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5292            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5293            if (pi != null) {
5294                final ResolveInfo ri = new ResolveInfo();
5295                ri.providerInfo = pi;
5296                list.add(ri);
5297            }
5298            return list;
5299        }
5300
5301        // reader
5302        synchronized (mPackages) {
5303            String pkgName = intent.getPackage();
5304            if (pkgName == null) {
5305                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5306            }
5307            final PackageParser.Package pkg = mPackages.get(pkgName);
5308            if (pkg != null) {
5309                return mProviders.queryIntentForPackage(
5310                        intent, resolvedType, flags, pkg.providers, userId);
5311            }
5312            return null;
5313        }
5314    }
5315
5316    @Override
5317    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5318        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5319
5320        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5321
5322        // writer
5323        synchronized (mPackages) {
5324            ArrayList<PackageInfo> list;
5325            if (listUninstalled) {
5326                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5327                for (PackageSetting ps : mSettings.mPackages.values()) {
5328                    PackageInfo pi;
5329                    if (ps.pkg != null) {
5330                        pi = generatePackageInfo(ps.pkg, flags, userId);
5331                    } else {
5332                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5333                    }
5334                    if (pi != null) {
5335                        list.add(pi);
5336                    }
5337                }
5338            } else {
5339                list = new ArrayList<PackageInfo>(mPackages.size());
5340                for (PackageParser.Package p : mPackages.values()) {
5341                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5342                    if (pi != null) {
5343                        list.add(pi);
5344                    }
5345                }
5346            }
5347
5348            return new ParceledListSlice<PackageInfo>(list);
5349        }
5350    }
5351
5352    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5353            String[] permissions, boolean[] tmp, int flags, int userId) {
5354        int numMatch = 0;
5355        final PermissionsState permissionsState = ps.getPermissionsState();
5356        for (int i=0; i<permissions.length; i++) {
5357            final String permission = permissions[i];
5358            if (permissionsState.hasPermission(permission, userId)) {
5359                tmp[i] = true;
5360                numMatch++;
5361            } else {
5362                tmp[i] = false;
5363            }
5364        }
5365        if (numMatch == 0) {
5366            return;
5367        }
5368        PackageInfo pi;
5369        if (ps.pkg != null) {
5370            pi = generatePackageInfo(ps.pkg, flags, userId);
5371        } else {
5372            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5373        }
5374        // The above might return null in cases of uninstalled apps or install-state
5375        // skew across users/profiles.
5376        if (pi != null) {
5377            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5378                if (numMatch == permissions.length) {
5379                    pi.requestedPermissions = permissions;
5380                } else {
5381                    pi.requestedPermissions = new String[numMatch];
5382                    numMatch = 0;
5383                    for (int i=0; i<permissions.length; i++) {
5384                        if (tmp[i]) {
5385                            pi.requestedPermissions[numMatch] = permissions[i];
5386                            numMatch++;
5387                        }
5388                    }
5389                }
5390            }
5391            list.add(pi);
5392        }
5393    }
5394
5395    @Override
5396    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5397            String[] permissions, int flags, int userId) {
5398        if (!sUserManager.exists(userId)) return null;
5399        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5400
5401        // writer
5402        synchronized (mPackages) {
5403            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5404            boolean[] tmpBools = new boolean[permissions.length];
5405            if (listUninstalled) {
5406                for (PackageSetting ps : mSettings.mPackages.values()) {
5407                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5408                }
5409            } else {
5410                for (PackageParser.Package pkg : mPackages.values()) {
5411                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5412                    if (ps != null) {
5413                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5414                                userId);
5415                    }
5416                }
5417            }
5418
5419            return new ParceledListSlice<PackageInfo>(list);
5420        }
5421    }
5422
5423    @Override
5424    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5425        if (!sUserManager.exists(userId)) return null;
5426        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
5427
5428        // writer
5429        synchronized (mPackages) {
5430            ArrayList<ApplicationInfo> list;
5431            if (listUninstalled) {
5432                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5433                for (PackageSetting ps : mSettings.mPackages.values()) {
5434                    ApplicationInfo ai;
5435                    if (ps.pkg != null) {
5436                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5437                                ps.readUserState(userId), userId);
5438                    } else {
5439                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5440                    }
5441                    if (ai != null) {
5442                        list.add(ai);
5443                    }
5444                }
5445            } else {
5446                list = new ArrayList<ApplicationInfo>(mPackages.size());
5447                for (PackageParser.Package p : mPackages.values()) {
5448                    if (p.mExtras != null) {
5449                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5450                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5451                        if (ai != null) {
5452                            list.add(ai);
5453                        }
5454                    }
5455                }
5456            }
5457
5458            return new ParceledListSlice<ApplicationInfo>(list);
5459        }
5460    }
5461
5462    public List<ApplicationInfo> getPersistentApplications(int flags) {
5463        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5464
5465        // reader
5466        synchronized (mPackages) {
5467            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5468            final int userId = UserHandle.getCallingUserId();
5469            while (i.hasNext()) {
5470                final PackageParser.Package p = i.next();
5471                if (p.applicationInfo != null
5472                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5473                        && (!mSafeMode || isSystemApp(p))) {
5474                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5475                    if (ps != null) {
5476                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5477                                ps.readUserState(userId), userId);
5478                        if (ai != null) {
5479                            finalList.add(ai);
5480                        }
5481                    }
5482                }
5483            }
5484        }
5485
5486        return finalList;
5487    }
5488
5489    @Override
5490    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5491        if (!sUserManager.exists(userId)) return null;
5492        // reader
5493        synchronized (mPackages) {
5494            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5495            PackageSetting ps = provider != null
5496                    ? mSettings.mPackages.get(provider.owner.packageName)
5497                    : null;
5498            return ps != null
5499                    && mSettings.isEnabledLPr(provider.info, flags, userId)
5500                    && (!mSafeMode || (provider.info.applicationInfo.flags
5501                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5502                    ? PackageParser.generateProviderInfo(provider, flags,
5503                            ps.readUserState(userId), userId)
5504                    : null;
5505        }
5506    }
5507
5508    /**
5509     * @deprecated
5510     */
5511    @Deprecated
5512    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5513        // reader
5514        synchronized (mPackages) {
5515            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5516                    .entrySet().iterator();
5517            final int userId = UserHandle.getCallingUserId();
5518            while (i.hasNext()) {
5519                Map.Entry<String, PackageParser.Provider> entry = i.next();
5520                PackageParser.Provider p = entry.getValue();
5521                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5522
5523                if (ps != null && p.syncable
5524                        && (!mSafeMode || (p.info.applicationInfo.flags
5525                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5526                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5527                            ps.readUserState(userId), userId);
5528                    if (info != null) {
5529                        outNames.add(entry.getKey());
5530                        outInfo.add(info);
5531                    }
5532                }
5533            }
5534        }
5535    }
5536
5537    @Override
5538    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5539            int uid, int flags) {
5540        ArrayList<ProviderInfo> finalList = null;
5541        // reader
5542        synchronized (mPackages) {
5543            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5544            final int userId = processName != null ?
5545                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
5546            while (i.hasNext()) {
5547                final PackageParser.Provider p = i.next();
5548                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5549                if (ps != null && p.info.authority != null
5550                        && (processName == null
5551                                || (p.info.processName.equals(processName)
5552                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5553                        && mSettings.isEnabledLPr(p.info, flags, userId)
5554                        && (!mSafeMode
5555                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5556                    if (finalList == null) {
5557                        finalList = new ArrayList<ProviderInfo>(3);
5558                    }
5559                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5560                            ps.readUserState(userId), userId);
5561                    if (info != null) {
5562                        finalList.add(info);
5563                    }
5564                }
5565            }
5566        }
5567
5568        if (finalList != null) {
5569            Collections.sort(finalList, mProviderInitOrderSorter);
5570            return new ParceledListSlice<ProviderInfo>(finalList);
5571        }
5572
5573        return null;
5574    }
5575
5576    @Override
5577    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
5578            int flags) {
5579        // reader
5580        synchronized (mPackages) {
5581            final PackageParser.Instrumentation i = mInstrumentation.get(name);
5582            return PackageParser.generateInstrumentationInfo(i, flags);
5583        }
5584    }
5585
5586    @Override
5587    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
5588            int flags) {
5589        ArrayList<InstrumentationInfo> finalList =
5590            new ArrayList<InstrumentationInfo>();
5591
5592        // reader
5593        synchronized (mPackages) {
5594            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
5595            while (i.hasNext()) {
5596                final PackageParser.Instrumentation p = i.next();
5597                if (targetPackage == null
5598                        || targetPackage.equals(p.info.targetPackage)) {
5599                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
5600                            flags);
5601                    if (ii != null) {
5602                        finalList.add(ii);
5603                    }
5604                }
5605            }
5606        }
5607
5608        return finalList;
5609    }
5610
5611    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
5612        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
5613        if (overlays == null) {
5614            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
5615            return;
5616        }
5617        for (PackageParser.Package opkg : overlays.values()) {
5618            // Not much to do if idmap fails: we already logged the error
5619            // and we certainly don't want to abort installation of pkg simply
5620            // because an overlay didn't fit properly. For these reasons,
5621            // ignore the return value of createIdmapForPackagePairLI.
5622            createIdmapForPackagePairLI(pkg, opkg);
5623        }
5624    }
5625
5626    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
5627            PackageParser.Package opkg) {
5628        if (!opkg.mTrustedOverlay) {
5629            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
5630                    opkg.baseCodePath + ": overlay not trusted");
5631            return false;
5632        }
5633        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
5634        if (overlaySet == null) {
5635            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
5636                    opkg.baseCodePath + " but target package has no known overlays");
5637            return false;
5638        }
5639        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
5640        // TODO: generate idmap for split APKs
5641        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
5642            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
5643                    + opkg.baseCodePath);
5644            return false;
5645        }
5646        PackageParser.Package[] overlayArray =
5647            overlaySet.values().toArray(new PackageParser.Package[0]);
5648        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
5649            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
5650                return p1.mOverlayPriority - p2.mOverlayPriority;
5651            }
5652        };
5653        Arrays.sort(overlayArray, cmp);
5654
5655        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
5656        int i = 0;
5657        for (PackageParser.Package p : overlayArray) {
5658            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
5659        }
5660        return true;
5661    }
5662
5663    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5664        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
5665        try {
5666            scanDirLI(dir, parseFlags, scanFlags, currentTime);
5667        } finally {
5668            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5669        }
5670    }
5671
5672    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
5673        final File[] files = dir.listFiles();
5674        if (ArrayUtils.isEmpty(files)) {
5675            Log.d(TAG, "No files in app dir " + dir);
5676            return;
5677        }
5678
5679        if (DEBUG_PACKAGE_SCANNING) {
5680            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
5681                    + " flags=0x" + Integer.toHexString(parseFlags));
5682        }
5683
5684        for (File file : files) {
5685            final boolean isPackage = (isApkFile(file) || file.isDirectory())
5686                    && !PackageInstallerService.isStageName(file.getName());
5687            if (!isPackage) {
5688                // Ignore entries which are not packages
5689                continue;
5690            }
5691            try {
5692                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
5693                        scanFlags, currentTime, UserHandle.SYSTEM);
5694            } catch (PackageManagerException e) {
5695                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
5696
5697                // Delete invalid userdata apps
5698                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
5699                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
5700                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
5701                    if (file.isDirectory()) {
5702                        mInstaller.rmPackageDir(file.getAbsolutePath());
5703                    } else {
5704                        file.delete();
5705                    }
5706                }
5707            }
5708        }
5709    }
5710
5711    private static File getSettingsProblemFile() {
5712        File dataDir = Environment.getDataDirectory();
5713        File systemDir = new File(dataDir, "system");
5714        File fname = new File(systemDir, "uiderrors.txt");
5715        return fname;
5716    }
5717
5718    static void reportSettingsProblem(int priority, String msg) {
5719        logCriticalInfo(priority, msg);
5720    }
5721
5722    static void logCriticalInfo(int priority, String msg) {
5723        Slog.println(priority, TAG, msg);
5724        EventLogTags.writePmCriticalInfo(msg);
5725        try {
5726            File fname = getSettingsProblemFile();
5727            FileOutputStream out = new FileOutputStream(fname, true);
5728            PrintWriter pw = new FastPrintWriter(out);
5729            SimpleDateFormat formatter = new SimpleDateFormat();
5730            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5731            pw.println(dateString + ": " + msg);
5732            pw.close();
5733            FileUtils.setPermissions(
5734                    fname.toString(),
5735                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5736                    -1, -1);
5737        } catch (java.io.IOException e) {
5738        }
5739    }
5740
5741    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5742            PackageParser.Package pkg, File srcFile, int parseFlags)
5743            throws PackageManagerException {
5744        if (ps != null
5745                && ps.codePath.equals(srcFile)
5746                && ps.timeStamp == srcFile.lastModified()
5747                && !isCompatSignatureUpdateNeeded(pkg)
5748                && !isRecoverSignatureUpdateNeeded(pkg)) {
5749            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5750            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5751            ArraySet<PublicKey> signingKs;
5752            synchronized (mPackages) {
5753                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5754            }
5755            if (ps.signatures.mSignatures != null
5756                    && ps.signatures.mSignatures.length != 0
5757                    && signingKs != null) {
5758                // Optimization: reuse the existing cached certificates
5759                // if the package appears to be unchanged.
5760                pkg.mSignatures = ps.signatures.mSignatures;
5761                pkg.mSigningKeys = signingKs;
5762                return;
5763            }
5764
5765            Slog.w(TAG, "PackageSetting for " + ps.name
5766                    + " is missing signatures.  Collecting certs again to recover them.");
5767        } else {
5768            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5769        }
5770
5771        try {
5772            pp.collectCertificates(pkg, parseFlags);
5773            pp.collectManifestDigest(pkg);
5774        } catch (PackageParserException e) {
5775            throw PackageManagerException.from(e);
5776        }
5777    }
5778
5779    /**
5780     *  Traces a package scan.
5781     *  @see #scanPackageLI(File, int, int, long, UserHandle)
5782     */
5783    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
5784            long currentTime, UserHandle user) throws PackageManagerException {
5785        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
5786        try {
5787            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
5788        } finally {
5789            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5790        }
5791    }
5792
5793    /**
5794     *  Scans a package and returns the newly parsed package.
5795     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
5796     */
5797    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5798            long currentTime, UserHandle user) throws PackageManagerException {
5799        Preconditions.checkNotNull(user);
5800
5801        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5802        parseFlags |= mDefParseFlags;
5803        PackageParser pp = new PackageParser();
5804        pp.setSeparateProcesses(mSeparateProcesses);
5805        pp.setOnlyCoreApps(mOnlyCore);
5806        pp.setDisplayMetrics(mMetrics);
5807
5808        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5809            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5810        }
5811
5812        final PackageParser.Package pkg;
5813        try {
5814            pkg = pp.parsePackage(scanFile, parseFlags);
5815        } catch (PackageParserException e) {
5816            throw PackageManagerException.from(e);
5817        }
5818
5819        PackageSetting ps = null;
5820        PackageSetting updatedPkg;
5821        // reader
5822        synchronized (mPackages) {
5823            // Look to see if we already know about this package.
5824            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5825            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5826                // This package has been renamed to its original name.  Let's
5827                // use that.
5828                ps = mSettings.peekPackageLPr(oldName);
5829            }
5830            // If there was no original package, see one for the real package name.
5831            if (ps == null) {
5832                ps = mSettings.peekPackageLPr(pkg.packageName);
5833            }
5834            // Check to see if this package could be hiding/updating a system
5835            // package.  Must look for it either under the original or real
5836            // package name depending on our state.
5837            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5838            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5839        }
5840        boolean updatedPkgBetter = false;
5841        // First check if this is a system package that may involve an update
5842        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
5843            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5844            // it needs to drop FLAG_PRIVILEGED.
5845            if (locationIsPrivileged(scanFile)) {
5846                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5847            } else {
5848                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5849            }
5850
5851            if (ps != null && !ps.codePath.equals(scanFile)) {
5852                // The path has changed from what was last scanned...  check the
5853                // version of the new path against what we have stored to determine
5854                // what to do.
5855                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5856                if (pkg.mVersionCode <= ps.versionCode) {
5857                    // The system package has been updated and the code path does not match
5858                    // Ignore entry. Skip it.
5859                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5860                            + " ignored: updated version " + ps.versionCode
5861                            + " better than this " + pkg.mVersionCode);
5862                    if (!updatedPkg.codePath.equals(scanFile)) {
5863                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5864                                + ps.name + " changing from " + updatedPkg.codePathString
5865                                + " to " + scanFile);
5866                        updatedPkg.codePath = scanFile;
5867                        updatedPkg.codePathString = scanFile.toString();
5868                        updatedPkg.resourcePath = scanFile;
5869                        updatedPkg.resourcePathString = scanFile.toString();
5870                    }
5871                    updatedPkg.pkg = pkg;
5872                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5873                            "Package " + ps.name + " at " + scanFile
5874                                    + " ignored: updated version " + ps.versionCode
5875                                    + " better than this " + pkg.mVersionCode);
5876                } else {
5877                    // The current app on the system partition is better than
5878                    // what we have updated to on the data partition; switch
5879                    // back to the system partition version.
5880                    // At this point, its safely assumed that package installation for
5881                    // apps in system partition will go through. If not there won't be a working
5882                    // version of the app
5883                    // writer
5884                    synchronized (mPackages) {
5885                        // Just remove the loaded entries from package lists.
5886                        mPackages.remove(ps.name);
5887                    }
5888
5889                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5890                            + " reverting from " + ps.codePathString
5891                            + ": new version " + pkg.mVersionCode
5892                            + " better than installed " + ps.versionCode);
5893
5894                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5895                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5896                    synchronized (mInstallLock) {
5897                        args.cleanUpResourcesLI();
5898                    }
5899                    synchronized (mPackages) {
5900                        mSettings.enableSystemPackageLPw(ps.name);
5901                    }
5902                    updatedPkgBetter = true;
5903                }
5904            }
5905        }
5906
5907        if (updatedPkg != null) {
5908            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5909            // initially
5910            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5911
5912            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5913            // flag set initially
5914            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5915                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5916            }
5917        }
5918
5919        // Verify certificates against what was last scanned
5920        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5921
5922        /*
5923         * A new system app appeared, but we already had a non-system one of the
5924         * same name installed earlier.
5925         */
5926        boolean shouldHideSystemApp = false;
5927        if (updatedPkg == null && ps != null
5928                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5929            /*
5930             * Check to make sure the signatures match first. If they don't,
5931             * wipe the installed application and its data.
5932             */
5933            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5934                    != PackageManager.SIGNATURE_MATCH) {
5935                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5936                        + " signatures don't match existing userdata copy; removing");
5937                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5938                ps = null;
5939            } else {
5940                /*
5941                 * If the newly-added system app is an older version than the
5942                 * already installed version, hide it. It will be scanned later
5943                 * and re-added like an update.
5944                 */
5945                if (pkg.mVersionCode <= ps.versionCode) {
5946                    shouldHideSystemApp = true;
5947                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5948                            + " but new version " + pkg.mVersionCode + " better than installed "
5949                            + ps.versionCode + "; hiding system");
5950                } else {
5951                    /*
5952                     * The newly found system app is a newer version that the
5953                     * one previously installed. Simply remove the
5954                     * already-installed application and replace it with our own
5955                     * while keeping the application data.
5956                     */
5957                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5958                            + " reverting from " + ps.codePathString + ": new version "
5959                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5960                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5961                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5962                    synchronized (mInstallLock) {
5963                        args.cleanUpResourcesLI();
5964                    }
5965                }
5966            }
5967        }
5968
5969        // The apk is forward locked (not public) if its code and resources
5970        // are kept in different files. (except for app in either system or
5971        // vendor path).
5972        // TODO grab this value from PackageSettings
5973        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5974            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5975                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5976            }
5977        }
5978
5979        // TODO: extend to support forward-locked splits
5980        String resourcePath = null;
5981        String baseResourcePath = null;
5982        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5983            if (ps != null && ps.resourcePathString != null) {
5984                resourcePath = ps.resourcePathString;
5985                baseResourcePath = ps.resourcePathString;
5986            } else {
5987                // Should not happen at all. Just log an error.
5988                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5989            }
5990        } else {
5991            resourcePath = pkg.codePath;
5992            baseResourcePath = pkg.baseCodePath;
5993        }
5994
5995        // Set application objects path explicitly.
5996        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5997        pkg.applicationInfo.setCodePath(pkg.codePath);
5998        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5999        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6000        pkg.applicationInfo.setResourcePath(resourcePath);
6001        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6002        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6003
6004        // Note that we invoke the following method only if we are about to unpack an application
6005        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6006                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6007
6008        /*
6009         * If the system app should be overridden by a previously installed
6010         * data, hide the system app now and let the /data/app scan pick it up
6011         * again.
6012         */
6013        if (shouldHideSystemApp) {
6014            synchronized (mPackages) {
6015                mSettings.disableSystemPackageLPw(pkg.packageName);
6016            }
6017        }
6018
6019        return scannedPkg;
6020    }
6021
6022    private static String fixProcessName(String defProcessName,
6023            String processName, int uid) {
6024        if (processName == null) {
6025            return defProcessName;
6026        }
6027        return processName;
6028    }
6029
6030    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6031            throws PackageManagerException {
6032        if (pkgSetting.signatures.mSignatures != null) {
6033            // Already existing package. Make sure signatures match
6034            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6035                    == PackageManager.SIGNATURE_MATCH;
6036            if (!match) {
6037                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6038                        == PackageManager.SIGNATURE_MATCH;
6039            }
6040            if (!match) {
6041                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6042                        == PackageManager.SIGNATURE_MATCH;
6043            }
6044            if (!match) {
6045                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6046                        + pkg.packageName + " signatures do not match the "
6047                        + "previously installed version; ignoring!");
6048            }
6049        }
6050
6051        // Check for shared user signatures
6052        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6053            // Already existing package. Make sure signatures match
6054            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6055                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6056            if (!match) {
6057                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6058                        == PackageManager.SIGNATURE_MATCH;
6059            }
6060            if (!match) {
6061                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6062                        == PackageManager.SIGNATURE_MATCH;
6063            }
6064            if (!match) {
6065                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6066                        "Package " + pkg.packageName
6067                        + " has no signatures that match those in shared user "
6068                        + pkgSetting.sharedUser.name + "; ignoring!");
6069            }
6070        }
6071    }
6072
6073    /**
6074     * Enforces that only the system UID or root's UID can call a method exposed
6075     * via Binder.
6076     *
6077     * @param message used as message if SecurityException is thrown
6078     * @throws SecurityException if the caller is not system or root
6079     */
6080    private static final void enforceSystemOrRoot(String message) {
6081        final int uid = Binder.getCallingUid();
6082        if (uid != Process.SYSTEM_UID && uid != 0) {
6083            throw new SecurityException(message);
6084        }
6085    }
6086
6087    @Override
6088    public void performBootDexOpt() {
6089        enforceSystemOrRoot("Only the system can request dexopt be performed");
6090
6091        // Before everything else, see whether we need to fstrim.
6092        try {
6093            IMountService ms = PackageHelper.getMountService();
6094            if (ms != null) {
6095                final boolean isUpgrade = isUpgrade();
6096                boolean doTrim = isUpgrade;
6097                if (doTrim) {
6098                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6099                } else {
6100                    final long interval = android.provider.Settings.Global.getLong(
6101                            mContext.getContentResolver(),
6102                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6103                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6104                    if (interval > 0) {
6105                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6106                        if (timeSinceLast > interval) {
6107                            doTrim = true;
6108                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6109                                    + "; running immediately");
6110                        }
6111                    }
6112                }
6113                if (doTrim) {
6114                    if (!isFirstBoot()) {
6115                        try {
6116                            ActivityManagerNative.getDefault().showBootMessage(
6117                                    mContext.getResources().getString(
6118                                            R.string.android_upgrading_fstrim), true);
6119                        } catch (RemoteException e) {
6120                        }
6121                    }
6122                    ms.runMaintenance();
6123                }
6124            } else {
6125                Slog.e(TAG, "Mount service unavailable!");
6126            }
6127        } catch (RemoteException e) {
6128            // Can't happen; MountService is local
6129        }
6130
6131        final ArraySet<PackageParser.Package> pkgs;
6132        synchronized (mPackages) {
6133            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
6134        }
6135
6136        if (pkgs != null) {
6137            // Sort apps by importance for dexopt ordering. Important apps are given more priority
6138            // in case the device runs out of space.
6139            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
6140            // Give priority to core apps.
6141            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6142                PackageParser.Package pkg = it.next();
6143                if (pkg.coreApp) {
6144                    if (DEBUG_DEXOPT) {
6145                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
6146                    }
6147                    sortedPkgs.add(pkg);
6148                    it.remove();
6149                }
6150            }
6151            // Give priority to system apps that listen for pre boot complete.
6152            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
6153            ArraySet<String> pkgNames = getPackageNamesForIntent(intent, UserHandle.USER_SYSTEM);
6154            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
6155                PackageParser.Package pkg = it.next();
6156                if (pkgNames.contains(pkg.packageName)) {
6157                    if (DEBUG_DEXOPT) {
6158                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
6159                    }
6160                    sortedPkgs.add(pkg);
6161                    it.remove();
6162                }
6163            }
6164            // Filter out packages that aren't recently used.
6165            filterRecentlyUsedApps(pkgs);
6166            // Add all remaining apps.
6167            for (PackageParser.Package pkg : pkgs) {
6168                if (DEBUG_DEXOPT) {
6169                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
6170                }
6171                sortedPkgs.add(pkg);
6172            }
6173
6174            // If we want to be lazy, filter everything that wasn't recently used.
6175            if (mLazyDexOpt) {
6176                filterRecentlyUsedApps(sortedPkgs);
6177            }
6178
6179            int i = 0;
6180            int total = sortedPkgs.size();
6181            File dataDir = Environment.getDataDirectory();
6182            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
6183            if (lowThreshold == 0) {
6184                throw new IllegalStateException("Invalid low memory threshold");
6185            }
6186            for (PackageParser.Package pkg : sortedPkgs) {
6187                long usableSpace = dataDir.getUsableSpace();
6188                if (usableSpace < lowThreshold) {
6189                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
6190                    break;
6191                }
6192                performBootDexOpt(pkg, ++i, total);
6193            }
6194        }
6195    }
6196
6197    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
6198        // Filter out packages that aren't recently used.
6199        //
6200        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
6201        // should do a full dexopt.
6202        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
6203            int total = pkgs.size();
6204            int skipped = 0;
6205            long now = System.currentTimeMillis();
6206            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
6207                PackageParser.Package pkg = i.next();
6208                long then = pkg.mLastPackageUsageTimeInMills;
6209                if (then + mDexOptLRUThresholdInMills < now) {
6210                    if (DEBUG_DEXOPT) {
6211                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
6212                              ((then == 0) ? "never" : new Date(then)));
6213                    }
6214                    i.remove();
6215                    skipped++;
6216                }
6217            }
6218            if (DEBUG_DEXOPT) {
6219                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
6220            }
6221        }
6222    }
6223
6224    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6225        List<ResolveInfo> ris = null;
6226        try {
6227            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6228                    intent, null, 0, userId);
6229        } catch (RemoteException e) {
6230        }
6231        ArraySet<String> pkgNames = new ArraySet<String>();
6232        if (ris != null) {
6233            for (ResolveInfo ri : ris) {
6234                pkgNames.add(ri.activityInfo.packageName);
6235            }
6236        }
6237        return pkgNames;
6238    }
6239
6240    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
6241        if (DEBUG_DEXOPT) {
6242            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
6243        }
6244        if (!isFirstBoot()) {
6245            try {
6246                ActivityManagerNative.getDefault().showBootMessage(
6247                        mContext.getResources().getString(R.string.android_upgrading_apk,
6248                                curr, total), true);
6249            } catch (RemoteException e) {
6250            }
6251        }
6252        PackageParser.Package p = pkg;
6253        synchronized (mInstallLock) {
6254            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
6255                    false /* force dex */, false /* defer */, true /* include dependencies */,
6256                    false /* boot complete */, false /*useJit*/);
6257        }
6258    }
6259
6260    @Override
6261    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6262        return performDexOptTraced(packageName, instructionSet, false);
6263    }
6264
6265    public boolean performDexOpt(
6266            String packageName, String instructionSet, boolean backgroundDexopt) {
6267        return performDexOptTraced(packageName, instructionSet, backgroundDexopt);
6268    }
6269
6270    private boolean performDexOptTraced(
6271            String packageName, String instructionSet, boolean backgroundDexopt) {
6272        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6273        try {
6274            return performDexOptInternal(packageName, instructionSet, backgroundDexopt);
6275        } finally {
6276            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6277        }
6278    }
6279
6280    private boolean performDexOptInternal(
6281            String packageName, String instructionSet, boolean backgroundDexopt) {
6282        boolean dexopt = mLazyDexOpt || backgroundDexopt;
6283        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
6284        if (!dexopt && !updateUsage) {
6285            // We aren't going to dexopt or update usage, so bail early.
6286            return false;
6287        }
6288        PackageParser.Package p;
6289        final String targetInstructionSet;
6290        synchronized (mPackages) {
6291            p = mPackages.get(packageName);
6292            if (p == null) {
6293                return false;
6294            }
6295            if (updateUsage) {
6296                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6297            }
6298            mPackageUsage.write(false);
6299            if (!dexopt) {
6300                // We aren't going to dexopt, so bail early.
6301                return false;
6302            }
6303
6304            targetInstructionSet = instructionSet != null ? instructionSet :
6305                    getPrimaryInstructionSet(p.applicationInfo);
6306            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6307                return false;
6308            }
6309        }
6310        long callingId = Binder.clearCallingIdentity();
6311        try {
6312            synchronized (mInstallLock) {
6313                final String[] instructionSets = new String[] { targetInstructionSet };
6314                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6315                        false /* forceDex */, false /* defer */, true /* inclDependencies */,
6316                        true /* boot complete */, false /*useJit*/);
6317                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6318            }
6319        } finally {
6320            Binder.restoreCallingIdentity(callingId);
6321        }
6322    }
6323
6324    public ArraySet<String> getPackagesThatNeedDexOpt() {
6325        ArraySet<String> pkgs = null;
6326        synchronized (mPackages) {
6327            for (PackageParser.Package p : mPackages.values()) {
6328                if (DEBUG_DEXOPT) {
6329                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6330                }
6331                if (!p.mDexOptPerformed.isEmpty()) {
6332                    continue;
6333                }
6334                if (pkgs == null) {
6335                    pkgs = new ArraySet<String>();
6336                }
6337                pkgs.add(p.packageName);
6338            }
6339        }
6340        return pkgs;
6341    }
6342
6343    public void shutdown() {
6344        mPackageUsage.write(true);
6345    }
6346
6347    @Override
6348    public void forceDexOpt(String packageName) {
6349        enforceSystemOrRoot("forceDexOpt");
6350
6351        PackageParser.Package pkg;
6352        synchronized (mPackages) {
6353            pkg = mPackages.get(packageName);
6354            if (pkg == null) {
6355                throw new IllegalArgumentException("Missing package: " + packageName);
6356            }
6357        }
6358
6359        synchronized (mInstallLock) {
6360            final String[] instructionSets = new String[] {
6361                    getPrimaryInstructionSet(pkg.applicationInfo) };
6362
6363            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6364
6365            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6366                    true /*forceDex*/, false /* defer */, true /* inclDependencies */,
6367                    true /* boot complete */, false /*useJit*/);
6368
6369            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6370            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6371                throw new IllegalStateException("Failed to dexopt: " + res);
6372            }
6373        }
6374    }
6375
6376    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6377        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6378            Slog.w(TAG, "Unable to update from " + oldPkg.name
6379                    + " to " + newPkg.packageName
6380                    + ": old package not in system partition");
6381            return false;
6382        } else if (mPackages.get(oldPkg.name) != null) {
6383            Slog.w(TAG, "Unable to update from " + oldPkg.name
6384                    + " to " + newPkg.packageName
6385                    + ": old package still exists");
6386            return false;
6387        }
6388        return true;
6389    }
6390
6391    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
6392        int[] users = sUserManager.getUserIds();
6393        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6394        if (res < 0) {
6395            return res;
6396        }
6397        for (int user : users) {
6398            if (user != 0) {
6399                res = mInstaller.createUserData(volumeUuid, packageName,
6400                        UserHandle.getUid(user, uid), user, seinfo);
6401                if (res < 0) {
6402                    return res;
6403                }
6404            }
6405        }
6406        return res;
6407    }
6408
6409    private int removeDataDirsLI(String volumeUuid, String packageName) {
6410        int[] users = sUserManager.getUserIds();
6411        int res = 0;
6412        for (int user : users) {
6413            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6414            if (resInner < 0) {
6415                res = resInner;
6416            }
6417        }
6418
6419        return res;
6420    }
6421
6422    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6423        int[] users = sUserManager.getUserIds();
6424        int res = 0;
6425        for (int user : users) {
6426            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6427            if (resInner < 0) {
6428                res = resInner;
6429            }
6430        }
6431        return res;
6432    }
6433
6434    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6435            PackageParser.Package changingLib) {
6436        if (file.path != null) {
6437            usesLibraryFiles.add(file.path);
6438            return;
6439        }
6440        PackageParser.Package p = mPackages.get(file.apk);
6441        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6442            // If we are doing this while in the middle of updating a library apk,
6443            // then we need to make sure to use that new apk for determining the
6444            // dependencies here.  (We haven't yet finished committing the new apk
6445            // to the package manager state.)
6446            if (p == null || p.packageName.equals(changingLib.packageName)) {
6447                p = changingLib;
6448            }
6449        }
6450        if (p != null) {
6451            usesLibraryFiles.addAll(p.getAllCodePaths());
6452        }
6453    }
6454
6455    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6456            PackageParser.Package changingLib) throws PackageManagerException {
6457        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6458            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6459            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6460            for (int i=0; i<N; i++) {
6461                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6462                if (file == null) {
6463                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6464                            "Package " + pkg.packageName + " requires unavailable shared library "
6465                            + pkg.usesLibraries.get(i) + "; failing!");
6466                }
6467                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6468            }
6469            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6470            for (int i=0; i<N; i++) {
6471                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6472                if (file == null) {
6473                    Slog.w(TAG, "Package " + pkg.packageName
6474                            + " desires unavailable shared library "
6475                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6476                } else {
6477                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6478                }
6479            }
6480            N = usesLibraryFiles.size();
6481            if (N > 0) {
6482                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6483            } else {
6484                pkg.usesLibraryFiles = null;
6485            }
6486        }
6487    }
6488
6489    private static boolean hasString(List<String> list, List<String> which) {
6490        if (list == null) {
6491            return false;
6492        }
6493        for (int i=list.size()-1; i>=0; i--) {
6494            for (int j=which.size()-1; j>=0; j--) {
6495                if (which.get(j).equals(list.get(i))) {
6496                    return true;
6497                }
6498            }
6499        }
6500        return false;
6501    }
6502
6503    private void updateAllSharedLibrariesLPw() {
6504        for (PackageParser.Package pkg : mPackages.values()) {
6505            try {
6506                updateSharedLibrariesLPw(pkg, null);
6507            } catch (PackageManagerException e) {
6508                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6509            }
6510        }
6511    }
6512
6513    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6514            PackageParser.Package changingPkg) {
6515        ArrayList<PackageParser.Package> res = null;
6516        for (PackageParser.Package pkg : mPackages.values()) {
6517            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6518                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6519                if (res == null) {
6520                    res = new ArrayList<PackageParser.Package>();
6521                }
6522                res.add(pkg);
6523                try {
6524                    updateSharedLibrariesLPw(pkg, changingPkg);
6525                } catch (PackageManagerException e) {
6526                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6527                }
6528            }
6529        }
6530        return res;
6531    }
6532
6533    /**
6534     * Derive the value of the {@code cpuAbiOverride} based on the provided
6535     * value and an optional stored value from the package settings.
6536     */
6537    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6538        String cpuAbiOverride = null;
6539
6540        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6541            cpuAbiOverride = null;
6542        } else if (abiOverride != null) {
6543            cpuAbiOverride = abiOverride;
6544        } else if (settings != null) {
6545            cpuAbiOverride = settings.cpuAbiOverrideString;
6546        }
6547
6548        return cpuAbiOverride;
6549    }
6550
6551    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6552            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6553        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6554        try {
6555            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6556        } finally {
6557            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6558        }
6559    }
6560
6561    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6562            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6563        boolean success = false;
6564        try {
6565            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6566                    currentTime, user);
6567            success = true;
6568            return res;
6569        } finally {
6570            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6571                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6572            }
6573        }
6574    }
6575
6576    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6577            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6578        final File scanFile = new File(pkg.codePath);
6579        if (pkg.applicationInfo.getCodePath() == null ||
6580                pkg.applicationInfo.getResourcePath() == null) {
6581            // Bail out. The resource and code paths haven't been set.
6582            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6583                    "Code and resource paths haven't been set correctly");
6584        }
6585
6586        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6587            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6588        } else {
6589            // Only allow system apps to be flagged as core apps.
6590            pkg.coreApp = false;
6591        }
6592
6593        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6594            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6595        }
6596
6597        if (mCustomResolverComponentName != null &&
6598                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6599            setUpCustomResolverActivity(pkg);
6600        }
6601
6602        if (pkg.packageName.equals("android")) {
6603            synchronized (mPackages) {
6604                if (mAndroidApplication != null) {
6605                    Slog.w(TAG, "*************************************************");
6606                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6607                    Slog.w(TAG, " file=" + scanFile);
6608                    Slog.w(TAG, "*************************************************");
6609                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6610                            "Core android package being redefined.  Skipping.");
6611                }
6612
6613                // Set up information for our fall-back user intent resolution activity.
6614                mPlatformPackage = pkg;
6615                pkg.mVersionCode = mSdkVersion;
6616                mAndroidApplication = pkg.applicationInfo;
6617
6618                if (!mResolverReplaced) {
6619                    mResolveActivity.applicationInfo = mAndroidApplication;
6620                    mResolveActivity.name = ResolverActivity.class.getName();
6621                    mResolveActivity.packageName = mAndroidApplication.packageName;
6622                    mResolveActivity.processName = "system:ui";
6623                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6624                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6625                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6626                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6627                    mResolveActivity.exported = true;
6628                    mResolveActivity.enabled = true;
6629                    mResolveInfo.activityInfo = mResolveActivity;
6630                    mResolveInfo.priority = 0;
6631                    mResolveInfo.preferredOrder = 0;
6632                    mResolveInfo.match = 0;
6633                    mResolveComponentName = new ComponentName(
6634                            mAndroidApplication.packageName, mResolveActivity.name);
6635                }
6636            }
6637        }
6638
6639        if (DEBUG_PACKAGE_SCANNING) {
6640            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6641                Log.d(TAG, "Scanning package " + pkg.packageName);
6642        }
6643
6644        if (mPackages.containsKey(pkg.packageName)
6645                || mSharedLibraries.containsKey(pkg.packageName)) {
6646            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6647                    "Application package " + pkg.packageName
6648                    + " already installed.  Skipping duplicate.");
6649        }
6650
6651        // If we're only installing presumed-existing packages, require that the
6652        // scanned APK is both already known and at the path previously established
6653        // for it.  Previously unknown packages we pick up normally, but if we have an
6654        // a priori expectation about this package's install presence, enforce it.
6655        // With a singular exception for new system packages. When an OTA contains
6656        // a new system package, we allow the codepath to change from a system location
6657        // to the user-installed location. If we don't allow this change, any newer,
6658        // user-installed version of the application will be ignored.
6659        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6660            if (mExpectingBetter.containsKey(pkg.packageName)) {
6661                logCriticalInfo(Log.WARN,
6662                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6663            } else {
6664                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6665                if (known != null) {
6666                    if (DEBUG_PACKAGE_SCANNING) {
6667                        Log.d(TAG, "Examining " + pkg.codePath
6668                                + " and requiring known paths " + known.codePathString
6669                                + " & " + known.resourcePathString);
6670                    }
6671                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6672                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6673                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6674                                "Application package " + pkg.packageName
6675                                + " found at " + pkg.applicationInfo.getCodePath()
6676                                + " but expected at " + known.codePathString + "; ignoring.");
6677                    }
6678                }
6679            }
6680        }
6681
6682        // Initialize package source and resource directories
6683        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6684        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6685
6686        SharedUserSetting suid = null;
6687        PackageSetting pkgSetting = null;
6688
6689        if (!isSystemApp(pkg)) {
6690            // Only system apps can use these features.
6691            pkg.mOriginalPackages = null;
6692            pkg.mRealPackage = null;
6693            pkg.mAdoptPermissions = null;
6694        }
6695
6696        // writer
6697        synchronized (mPackages) {
6698            if (pkg.mSharedUserId != null) {
6699                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
6700                if (suid == null) {
6701                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6702                            "Creating application package " + pkg.packageName
6703                            + " for shared user failed");
6704                }
6705                if (DEBUG_PACKAGE_SCANNING) {
6706                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6707                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
6708                                + "): packages=" + suid.packages);
6709                }
6710            }
6711
6712            // Check if we are renaming from an original package name.
6713            PackageSetting origPackage = null;
6714            String realName = null;
6715            if (pkg.mOriginalPackages != null) {
6716                // This package may need to be renamed to a previously
6717                // installed name.  Let's check on that...
6718                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
6719                if (pkg.mOriginalPackages.contains(renamed)) {
6720                    // This package had originally been installed as the
6721                    // original name, and we have already taken care of
6722                    // transitioning to the new one.  Just update the new
6723                    // one to continue using the old name.
6724                    realName = pkg.mRealPackage;
6725                    if (!pkg.packageName.equals(renamed)) {
6726                        // Callers into this function may have already taken
6727                        // care of renaming the package; only do it here if
6728                        // it is not already done.
6729                        pkg.setPackageName(renamed);
6730                    }
6731
6732                } else {
6733                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
6734                        if ((origPackage = mSettings.peekPackageLPr(
6735                                pkg.mOriginalPackages.get(i))) != null) {
6736                            // We do have the package already installed under its
6737                            // original name...  should we use it?
6738                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
6739                                // New package is not compatible with original.
6740                                origPackage = null;
6741                                continue;
6742                            } else if (origPackage.sharedUser != null) {
6743                                // Make sure uid is compatible between packages.
6744                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
6745                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
6746                                            + " to " + pkg.packageName + ": old uid "
6747                                            + origPackage.sharedUser.name
6748                                            + " differs from " + pkg.mSharedUserId);
6749                                    origPackage = null;
6750                                    continue;
6751                                }
6752                            } else {
6753                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
6754                                        + pkg.packageName + " to old name " + origPackage.name);
6755                            }
6756                            break;
6757                        }
6758                    }
6759                }
6760            }
6761
6762            if (mTransferedPackages.contains(pkg.packageName)) {
6763                Slog.w(TAG, "Package " + pkg.packageName
6764                        + " was transferred to another, but its .apk remains");
6765            }
6766
6767            // Just create the setting, don't add it yet. For already existing packages
6768            // the PkgSetting exists already and doesn't have to be created.
6769            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6770                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6771                    pkg.applicationInfo.primaryCpuAbi,
6772                    pkg.applicationInfo.secondaryCpuAbi,
6773                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6774                    user, false);
6775            if (pkgSetting == null) {
6776                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6777                        "Creating application package " + pkg.packageName + " failed");
6778            }
6779
6780            if (pkgSetting.origPackage != null) {
6781                // If we are first transitioning from an original package,
6782                // fix up the new package's name now.  We need to do this after
6783                // looking up the package under its new name, so getPackageLP
6784                // can take care of fiddling things correctly.
6785                pkg.setPackageName(origPackage.name);
6786
6787                // File a report about this.
6788                String msg = "New package " + pkgSetting.realName
6789                        + " renamed to replace old package " + pkgSetting.name;
6790                reportSettingsProblem(Log.WARN, msg);
6791
6792                // Make a note of it.
6793                mTransferedPackages.add(origPackage.name);
6794
6795                // No longer need to retain this.
6796                pkgSetting.origPackage = null;
6797            }
6798
6799            if (realName != null) {
6800                // Make a note of it.
6801                mTransferedPackages.add(pkg.packageName);
6802            }
6803
6804            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6805                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6806            }
6807
6808            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6809                // Check all shared libraries and map to their actual file path.
6810                // We only do this here for apps not on a system dir, because those
6811                // are the only ones that can fail an install due to this.  We
6812                // will take care of the system apps by updating all of their
6813                // library paths after the scan is done.
6814                updateSharedLibrariesLPw(pkg, null);
6815            }
6816
6817            if (mFoundPolicyFile) {
6818                SELinuxMMAC.assignSeinfoValue(pkg);
6819            }
6820
6821            pkg.applicationInfo.uid = pkgSetting.appId;
6822            pkg.mExtras = pkgSetting;
6823            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
6824                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
6825                    // We just determined the app is signed correctly, so bring
6826                    // over the latest parsed certs.
6827                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6828                } else {
6829                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6830                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6831                                "Package " + pkg.packageName + " upgrade keys do not match the "
6832                                + "previously installed version");
6833                    } else {
6834                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
6835                        String msg = "System package " + pkg.packageName
6836                            + " signature changed; retaining data.";
6837                        reportSettingsProblem(Log.WARN, msg);
6838                    }
6839                }
6840            } else {
6841                try {
6842                    verifySignaturesLP(pkgSetting, pkg);
6843                    // We just determined the app is signed correctly, so bring
6844                    // over the latest parsed certs.
6845                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6846                } catch (PackageManagerException e) {
6847                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6848                        throw e;
6849                    }
6850                    // The signature has changed, but this package is in the system
6851                    // image...  let's recover!
6852                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6853                    // However...  if this package is part of a shared user, but it
6854                    // doesn't match the signature of the shared user, let's fail.
6855                    // What this means is that you can't change the signatures
6856                    // associated with an overall shared user, which doesn't seem all
6857                    // that unreasonable.
6858                    if (pkgSetting.sharedUser != null) {
6859                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6860                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6861                            throw new PackageManagerException(
6862                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6863                                            "Signature mismatch for shared user : "
6864                                            + pkgSetting.sharedUser);
6865                        }
6866                    }
6867                    // File a report about this.
6868                    String msg = "System package " + pkg.packageName
6869                        + " signature changed; retaining data.";
6870                    reportSettingsProblem(Log.WARN, msg);
6871                }
6872            }
6873            // Verify that this new package doesn't have any content providers
6874            // that conflict with existing packages.  Only do this if the
6875            // package isn't already installed, since we don't want to break
6876            // things that are installed.
6877            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6878                final int N = pkg.providers.size();
6879                int i;
6880                for (i=0; i<N; i++) {
6881                    PackageParser.Provider p = pkg.providers.get(i);
6882                    if (p.info.authority != null) {
6883                        String names[] = p.info.authority.split(";");
6884                        for (int j = 0; j < names.length; j++) {
6885                            if (mProvidersByAuthority.containsKey(names[j])) {
6886                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6887                                final String otherPackageName =
6888                                        ((other != null && other.getComponentName() != null) ?
6889                                                other.getComponentName().getPackageName() : "?");
6890                                throw new PackageManagerException(
6891                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6892                                                "Can't install because provider name " + names[j]
6893                                                + " (in package " + pkg.applicationInfo.packageName
6894                                                + ") is already used by " + otherPackageName);
6895                            }
6896                        }
6897                    }
6898                }
6899            }
6900
6901            if (pkg.mAdoptPermissions != null) {
6902                // This package wants to adopt ownership of permissions from
6903                // another package.
6904                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6905                    final String origName = pkg.mAdoptPermissions.get(i);
6906                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6907                    if (orig != null) {
6908                        if (verifyPackageUpdateLPr(orig, pkg)) {
6909                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6910                                    + pkg.packageName);
6911                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6912                        }
6913                    }
6914                }
6915            }
6916        }
6917
6918        final String pkgName = pkg.packageName;
6919
6920        final long scanFileTime = scanFile.lastModified();
6921        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6922        pkg.applicationInfo.processName = fixProcessName(
6923                pkg.applicationInfo.packageName,
6924                pkg.applicationInfo.processName,
6925                pkg.applicationInfo.uid);
6926
6927        File dataPath;
6928        if (mPlatformPackage == pkg) {
6929            // The system package is special.
6930            dataPath = new File(Environment.getDataDirectory(), "system");
6931
6932            pkg.applicationInfo.dataDir = dataPath.getPath();
6933
6934        } else {
6935            // This is a normal package, need to make its data directory.
6936            dataPath = Environment.getDataUserPackageDirectory(pkg.volumeUuid,
6937                    UserHandle.USER_SYSTEM, pkg.packageName);
6938
6939            boolean uidError = false;
6940            if (dataPath.exists()) {
6941                int currentUid = 0;
6942                try {
6943                    StructStat stat = Os.stat(dataPath.getPath());
6944                    currentUid = stat.st_uid;
6945                } catch (ErrnoException e) {
6946                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6947                }
6948
6949                // If we have mismatched owners for the data path, we have a problem.
6950                if (currentUid != pkg.applicationInfo.uid) {
6951                    boolean recovered = false;
6952                    if (currentUid == 0) {
6953                        // The directory somehow became owned by root.  Wow.
6954                        // This is probably because the system was stopped while
6955                        // installd was in the middle of messing with its libs
6956                        // directory.  Ask installd to fix that.
6957                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6958                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6959                        if (ret >= 0) {
6960                            recovered = true;
6961                            String msg = "Package " + pkg.packageName
6962                                    + " unexpectedly changed to uid 0; recovered to " +
6963                                    + pkg.applicationInfo.uid;
6964                            reportSettingsProblem(Log.WARN, msg);
6965                        }
6966                    }
6967                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6968                            || (scanFlags&SCAN_BOOTING) != 0)) {
6969                        // If this is a system app, we can at least delete its
6970                        // current data so the application will still work.
6971                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6972                        if (ret >= 0) {
6973                            // TODO: Kill the processes first
6974                            // Old data gone!
6975                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6976                                    ? "System package " : "Third party package ";
6977                            String msg = prefix + pkg.packageName
6978                                    + " has changed from uid: "
6979                                    + currentUid + " to "
6980                                    + pkg.applicationInfo.uid + "; old data erased";
6981                            reportSettingsProblem(Log.WARN, msg);
6982                            recovered = true;
6983
6984                            // And now re-install the app.
6985                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6986                                    pkg.applicationInfo.seinfo);
6987                            if (ret == -1) {
6988                                // Ack should not happen!
6989                                msg = prefix + pkg.packageName
6990                                        + " could not have data directory re-created after delete.";
6991                                reportSettingsProblem(Log.WARN, msg);
6992                                throw new PackageManagerException(
6993                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6994                            }
6995                        }
6996                        if (!recovered) {
6997                            mHasSystemUidErrors = true;
6998                        }
6999                    } else if (!recovered) {
7000                        // If we allow this install to proceed, we will be broken.
7001                        // Abort, abort!
7002                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7003                                "scanPackageLI");
7004                    }
7005                    if (!recovered) {
7006                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7007                            + pkg.applicationInfo.uid + "/fs_"
7008                            + currentUid;
7009                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7010                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7011                        String msg = "Package " + pkg.packageName
7012                                + " has mismatched uid: "
7013                                + currentUid + " on disk, "
7014                                + pkg.applicationInfo.uid + " in settings";
7015                        // writer
7016                        synchronized (mPackages) {
7017                            mSettings.mReadMessages.append(msg);
7018                            mSettings.mReadMessages.append('\n');
7019                            uidError = true;
7020                            if (!pkgSetting.uidError) {
7021                                reportSettingsProblem(Log.ERROR, msg);
7022                            }
7023                        }
7024                    }
7025                }
7026                pkg.applicationInfo.dataDir = dataPath.getPath();
7027                if (mShouldRestoreconData) {
7028                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7029                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7030                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7031                }
7032            } else {
7033                if (DEBUG_PACKAGE_SCANNING) {
7034                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7035                        Log.v(TAG, "Want this data dir: " + dataPath);
7036                }
7037                //invoke installer to do the actual installation
7038                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7039                        pkg.applicationInfo.seinfo);
7040                if (ret < 0) {
7041                    // Error from installer
7042                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7043                            "Unable to create data dirs [errorCode=" + ret + "]");
7044                }
7045
7046                if (dataPath.exists()) {
7047                    pkg.applicationInfo.dataDir = dataPath.getPath();
7048                } else {
7049                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
7050                    pkg.applicationInfo.dataDir = null;
7051                }
7052            }
7053
7054            pkgSetting.uidError = uidError;
7055        }
7056
7057        final String path = scanFile.getPath();
7058        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7059
7060        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7061            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7062
7063            // Some system apps still use directory structure for native libraries
7064            // in which case we might end up not detecting abi solely based on apk
7065            // structure. Try to detect abi based on directory structure.
7066            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7067                    pkg.applicationInfo.primaryCpuAbi == null) {
7068                setBundledAppAbisAndRoots(pkg, pkgSetting);
7069                setNativeLibraryPaths(pkg);
7070            }
7071
7072        } else {
7073            if ((scanFlags & SCAN_MOVE) != 0) {
7074                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7075                // but we already have this packages package info in the PackageSetting. We just
7076                // use that and derive the native library path based on the new codepath.
7077                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7078                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7079            }
7080
7081            // Set native library paths again. For moves, the path will be updated based on the
7082            // ABIs we've determined above. For non-moves, the path will be updated based on the
7083            // ABIs we determined during compilation, but the path will depend on the final
7084            // package path (after the rename away from the stage path).
7085            setNativeLibraryPaths(pkg);
7086        }
7087
7088        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7089        final int[] userIds = sUserManager.getUserIds();
7090        synchronized (mInstallLock) {
7091            // Make sure all user data directories are ready to roll; we're okay
7092            // if they already exist
7093            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7094                for (int userId : userIds) {
7095                    if (userId != UserHandle.USER_SYSTEM) {
7096                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7097                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7098                                pkg.applicationInfo.seinfo);
7099                    }
7100                }
7101            }
7102
7103            // Create a native library symlink only if we have native libraries
7104            // and if the native libraries are 32 bit libraries. We do not provide
7105            // this symlink for 64 bit libraries.
7106            if (pkg.applicationInfo.primaryCpuAbi != null &&
7107                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7108                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7109                try {
7110                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7111                    for (int userId : userIds) {
7112                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7113                                nativeLibPath, userId) < 0) {
7114                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7115                                    "Failed linking native library dir (user=" + userId + ")");
7116                        }
7117                    }
7118                } finally {
7119                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7120                }
7121            }
7122        }
7123
7124        // This is a special case for the "system" package, where the ABI is
7125        // dictated by the zygote configuration (and init.rc). We should keep track
7126        // of this ABI so that we can deal with "normal" applications that run under
7127        // the same UID correctly.
7128        if (mPlatformPackage == pkg) {
7129            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7130                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7131        }
7132
7133        // If there's a mismatch between the abi-override in the package setting
7134        // and the abiOverride specified for the install. Warn about this because we
7135        // would've already compiled the app without taking the package setting into
7136        // account.
7137        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7138            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7139                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7140                        " for package: " + pkg.packageName);
7141            }
7142        }
7143
7144        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7145        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7146        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7147
7148        // Copy the derived override back to the parsed package, so that we can
7149        // update the package settings accordingly.
7150        pkg.cpuAbiOverride = cpuAbiOverride;
7151
7152        if (DEBUG_ABI_SELECTION) {
7153            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7154                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7155                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7156        }
7157
7158        // Push the derived path down into PackageSettings so we know what to
7159        // clean up at uninstall time.
7160        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7161
7162        if (DEBUG_ABI_SELECTION) {
7163            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7164                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7165                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7166        }
7167
7168        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7169            // We don't do this here during boot because we can do it all
7170            // at once after scanning all existing packages.
7171            //
7172            // We also do this *before* we perform dexopt on this package, so that
7173            // we can avoid redundant dexopts, and also to make sure we've got the
7174            // code and package path correct.
7175            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7176                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, true /* boot complete */);
7177        }
7178
7179        if ((scanFlags & SCAN_NO_DEX) == 0) {
7180            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7181
7182            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
7183                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */,
7184                    (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/);
7185
7186            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7187            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7188                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
7189            }
7190        }
7191        if (mFactoryTest && pkg.requestedPermissions.contains(
7192                android.Manifest.permission.FACTORY_TEST)) {
7193            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7194        }
7195
7196        ArrayList<PackageParser.Package> clientLibPkgs = null;
7197
7198        // writer
7199        synchronized (mPackages) {
7200            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7201                // Only system apps can add new shared libraries.
7202                if (pkg.libraryNames != null) {
7203                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7204                        String name = pkg.libraryNames.get(i);
7205                        boolean allowed = false;
7206                        if (pkg.isUpdatedSystemApp()) {
7207                            // New library entries can only be added through the
7208                            // system image.  This is important to get rid of a lot
7209                            // of nasty edge cases: for example if we allowed a non-
7210                            // system update of the app to add a library, then uninstalling
7211                            // the update would make the library go away, and assumptions
7212                            // we made such as through app install filtering would now
7213                            // have allowed apps on the device which aren't compatible
7214                            // with it.  Better to just have the restriction here, be
7215                            // conservative, and create many fewer cases that can negatively
7216                            // impact the user experience.
7217                            final PackageSetting sysPs = mSettings
7218                                    .getDisabledSystemPkgLPr(pkg.packageName);
7219                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7220                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7221                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7222                                        allowed = true;
7223                                        break;
7224                                    }
7225                                }
7226                            }
7227                        } else {
7228                            allowed = true;
7229                        }
7230                        if (allowed) {
7231                            if (!mSharedLibraries.containsKey(name)) {
7232                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7233                            } else if (!name.equals(pkg.packageName)) {
7234                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7235                                        + name + " already exists; skipping");
7236                            }
7237                        } else {
7238                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7239                                    + name + " that is not declared on system image; skipping");
7240                        }
7241                    }
7242                    if ((scanFlags&SCAN_BOOTING) == 0) {
7243                        // If we are not booting, we need to update any applications
7244                        // that are clients of our shared library.  If we are booting,
7245                        // this will all be done once the scan is complete.
7246                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7247                    }
7248                }
7249            }
7250        }
7251
7252        // We also need to dexopt any apps that are dependent on this library.  Note that
7253        // if these fail, we should abort the install since installing the library will
7254        // result in some apps being broken.
7255        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7256        try {
7257            if (clientLibPkgs != null) {
7258                if ((scanFlags & SCAN_NO_DEX) == 0) {
7259                    for (int i = 0; i < clientLibPkgs.size(); i++) {
7260                        PackageParser.Package clientPkg = clientLibPkgs.get(i);
7261                        int result = mPackageDexOptimizer.performDexOpt(clientPkg,
7262                                null /* instruction sets */, forceDex,
7263                                (scanFlags & SCAN_DEFER_DEX) != 0, false,
7264                                (scanFlags & SCAN_BOOTING) == 0, false /*useJit*/);
7265                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7266                            throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
7267                                    "scanPackageLI failed to dexopt clientLibPkgs");
7268                        }
7269                    }
7270                }
7271            }
7272        } finally {
7273            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7274        }
7275
7276        // Request the ActivityManager to kill the process(only for existing packages)
7277        // so that we do not end up in a confused state while the user is still using the older
7278        // version of the application while the new one gets installed.
7279        if ((scanFlags & SCAN_REPLACING) != 0) {
7280            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7281
7282            killApplication(pkg.applicationInfo.packageName,
7283                        pkg.applicationInfo.uid, "replace pkg");
7284
7285            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7286        }
7287
7288        // Also need to kill any apps that are dependent on the library.
7289        if (clientLibPkgs != null) {
7290            for (int i=0; i<clientLibPkgs.size(); i++) {
7291                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7292                killApplication(clientPkg.applicationInfo.packageName,
7293                        clientPkg.applicationInfo.uid, "update lib");
7294            }
7295        }
7296
7297        // Make sure we're not adding any bogus keyset info
7298        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7299        ksms.assertScannedPackageValid(pkg);
7300
7301        // writer
7302        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7303
7304        boolean createIdmapFailed = false;
7305        synchronized (mPackages) {
7306            // We don't expect installation to fail beyond this point
7307
7308            // Add the new setting to mSettings
7309            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7310            // Add the new setting to mPackages
7311            mPackages.put(pkg.applicationInfo.packageName, pkg);
7312            // Make sure we don't accidentally delete its data.
7313            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7314            while (iter.hasNext()) {
7315                PackageCleanItem item = iter.next();
7316                if (pkgName.equals(item.packageName)) {
7317                    iter.remove();
7318                }
7319            }
7320
7321            // Take care of first install / last update times.
7322            if (currentTime != 0) {
7323                if (pkgSetting.firstInstallTime == 0) {
7324                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7325                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7326                    pkgSetting.lastUpdateTime = currentTime;
7327                }
7328            } else if (pkgSetting.firstInstallTime == 0) {
7329                // We need *something*.  Take time time stamp of the file.
7330                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7331            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7332                if (scanFileTime != pkgSetting.timeStamp) {
7333                    // A package on the system image has changed; consider this
7334                    // to be an update.
7335                    pkgSetting.lastUpdateTime = scanFileTime;
7336                }
7337            }
7338
7339            // Add the package's KeySets to the global KeySetManagerService
7340            ksms.addScannedPackageLPw(pkg);
7341
7342            int N = pkg.providers.size();
7343            StringBuilder r = null;
7344            int i;
7345            for (i=0; i<N; i++) {
7346                PackageParser.Provider p = pkg.providers.get(i);
7347                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7348                        p.info.processName, pkg.applicationInfo.uid);
7349                mProviders.addProvider(p);
7350                p.syncable = p.info.isSyncable;
7351                if (p.info.authority != null) {
7352                    String names[] = p.info.authority.split(";");
7353                    p.info.authority = null;
7354                    for (int j = 0; j < names.length; j++) {
7355                        if (j == 1 && p.syncable) {
7356                            // We only want the first authority for a provider to possibly be
7357                            // syncable, so if we already added this provider using a different
7358                            // authority clear the syncable flag. We copy the provider before
7359                            // changing it because the mProviders object contains a reference
7360                            // to a provider that we don't want to change.
7361                            // Only do this for the second authority since the resulting provider
7362                            // object can be the same for all future authorities for this provider.
7363                            p = new PackageParser.Provider(p);
7364                            p.syncable = false;
7365                        }
7366                        if (!mProvidersByAuthority.containsKey(names[j])) {
7367                            mProvidersByAuthority.put(names[j], p);
7368                            if (p.info.authority == null) {
7369                                p.info.authority = names[j];
7370                            } else {
7371                                p.info.authority = p.info.authority + ";" + names[j];
7372                            }
7373                            if (DEBUG_PACKAGE_SCANNING) {
7374                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7375                                    Log.d(TAG, "Registered content provider: " + names[j]
7376                                            + ", className = " + p.info.name + ", isSyncable = "
7377                                            + p.info.isSyncable);
7378                            }
7379                        } else {
7380                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7381                            Slog.w(TAG, "Skipping provider name " + names[j] +
7382                                    " (in package " + pkg.applicationInfo.packageName +
7383                                    "): name already used by "
7384                                    + ((other != null && other.getComponentName() != null)
7385                                            ? other.getComponentName().getPackageName() : "?"));
7386                        }
7387                    }
7388                }
7389                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7390                    if (r == null) {
7391                        r = new StringBuilder(256);
7392                    } else {
7393                        r.append(' ');
7394                    }
7395                    r.append(p.info.name);
7396                }
7397            }
7398            if (r != null) {
7399                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7400            }
7401
7402            N = pkg.services.size();
7403            r = null;
7404            for (i=0; i<N; i++) {
7405                PackageParser.Service s = pkg.services.get(i);
7406                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7407                        s.info.processName, pkg.applicationInfo.uid);
7408                mServices.addService(s);
7409                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7410                    if (r == null) {
7411                        r = new StringBuilder(256);
7412                    } else {
7413                        r.append(' ');
7414                    }
7415                    r.append(s.info.name);
7416                }
7417            }
7418            if (r != null) {
7419                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7420            }
7421
7422            N = pkg.receivers.size();
7423            r = null;
7424            for (i=0; i<N; i++) {
7425                PackageParser.Activity a = pkg.receivers.get(i);
7426                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7427                        a.info.processName, pkg.applicationInfo.uid);
7428                mReceivers.addActivity(a, "receiver");
7429                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7430                    if (r == null) {
7431                        r = new StringBuilder(256);
7432                    } else {
7433                        r.append(' ');
7434                    }
7435                    r.append(a.info.name);
7436                }
7437            }
7438            if (r != null) {
7439                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7440            }
7441
7442            N = pkg.activities.size();
7443            r = null;
7444            for (i=0; i<N; i++) {
7445                PackageParser.Activity a = pkg.activities.get(i);
7446                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7447                        a.info.processName, pkg.applicationInfo.uid);
7448                mActivities.addActivity(a, "activity");
7449                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7450                    if (r == null) {
7451                        r = new StringBuilder(256);
7452                    } else {
7453                        r.append(' ');
7454                    }
7455                    r.append(a.info.name);
7456                }
7457            }
7458            if (r != null) {
7459                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7460            }
7461
7462            N = pkg.permissionGroups.size();
7463            r = null;
7464            for (i=0; i<N; i++) {
7465                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7466                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7467                if (cur == null) {
7468                    mPermissionGroups.put(pg.info.name, pg);
7469                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7470                        if (r == null) {
7471                            r = new StringBuilder(256);
7472                        } else {
7473                            r.append(' ');
7474                        }
7475                        r.append(pg.info.name);
7476                    }
7477                } else {
7478                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7479                            + pg.info.packageName + " ignored: original from "
7480                            + cur.info.packageName);
7481                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7482                        if (r == null) {
7483                            r = new StringBuilder(256);
7484                        } else {
7485                            r.append(' ');
7486                        }
7487                        r.append("DUP:");
7488                        r.append(pg.info.name);
7489                    }
7490                }
7491            }
7492            if (r != null) {
7493                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7494            }
7495
7496            N = pkg.permissions.size();
7497            r = null;
7498            for (i=0; i<N; i++) {
7499                PackageParser.Permission p = pkg.permissions.get(i);
7500
7501                // Assume by default that we did not install this permission into the system.
7502                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7503
7504                // Now that permission groups have a special meaning, we ignore permission
7505                // groups for legacy apps to prevent unexpected behavior. In particular,
7506                // permissions for one app being granted to someone just becuase they happen
7507                // to be in a group defined by another app (before this had no implications).
7508                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7509                    p.group = mPermissionGroups.get(p.info.group);
7510                    // Warn for a permission in an unknown group.
7511                    if (p.info.group != null && p.group == null) {
7512                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7513                                + p.info.packageName + " in an unknown group " + p.info.group);
7514                    }
7515                }
7516
7517                ArrayMap<String, BasePermission> permissionMap =
7518                        p.tree ? mSettings.mPermissionTrees
7519                                : mSettings.mPermissions;
7520                BasePermission bp = permissionMap.get(p.info.name);
7521
7522                // Allow system apps to redefine non-system permissions
7523                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7524                    final boolean currentOwnerIsSystem = (bp.perm != null
7525                            && isSystemApp(bp.perm.owner));
7526                    if (isSystemApp(p.owner)) {
7527                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7528                            // It's a built-in permission and no owner, take ownership now
7529                            bp.packageSetting = pkgSetting;
7530                            bp.perm = p;
7531                            bp.uid = pkg.applicationInfo.uid;
7532                            bp.sourcePackage = p.info.packageName;
7533                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7534                        } else if (!currentOwnerIsSystem) {
7535                            String msg = "New decl " + p.owner + " of permission  "
7536                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7537                            reportSettingsProblem(Log.WARN, msg);
7538                            bp = null;
7539                        }
7540                    }
7541                }
7542
7543                if (bp == null) {
7544                    bp = new BasePermission(p.info.name, p.info.packageName,
7545                            BasePermission.TYPE_NORMAL);
7546                    permissionMap.put(p.info.name, bp);
7547                }
7548
7549                if (bp.perm == null) {
7550                    if (bp.sourcePackage == null
7551                            || bp.sourcePackage.equals(p.info.packageName)) {
7552                        BasePermission tree = findPermissionTreeLP(p.info.name);
7553                        if (tree == null
7554                                || tree.sourcePackage.equals(p.info.packageName)) {
7555                            bp.packageSetting = pkgSetting;
7556                            bp.perm = p;
7557                            bp.uid = pkg.applicationInfo.uid;
7558                            bp.sourcePackage = p.info.packageName;
7559                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7560                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7561                                if (r == null) {
7562                                    r = new StringBuilder(256);
7563                                } else {
7564                                    r.append(' ');
7565                                }
7566                                r.append(p.info.name);
7567                            }
7568                        } else {
7569                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7570                                    + p.info.packageName + " ignored: base tree "
7571                                    + tree.name + " is from package "
7572                                    + tree.sourcePackage);
7573                        }
7574                    } else {
7575                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7576                                + p.info.packageName + " ignored: original from "
7577                                + bp.sourcePackage);
7578                    }
7579                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7580                    if (r == null) {
7581                        r = new StringBuilder(256);
7582                    } else {
7583                        r.append(' ');
7584                    }
7585                    r.append("DUP:");
7586                    r.append(p.info.name);
7587                }
7588                if (bp.perm == p) {
7589                    bp.protectionLevel = p.info.protectionLevel;
7590                }
7591            }
7592
7593            if (r != null) {
7594                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7595            }
7596
7597            N = pkg.instrumentation.size();
7598            r = null;
7599            for (i=0; i<N; i++) {
7600                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7601                a.info.packageName = pkg.applicationInfo.packageName;
7602                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7603                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7604                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7605                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7606                a.info.dataDir = pkg.applicationInfo.dataDir;
7607
7608                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7609                // need other information about the application, like the ABI and what not ?
7610                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7611                mInstrumentation.put(a.getComponentName(), a);
7612                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7613                    if (r == null) {
7614                        r = new StringBuilder(256);
7615                    } else {
7616                        r.append(' ');
7617                    }
7618                    r.append(a.info.name);
7619                }
7620            }
7621            if (r != null) {
7622                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7623            }
7624
7625            if (pkg.protectedBroadcasts != null) {
7626                N = pkg.protectedBroadcasts.size();
7627                for (i=0; i<N; i++) {
7628                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7629                }
7630            }
7631
7632            pkgSetting.setTimeStamp(scanFileTime);
7633
7634            // Create idmap files for pairs of (packages, overlay packages).
7635            // Note: "android", ie framework-res.apk, is handled by native layers.
7636            if (pkg.mOverlayTarget != null) {
7637                // This is an overlay package.
7638                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7639                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7640                        mOverlays.put(pkg.mOverlayTarget,
7641                                new ArrayMap<String, PackageParser.Package>());
7642                    }
7643                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7644                    map.put(pkg.packageName, pkg);
7645                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7646                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7647                        createIdmapFailed = true;
7648                    }
7649                }
7650            } else if (mOverlays.containsKey(pkg.packageName) &&
7651                    !pkg.packageName.equals("android")) {
7652                // This is a regular package, with one or more known overlay packages.
7653                createIdmapsForPackageLI(pkg);
7654            }
7655        }
7656
7657        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7658
7659        if (createIdmapFailed) {
7660            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7661                    "scanPackageLI failed to createIdmap");
7662        }
7663        return pkg;
7664    }
7665
7666    /**
7667     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7668     * is derived purely on the basis of the contents of {@code scanFile} and
7669     * {@code cpuAbiOverride}.
7670     *
7671     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7672     */
7673    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7674                                 String cpuAbiOverride, boolean extractLibs)
7675            throws PackageManagerException {
7676        // TODO: We can probably be smarter about this stuff. For installed apps,
7677        // we can calculate this information at install time once and for all. For
7678        // system apps, we can probably assume that this information doesn't change
7679        // after the first boot scan. As things stand, we do lots of unnecessary work.
7680
7681        // Give ourselves some initial paths; we'll come back for another
7682        // pass once we've determined ABI below.
7683        setNativeLibraryPaths(pkg);
7684
7685        // We would never need to extract libs for forward-locked and external packages,
7686        // since the container service will do it for us. We shouldn't attempt to
7687        // extract libs from system app when it was not updated.
7688        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7689                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7690            extractLibs = false;
7691        }
7692
7693        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7694        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7695
7696        NativeLibraryHelper.Handle handle = null;
7697        try {
7698            handle = NativeLibraryHelper.Handle.create(pkg);
7699            // TODO(multiArch): This can be null for apps that didn't go through the
7700            // usual installation process. We can calculate it again, like we
7701            // do during install time.
7702            //
7703            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7704            // unnecessary.
7705            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7706
7707            // Null out the abis so that they can be recalculated.
7708            pkg.applicationInfo.primaryCpuAbi = null;
7709            pkg.applicationInfo.secondaryCpuAbi = null;
7710            if (isMultiArch(pkg.applicationInfo)) {
7711                // Warn if we've set an abiOverride for multi-lib packages..
7712                // By definition, we need to copy both 32 and 64 bit libraries for
7713                // such packages.
7714                if (pkg.cpuAbiOverride != null
7715                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7716                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7717                }
7718
7719                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7720                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7721                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7722                    if (extractLibs) {
7723                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7724                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7725                                useIsaSpecificSubdirs);
7726                    } else {
7727                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7728                    }
7729                }
7730
7731                maybeThrowExceptionForMultiArchCopy(
7732                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7733
7734                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7735                    if (extractLibs) {
7736                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7737                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7738                                useIsaSpecificSubdirs);
7739                    } else {
7740                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7741                    }
7742                }
7743
7744                maybeThrowExceptionForMultiArchCopy(
7745                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7746
7747                if (abi64 >= 0) {
7748                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7749                }
7750
7751                if (abi32 >= 0) {
7752                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
7753                    if (abi64 >= 0) {
7754                        pkg.applicationInfo.secondaryCpuAbi = abi;
7755                    } else {
7756                        pkg.applicationInfo.primaryCpuAbi = abi;
7757                    }
7758                }
7759            } else {
7760                String[] abiList = (cpuAbiOverride != null) ?
7761                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
7762
7763                // Enable gross and lame hacks for apps that are built with old
7764                // SDK tools. We must scan their APKs for renderscript bitcode and
7765                // not launch them if it's present. Don't bother checking on devices
7766                // that don't have 64 bit support.
7767                boolean needsRenderScriptOverride = false;
7768                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
7769                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
7770                    abiList = Build.SUPPORTED_32_BIT_ABIS;
7771                    needsRenderScriptOverride = true;
7772                }
7773
7774                final int copyRet;
7775                if (extractLibs) {
7776                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7777                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
7778                } else {
7779                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
7780                }
7781
7782                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
7783                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7784                            "Error unpackaging native libs for app, errorCode=" + copyRet);
7785                }
7786
7787                if (copyRet >= 0) {
7788                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
7789                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
7790                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
7791                } else if (needsRenderScriptOverride) {
7792                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
7793                }
7794            }
7795        } catch (IOException ioe) {
7796            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
7797        } finally {
7798            IoUtils.closeQuietly(handle);
7799        }
7800
7801        // Now that we've calculated the ABIs and determined if it's an internal app,
7802        // we will go ahead and populate the nativeLibraryPath.
7803        setNativeLibraryPaths(pkg);
7804    }
7805
7806    /**
7807     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
7808     * i.e, so that all packages can be run inside a single process if required.
7809     *
7810     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
7811     * this function will either try and make the ABI for all packages in {@code packagesForUser}
7812     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
7813     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
7814     * updating a package that belongs to a shared user.
7815     *
7816     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
7817     * adds unnecessary complexity.
7818     */
7819    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
7820            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt,
7821            boolean bootComplete) {
7822        String requiredInstructionSet = null;
7823        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
7824            requiredInstructionSet = VMRuntime.getInstructionSet(
7825                     scannedPackage.applicationInfo.primaryCpuAbi);
7826        }
7827
7828        PackageSetting requirer = null;
7829        for (PackageSetting ps : packagesForUser) {
7830            // If packagesForUser contains scannedPackage, we skip it. This will happen
7831            // when scannedPackage is an update of an existing package. Without this check,
7832            // we will never be able to change the ABI of any package belonging to a shared
7833            // user, even if it's compatible with other packages.
7834            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7835                if (ps.primaryCpuAbiString == null) {
7836                    continue;
7837                }
7838
7839                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7840                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7841                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7842                    // this but there's not much we can do.
7843                    String errorMessage = "Instruction set mismatch, "
7844                            + ((requirer == null) ? "[caller]" : requirer)
7845                            + " requires " + requiredInstructionSet + " whereas " + ps
7846                            + " requires " + instructionSet;
7847                    Slog.w(TAG, errorMessage);
7848                }
7849
7850                if (requiredInstructionSet == null) {
7851                    requiredInstructionSet = instructionSet;
7852                    requirer = ps;
7853                }
7854            }
7855        }
7856
7857        if (requiredInstructionSet != null) {
7858            String adjustedAbi;
7859            if (requirer != null) {
7860                // requirer != null implies that either scannedPackage was null or that scannedPackage
7861                // did not require an ABI, in which case we have to adjust scannedPackage to match
7862                // the ABI of the set (which is the same as requirer's ABI)
7863                adjustedAbi = requirer.primaryCpuAbiString;
7864                if (scannedPackage != null) {
7865                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7866                }
7867            } else {
7868                // requirer == null implies that we're updating all ABIs in the set to
7869                // match scannedPackage.
7870                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7871            }
7872
7873            for (PackageSetting ps : packagesForUser) {
7874                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7875                    if (ps.primaryCpuAbiString != null) {
7876                        continue;
7877                    }
7878
7879                    ps.primaryCpuAbiString = adjustedAbi;
7880                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7881                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7882                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7883
7884                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7885
7886                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7887                                null /* instruction sets */, forceDexOpt, deferDexOpt, true,
7888                                bootComplete, false /*useJit*/);
7889
7890                        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7891                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7892                            ps.primaryCpuAbiString = null;
7893                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7894                            return;
7895                        } else {
7896                            mInstaller.rmdex(ps.codePathString,
7897                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7898                        }
7899                    }
7900                }
7901            }
7902        }
7903    }
7904
7905    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7906        synchronized (mPackages) {
7907            mResolverReplaced = true;
7908            // Set up information for custom user intent resolution activity.
7909            mResolveActivity.applicationInfo = pkg.applicationInfo;
7910            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7911            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7912            mResolveActivity.processName = pkg.applicationInfo.packageName;
7913            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7914            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7915                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7916            mResolveActivity.theme = 0;
7917            mResolveActivity.exported = true;
7918            mResolveActivity.enabled = true;
7919            mResolveInfo.activityInfo = mResolveActivity;
7920            mResolveInfo.priority = 0;
7921            mResolveInfo.preferredOrder = 0;
7922            mResolveInfo.match = 0;
7923            mResolveComponentName = mCustomResolverComponentName;
7924            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7925                    mResolveComponentName);
7926        }
7927    }
7928
7929    private static String calculateBundledApkRoot(final String codePathString) {
7930        final File codePath = new File(codePathString);
7931        final File codeRoot;
7932        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7933            codeRoot = Environment.getRootDirectory();
7934        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7935            codeRoot = Environment.getOemDirectory();
7936        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7937            codeRoot = Environment.getVendorDirectory();
7938        } else {
7939            // Unrecognized code path; take its top real segment as the apk root:
7940            // e.g. /something/app/blah.apk => /something
7941            try {
7942                File f = codePath.getCanonicalFile();
7943                File parent = f.getParentFile();    // non-null because codePath is a file
7944                File tmp;
7945                while ((tmp = parent.getParentFile()) != null) {
7946                    f = parent;
7947                    parent = tmp;
7948                }
7949                codeRoot = f;
7950                Slog.w(TAG, "Unrecognized code path "
7951                        + codePath + " - using " + codeRoot);
7952            } catch (IOException e) {
7953                // Can't canonicalize the code path -- shenanigans?
7954                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7955                return Environment.getRootDirectory().getPath();
7956            }
7957        }
7958        return codeRoot.getPath();
7959    }
7960
7961    /**
7962     * Derive and set the location of native libraries for the given package,
7963     * which varies depending on where and how the package was installed.
7964     */
7965    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7966        final ApplicationInfo info = pkg.applicationInfo;
7967        final String codePath = pkg.codePath;
7968        final File codeFile = new File(codePath);
7969        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7970        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
7971
7972        info.nativeLibraryRootDir = null;
7973        info.nativeLibraryRootRequiresIsa = false;
7974        info.nativeLibraryDir = null;
7975        info.secondaryNativeLibraryDir = null;
7976
7977        if (isApkFile(codeFile)) {
7978            // Monolithic install
7979            if (bundledApp) {
7980                // If "/system/lib64/apkname" exists, assume that is the per-package
7981                // native library directory to use; otherwise use "/system/lib/apkname".
7982                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7983                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7984                        getPrimaryInstructionSet(info));
7985
7986                // This is a bundled system app so choose the path based on the ABI.
7987                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7988                // is just the default path.
7989                final String apkName = deriveCodePathName(codePath);
7990                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7991                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7992                        apkName).getAbsolutePath();
7993
7994                if (info.secondaryCpuAbi != null) {
7995                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7996                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7997                            secondaryLibDir, apkName).getAbsolutePath();
7998                }
7999            } else if (asecApp) {
8000                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8001                        .getAbsolutePath();
8002            } else {
8003                final String apkName = deriveCodePathName(codePath);
8004                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8005                        .getAbsolutePath();
8006            }
8007
8008            info.nativeLibraryRootRequiresIsa = false;
8009            info.nativeLibraryDir = info.nativeLibraryRootDir;
8010        } else {
8011            // Cluster install
8012            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8013            info.nativeLibraryRootRequiresIsa = true;
8014
8015            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8016                    getPrimaryInstructionSet(info)).getAbsolutePath();
8017
8018            if (info.secondaryCpuAbi != null) {
8019                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8020                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8021            }
8022        }
8023    }
8024
8025    /**
8026     * Calculate the abis and roots for a bundled app. These can uniquely
8027     * be determined from the contents of the system partition, i.e whether
8028     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8029     * of this information, and instead assume that the system was built
8030     * sensibly.
8031     */
8032    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8033                                           PackageSetting pkgSetting) {
8034        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8035
8036        // If "/system/lib64/apkname" exists, assume that is the per-package
8037        // native library directory to use; otherwise use "/system/lib/apkname".
8038        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8039        setBundledAppAbi(pkg, apkRoot, apkName);
8040        // pkgSetting might be null during rescan following uninstall of updates
8041        // to a bundled app, so accommodate that possibility.  The settings in
8042        // that case will be established later from the parsed package.
8043        //
8044        // If the settings aren't null, sync them up with what we've just derived.
8045        // note that apkRoot isn't stored in the package settings.
8046        if (pkgSetting != null) {
8047            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8048            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8049        }
8050    }
8051
8052    /**
8053     * Deduces the ABI of a bundled app and sets the relevant fields on the
8054     * parsed pkg object.
8055     *
8056     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8057     *        under which system libraries are installed.
8058     * @param apkName the name of the installed package.
8059     */
8060    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8061        final File codeFile = new File(pkg.codePath);
8062
8063        final boolean has64BitLibs;
8064        final boolean has32BitLibs;
8065        if (isApkFile(codeFile)) {
8066            // Monolithic install
8067            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8068            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8069        } else {
8070            // Cluster install
8071            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8072            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8073                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8074                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8075                has64BitLibs = (new File(rootDir, isa)).exists();
8076            } else {
8077                has64BitLibs = false;
8078            }
8079            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8080                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8081                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8082                has32BitLibs = (new File(rootDir, isa)).exists();
8083            } else {
8084                has32BitLibs = false;
8085            }
8086        }
8087
8088        if (has64BitLibs && !has32BitLibs) {
8089            // The package has 64 bit libs, but not 32 bit libs. Its primary
8090            // ABI should be 64 bit. We can safely assume here that the bundled
8091            // native libraries correspond to the most preferred ABI in the list.
8092
8093            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8094            pkg.applicationInfo.secondaryCpuAbi = null;
8095        } else if (has32BitLibs && !has64BitLibs) {
8096            // The package has 32 bit libs but not 64 bit libs. Its primary
8097            // ABI should be 32 bit.
8098
8099            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8100            pkg.applicationInfo.secondaryCpuAbi = null;
8101        } else if (has32BitLibs && has64BitLibs) {
8102            // The application has both 64 and 32 bit bundled libraries. We check
8103            // here that the app declares multiArch support, and warn if it doesn't.
8104            //
8105            // We will be lenient here and record both ABIs. The primary will be the
8106            // ABI that's higher on the list, i.e, a device that's configured to prefer
8107            // 64 bit apps will see a 64 bit primary ABI,
8108
8109            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8110                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
8111            }
8112
8113            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8114                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8115                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8116            } else {
8117                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8118                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8119            }
8120        } else {
8121            pkg.applicationInfo.primaryCpuAbi = null;
8122            pkg.applicationInfo.secondaryCpuAbi = null;
8123        }
8124    }
8125
8126    private void killApplication(String pkgName, int appId, String reason) {
8127        // Request the ActivityManager to kill the process(only for existing packages)
8128        // so that we do not end up in a confused state while the user is still using the older
8129        // version of the application while the new one gets installed.
8130        IActivityManager am = ActivityManagerNative.getDefault();
8131        if (am != null) {
8132            try {
8133                am.killApplicationWithAppId(pkgName, appId, reason);
8134            } catch (RemoteException e) {
8135            }
8136        }
8137    }
8138
8139    void removePackageLI(PackageSetting ps, boolean chatty) {
8140        if (DEBUG_INSTALL) {
8141            if (chatty)
8142                Log.d(TAG, "Removing package " + ps.name);
8143        }
8144
8145        // writer
8146        synchronized (mPackages) {
8147            mPackages.remove(ps.name);
8148            final PackageParser.Package pkg = ps.pkg;
8149            if (pkg != null) {
8150                cleanPackageDataStructuresLILPw(pkg, chatty);
8151            }
8152        }
8153    }
8154
8155    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8156        if (DEBUG_INSTALL) {
8157            if (chatty)
8158                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8159        }
8160
8161        // writer
8162        synchronized (mPackages) {
8163            mPackages.remove(pkg.applicationInfo.packageName);
8164            cleanPackageDataStructuresLILPw(pkg, chatty);
8165        }
8166    }
8167
8168    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8169        int N = pkg.providers.size();
8170        StringBuilder r = null;
8171        int i;
8172        for (i=0; i<N; i++) {
8173            PackageParser.Provider p = pkg.providers.get(i);
8174            mProviders.removeProvider(p);
8175            if (p.info.authority == null) {
8176
8177                /* There was another ContentProvider with this authority when
8178                 * this app was installed so this authority is null,
8179                 * Ignore it as we don't have to unregister the provider.
8180                 */
8181                continue;
8182            }
8183            String names[] = p.info.authority.split(";");
8184            for (int j = 0; j < names.length; j++) {
8185                if (mProvidersByAuthority.get(names[j]) == p) {
8186                    mProvidersByAuthority.remove(names[j]);
8187                    if (DEBUG_REMOVE) {
8188                        if (chatty)
8189                            Log.d(TAG, "Unregistered content provider: " + names[j]
8190                                    + ", className = " + p.info.name + ", isSyncable = "
8191                                    + p.info.isSyncable);
8192                    }
8193                }
8194            }
8195            if (DEBUG_REMOVE && chatty) {
8196                if (r == null) {
8197                    r = new StringBuilder(256);
8198                } else {
8199                    r.append(' ');
8200                }
8201                r.append(p.info.name);
8202            }
8203        }
8204        if (r != null) {
8205            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8206        }
8207
8208        N = pkg.services.size();
8209        r = null;
8210        for (i=0; i<N; i++) {
8211            PackageParser.Service s = pkg.services.get(i);
8212            mServices.removeService(s);
8213            if (chatty) {
8214                if (r == null) {
8215                    r = new StringBuilder(256);
8216                } else {
8217                    r.append(' ');
8218                }
8219                r.append(s.info.name);
8220            }
8221        }
8222        if (r != null) {
8223            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8224        }
8225
8226        N = pkg.receivers.size();
8227        r = null;
8228        for (i=0; i<N; i++) {
8229            PackageParser.Activity a = pkg.receivers.get(i);
8230            mReceivers.removeActivity(a, "receiver");
8231            if (DEBUG_REMOVE && chatty) {
8232                if (r == null) {
8233                    r = new StringBuilder(256);
8234                } else {
8235                    r.append(' ');
8236                }
8237                r.append(a.info.name);
8238            }
8239        }
8240        if (r != null) {
8241            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8242        }
8243
8244        N = pkg.activities.size();
8245        r = null;
8246        for (i=0; i<N; i++) {
8247            PackageParser.Activity a = pkg.activities.get(i);
8248            mActivities.removeActivity(a, "activity");
8249            if (DEBUG_REMOVE && chatty) {
8250                if (r == null) {
8251                    r = new StringBuilder(256);
8252                } else {
8253                    r.append(' ');
8254                }
8255                r.append(a.info.name);
8256            }
8257        }
8258        if (r != null) {
8259            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8260        }
8261
8262        N = pkg.permissions.size();
8263        r = null;
8264        for (i=0; i<N; i++) {
8265            PackageParser.Permission p = pkg.permissions.get(i);
8266            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8267            if (bp == null) {
8268                bp = mSettings.mPermissionTrees.get(p.info.name);
8269            }
8270            if (bp != null && bp.perm == p) {
8271                bp.perm = null;
8272                if (DEBUG_REMOVE && chatty) {
8273                    if (r == null) {
8274                        r = new StringBuilder(256);
8275                    } else {
8276                        r.append(' ');
8277                    }
8278                    r.append(p.info.name);
8279                }
8280            }
8281            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8282                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
8283                if (appOpPerms != null) {
8284                    appOpPerms.remove(pkg.packageName);
8285                }
8286            }
8287        }
8288        if (r != null) {
8289            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8290        }
8291
8292        N = pkg.requestedPermissions.size();
8293        r = null;
8294        for (i=0; i<N; i++) {
8295            String perm = pkg.requestedPermissions.get(i);
8296            BasePermission bp = mSettings.mPermissions.get(perm);
8297            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8298                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
8299                if (appOpPerms != null) {
8300                    appOpPerms.remove(pkg.packageName);
8301                    if (appOpPerms.isEmpty()) {
8302                        mAppOpPermissionPackages.remove(perm);
8303                    }
8304                }
8305            }
8306        }
8307        if (r != null) {
8308            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8309        }
8310
8311        N = pkg.instrumentation.size();
8312        r = null;
8313        for (i=0; i<N; i++) {
8314            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8315            mInstrumentation.remove(a.getComponentName());
8316            if (DEBUG_REMOVE && chatty) {
8317                if (r == null) {
8318                    r = new StringBuilder(256);
8319                } else {
8320                    r.append(' ');
8321                }
8322                r.append(a.info.name);
8323            }
8324        }
8325        if (r != null) {
8326            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8327        }
8328
8329        r = null;
8330        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8331            // Only system apps can hold shared libraries.
8332            if (pkg.libraryNames != null) {
8333                for (i=0; i<pkg.libraryNames.size(); i++) {
8334                    String name = pkg.libraryNames.get(i);
8335                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8336                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8337                        mSharedLibraries.remove(name);
8338                        if (DEBUG_REMOVE && chatty) {
8339                            if (r == null) {
8340                                r = new StringBuilder(256);
8341                            } else {
8342                                r.append(' ');
8343                            }
8344                            r.append(name);
8345                        }
8346                    }
8347                }
8348            }
8349        }
8350        if (r != null) {
8351            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8352        }
8353    }
8354
8355    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8356        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8357            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8358                return true;
8359            }
8360        }
8361        return false;
8362    }
8363
8364    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8365    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8366    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8367
8368    private void updatePermissionsLPw(String changingPkg,
8369            PackageParser.Package pkgInfo, int flags) {
8370        // Make sure there are no dangling permission trees.
8371        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8372        while (it.hasNext()) {
8373            final BasePermission bp = it.next();
8374            if (bp.packageSetting == null) {
8375                // We may not yet have parsed the package, so just see if
8376                // we still know about its settings.
8377                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8378            }
8379            if (bp.packageSetting == null) {
8380                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8381                        + " from package " + bp.sourcePackage);
8382                it.remove();
8383            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8384                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8385                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8386                            + " from package " + bp.sourcePackage);
8387                    flags |= UPDATE_PERMISSIONS_ALL;
8388                    it.remove();
8389                }
8390            }
8391        }
8392
8393        // Make sure all dynamic permissions have been assigned to a package,
8394        // and make sure there are no dangling permissions.
8395        it = mSettings.mPermissions.values().iterator();
8396        while (it.hasNext()) {
8397            final BasePermission bp = it.next();
8398            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8399                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8400                        + bp.name + " pkg=" + bp.sourcePackage
8401                        + " info=" + bp.pendingInfo);
8402                if (bp.packageSetting == null && bp.pendingInfo != null) {
8403                    final BasePermission tree = findPermissionTreeLP(bp.name);
8404                    if (tree != null && tree.perm != null) {
8405                        bp.packageSetting = tree.packageSetting;
8406                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8407                                new PermissionInfo(bp.pendingInfo));
8408                        bp.perm.info.packageName = tree.perm.info.packageName;
8409                        bp.perm.info.name = bp.name;
8410                        bp.uid = tree.uid;
8411                    }
8412                }
8413            }
8414            if (bp.packageSetting == null) {
8415                // We may not yet have parsed the package, so just see if
8416                // we still know about its settings.
8417                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8418            }
8419            if (bp.packageSetting == null) {
8420                Slog.w(TAG, "Removing dangling permission: " + bp.name
8421                        + " from package " + bp.sourcePackage);
8422                it.remove();
8423            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8424                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8425                    Slog.i(TAG, "Removing old permission: " + bp.name
8426                            + " from package " + bp.sourcePackage);
8427                    flags |= UPDATE_PERMISSIONS_ALL;
8428                    it.remove();
8429                }
8430            }
8431        }
8432
8433        // Now update the permissions for all packages, in particular
8434        // replace the granted permissions of the system packages.
8435        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8436            for (PackageParser.Package pkg : mPackages.values()) {
8437                if (pkg != pkgInfo) {
8438                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
8439                            changingPkg);
8440                }
8441            }
8442        }
8443
8444        if (pkgInfo != null) {
8445            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
8446        }
8447    }
8448
8449    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8450            String packageOfInterest) {
8451        // IMPORTANT: There are two types of permissions: install and runtime.
8452        // Install time permissions are granted when the app is installed to
8453        // all device users and users added in the future. Runtime permissions
8454        // are granted at runtime explicitly to specific users. Normal and signature
8455        // protected permissions are install time permissions. Dangerous permissions
8456        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8457        // otherwise they are runtime permissions. This function does not manage
8458        // runtime permissions except for the case an app targeting Lollipop MR1
8459        // being upgraded to target a newer SDK, in which case dangerous permissions
8460        // are transformed from install time to runtime ones.
8461
8462        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8463        if (ps == null) {
8464            return;
8465        }
8466
8467        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8468
8469        PermissionsState permissionsState = ps.getPermissionsState();
8470        PermissionsState origPermissions = permissionsState;
8471
8472        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8473
8474        boolean runtimePermissionsRevoked = false;
8475        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8476
8477        boolean changedInstallPermission = false;
8478
8479        if (replace) {
8480            ps.installPermissionsFixed = false;
8481            if (!ps.isSharedUser()) {
8482                origPermissions = new PermissionsState(permissionsState);
8483                permissionsState.reset();
8484            } else {
8485                // We need to know only about runtime permission changes since the
8486                // calling code always writes the install permissions state but
8487                // the runtime ones are written only if changed. The only cases of
8488                // changed runtime permissions here are promotion of an install to
8489                // runtime and revocation of a runtime from a shared user.
8490                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8491                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8492                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8493                    runtimePermissionsRevoked = true;
8494                }
8495            }
8496        }
8497
8498        permissionsState.setGlobalGids(mGlobalGids);
8499
8500        final int N = pkg.requestedPermissions.size();
8501        for (int i=0; i<N; i++) {
8502            final String name = pkg.requestedPermissions.get(i);
8503            final BasePermission bp = mSettings.mPermissions.get(name);
8504
8505            if (DEBUG_INSTALL) {
8506                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8507            }
8508
8509            if (bp == null || bp.packageSetting == null) {
8510                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8511                    Slog.w(TAG, "Unknown permission " + name
8512                            + " in package " + pkg.packageName);
8513                }
8514                continue;
8515            }
8516
8517            final String perm = bp.name;
8518            boolean allowedSig = false;
8519            int grant = GRANT_DENIED;
8520
8521            // Keep track of app op permissions.
8522            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8523                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8524                if (pkgs == null) {
8525                    pkgs = new ArraySet<>();
8526                    mAppOpPermissionPackages.put(bp.name, pkgs);
8527                }
8528                pkgs.add(pkg.packageName);
8529            }
8530
8531            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8532            switch (level) {
8533                case PermissionInfo.PROTECTION_NORMAL: {
8534                    // For all apps normal permissions are install time ones.
8535                    grant = GRANT_INSTALL;
8536                } break;
8537
8538                case PermissionInfo.PROTECTION_DANGEROUS: {
8539                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
8540                        // For legacy apps dangerous permissions are install time ones.
8541                        grant = GRANT_INSTALL_LEGACY;
8542                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8543                        // For legacy apps that became modern, install becomes runtime.
8544                        grant = GRANT_UPGRADE;
8545                    } else if (mPromoteSystemApps
8546                            && isSystemApp(ps)
8547                            && mExistingSystemPackages.contains(ps.name)) {
8548                        // For legacy system apps, install becomes runtime.
8549                        // We cannot check hasInstallPermission() for system apps since those
8550                        // permissions were granted implicitly and not persisted pre-M.
8551                        grant = GRANT_UPGRADE;
8552                    } else {
8553                        // For modern apps keep runtime permissions unchanged.
8554                        grant = GRANT_RUNTIME;
8555                    }
8556                } break;
8557
8558                case PermissionInfo.PROTECTION_SIGNATURE: {
8559                    // For all apps signature permissions are install time ones.
8560                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8561                    if (allowedSig) {
8562                        grant = GRANT_INSTALL;
8563                    }
8564                } break;
8565            }
8566
8567            if (DEBUG_INSTALL) {
8568                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8569            }
8570
8571            if (grant != GRANT_DENIED) {
8572                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8573                    // If this is an existing, non-system package, then
8574                    // we can't add any new permissions to it.
8575                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8576                        // Except...  if this is a permission that was added
8577                        // to the platform (note: need to only do this when
8578                        // updating the platform).
8579                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8580                            grant = GRANT_DENIED;
8581                        }
8582                    }
8583                }
8584
8585                switch (grant) {
8586                    case GRANT_INSTALL: {
8587                        // Revoke this as runtime permission to handle the case of
8588                        // a runtime permission being downgraded to an install one.
8589                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8590                            if (origPermissions.getRuntimePermissionState(
8591                                    bp.name, userId) != null) {
8592                                // Revoke the runtime permission and clear the flags.
8593                                origPermissions.revokeRuntimePermission(bp, userId);
8594                                origPermissions.updatePermissionFlags(bp, userId,
8595                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8596                                // If we revoked a permission permission, we have to write.
8597                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8598                                        changedRuntimePermissionUserIds, userId);
8599                            }
8600                        }
8601                        // Grant an install permission.
8602                        if (permissionsState.grantInstallPermission(bp) !=
8603                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8604                            changedInstallPermission = true;
8605                        }
8606                    } break;
8607
8608                    case GRANT_INSTALL_LEGACY: {
8609                        // Grant an install permission.
8610                        if (permissionsState.grantInstallPermission(bp) !=
8611                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8612                            changedInstallPermission = true;
8613                        }
8614                    } break;
8615
8616                    case GRANT_RUNTIME: {
8617                        // Grant previously granted runtime permissions.
8618                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8619                            PermissionState permissionState = origPermissions
8620                                    .getRuntimePermissionState(bp.name, userId);
8621                            final int flags = permissionState != null
8622                                    ? permissionState.getFlags() : 0;
8623                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8624                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8625                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8626                                    // If we cannot put the permission as it was, we have to write.
8627                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8628                                            changedRuntimePermissionUserIds, userId);
8629                                }
8630                            }
8631                            // Propagate the permission flags.
8632                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8633                        }
8634                    } break;
8635
8636                    case GRANT_UPGRADE: {
8637                        // Grant runtime permissions for a previously held install permission.
8638                        PermissionState permissionState = origPermissions
8639                                .getInstallPermissionState(bp.name);
8640                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8641
8642                        if (origPermissions.revokeInstallPermission(bp)
8643                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8644                            // We will be transferring the permission flags, so clear them.
8645                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8646                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8647                            changedInstallPermission = true;
8648                        }
8649
8650                        // If the permission is not to be promoted to runtime we ignore it and
8651                        // also its other flags as they are not applicable to install permissions.
8652                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8653                            for (int userId : currentUserIds) {
8654                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8655                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8656                                    // Transfer the permission flags.
8657                                    permissionsState.updatePermissionFlags(bp, userId,
8658                                            flags, flags);
8659                                    // If we granted the permission, we have to write.
8660                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8661                                            changedRuntimePermissionUserIds, userId);
8662                                }
8663                            }
8664                        }
8665                    } break;
8666
8667                    default: {
8668                        if (packageOfInterest == null
8669                                || packageOfInterest.equals(pkg.packageName)) {
8670                            Slog.w(TAG, "Not granting permission " + perm
8671                                    + " to package " + pkg.packageName
8672                                    + " because it was previously installed without");
8673                        }
8674                    } break;
8675                }
8676            } else {
8677                if (permissionsState.revokeInstallPermission(bp) !=
8678                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8679                    // Also drop the permission flags.
8680                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8681                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8682                    changedInstallPermission = true;
8683                    Slog.i(TAG, "Un-granting permission " + perm
8684                            + " from package " + pkg.packageName
8685                            + " (protectionLevel=" + bp.protectionLevel
8686                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8687                            + ")");
8688                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8689                    // Don't print warning for app op permissions, since it is fine for them
8690                    // not to be granted, there is a UI for the user to decide.
8691                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8692                        Slog.w(TAG, "Not granting permission " + perm
8693                                + " to package " + pkg.packageName
8694                                + " (protectionLevel=" + bp.protectionLevel
8695                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8696                                + ")");
8697                    }
8698                }
8699            }
8700        }
8701
8702        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8703                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8704            // This is the first that we have heard about this package, so the
8705            // permissions we have now selected are fixed until explicitly
8706            // changed.
8707            ps.installPermissionsFixed = true;
8708        }
8709
8710        // Persist the runtime permissions state for users with changes. If permissions
8711        // were revoked because no app in the shared user declares them we have to
8712        // write synchronously to avoid losing runtime permissions state.
8713        for (int userId : changedRuntimePermissionUserIds) {
8714            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
8715        }
8716
8717        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8718    }
8719
8720    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
8721        boolean allowed = false;
8722        final int NP = PackageParser.NEW_PERMISSIONS.length;
8723        for (int ip=0; ip<NP; ip++) {
8724            final PackageParser.NewPermissionInfo npi
8725                    = PackageParser.NEW_PERMISSIONS[ip];
8726            if (npi.name.equals(perm)
8727                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
8728                allowed = true;
8729                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
8730                        + pkg.packageName);
8731                break;
8732            }
8733        }
8734        return allowed;
8735    }
8736
8737    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
8738            BasePermission bp, PermissionsState origPermissions) {
8739        boolean allowed;
8740        allowed = (compareSignatures(
8741                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
8742                        == PackageManager.SIGNATURE_MATCH)
8743                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
8744                        == PackageManager.SIGNATURE_MATCH);
8745        if (!allowed && (bp.protectionLevel
8746                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
8747            if (isSystemApp(pkg)) {
8748                // For updated system applications, a system permission
8749                // is granted only if it had been defined by the original application.
8750                if (pkg.isUpdatedSystemApp()) {
8751                    final PackageSetting sysPs = mSettings
8752                            .getDisabledSystemPkgLPr(pkg.packageName);
8753                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
8754                        // If the original was granted this permission, we take
8755                        // that grant decision as read and propagate it to the
8756                        // update.
8757                        if (sysPs.isPrivileged()) {
8758                            allowed = true;
8759                        }
8760                    } else {
8761                        // The system apk may have been updated with an older
8762                        // version of the one on the data partition, but which
8763                        // granted a new system permission that it didn't have
8764                        // before.  In this case we do want to allow the app to
8765                        // now get the new permission if the ancestral apk is
8766                        // privileged to get it.
8767                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
8768                            for (int j=0;
8769                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
8770                                if (perm.equals(
8771                                        sysPs.pkg.requestedPermissions.get(j))) {
8772                                    allowed = true;
8773                                    break;
8774                                }
8775                            }
8776                        }
8777                    }
8778                } else {
8779                    allowed = isPrivilegedApp(pkg);
8780                }
8781            }
8782        }
8783        if (!allowed) {
8784            if (!allowed && (bp.protectionLevel
8785                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
8786                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
8787                // If this was a previously normal/dangerous permission that got moved
8788                // to a system permission as part of the runtime permission redesign, then
8789                // we still want to blindly grant it to old apps.
8790                allowed = true;
8791            }
8792            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
8793                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
8794                // If this permission is to be granted to the system installer and
8795                // this app is an installer, then it gets the permission.
8796                allowed = true;
8797            }
8798            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
8799                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
8800                // If this permission is to be granted to the system verifier and
8801                // this app is a verifier, then it gets the permission.
8802                allowed = true;
8803            }
8804            if (!allowed && (bp.protectionLevel
8805                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
8806                    && isSystemApp(pkg)) {
8807                // Any pre-installed system app is allowed to get this permission.
8808                allowed = true;
8809            }
8810            if (!allowed && (bp.protectionLevel
8811                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
8812                // For development permissions, a development permission
8813                // is granted only if it was already granted.
8814                allowed = origPermissions.hasInstallPermission(perm);
8815            }
8816        }
8817        return allowed;
8818    }
8819
8820    final class ActivityIntentResolver
8821            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
8822        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8823                boolean defaultOnly, int userId) {
8824            if (!sUserManager.exists(userId)) return null;
8825            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8826            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8827        }
8828
8829        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8830                int userId) {
8831            if (!sUserManager.exists(userId)) return null;
8832            mFlags = flags;
8833            return super.queryIntent(intent, resolvedType,
8834                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8835        }
8836
8837        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8838                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
8839            if (!sUserManager.exists(userId)) return null;
8840            if (packageActivities == null) {
8841                return null;
8842            }
8843            mFlags = flags;
8844            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8845            final int N = packageActivities.size();
8846            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
8847                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
8848
8849            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
8850            for (int i = 0; i < N; ++i) {
8851                intentFilters = packageActivities.get(i).intents;
8852                if (intentFilters != null && intentFilters.size() > 0) {
8853                    PackageParser.ActivityIntentInfo[] array =
8854                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
8855                    intentFilters.toArray(array);
8856                    listCut.add(array);
8857                }
8858            }
8859            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8860        }
8861
8862        public final void addActivity(PackageParser.Activity a, String type) {
8863            final boolean systemApp = a.info.applicationInfo.isSystemApp();
8864            mActivities.put(a.getComponentName(), a);
8865            if (DEBUG_SHOW_INFO)
8866                Log.v(
8867                TAG, "  " + type + " " +
8868                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
8869            if (DEBUG_SHOW_INFO)
8870                Log.v(TAG, "    Class=" + a.info.name);
8871            final int NI = a.intents.size();
8872            for (int j=0; j<NI; j++) {
8873                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8874                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
8875                    intent.setPriority(0);
8876                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
8877                            + a.className + " with priority > 0, forcing to 0");
8878                }
8879                if (DEBUG_SHOW_INFO) {
8880                    Log.v(TAG, "    IntentFilter:");
8881                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8882                }
8883                if (!intent.debugCheck()) {
8884                    Log.w(TAG, "==> For Activity " + a.info.name);
8885                }
8886                addFilter(intent);
8887            }
8888        }
8889
8890        public final void removeActivity(PackageParser.Activity a, String type) {
8891            mActivities.remove(a.getComponentName());
8892            if (DEBUG_SHOW_INFO) {
8893                Log.v(TAG, "  " + type + " "
8894                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
8895                                : a.info.name) + ":");
8896                Log.v(TAG, "    Class=" + a.info.name);
8897            }
8898            final int NI = a.intents.size();
8899            for (int j=0; j<NI; j++) {
8900                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8901                if (DEBUG_SHOW_INFO) {
8902                    Log.v(TAG, "    IntentFilter:");
8903                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8904                }
8905                removeFilter(intent);
8906            }
8907        }
8908
8909        @Override
8910        protected boolean allowFilterResult(
8911                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8912            ActivityInfo filterAi = filter.activity.info;
8913            for (int i=dest.size()-1; i>=0; i--) {
8914                ActivityInfo destAi = dest.get(i).activityInfo;
8915                if (destAi.name == filterAi.name
8916                        && destAi.packageName == filterAi.packageName) {
8917                    return false;
8918                }
8919            }
8920            return true;
8921        }
8922
8923        @Override
8924        protected ActivityIntentInfo[] newArray(int size) {
8925            return new ActivityIntentInfo[size];
8926        }
8927
8928        @Override
8929        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8930            if (!sUserManager.exists(userId)) return true;
8931            PackageParser.Package p = filter.activity.owner;
8932            if (p != null) {
8933                PackageSetting ps = (PackageSetting)p.mExtras;
8934                if (ps != null) {
8935                    // System apps are never considered stopped for purposes of
8936                    // filtering, because there may be no way for the user to
8937                    // actually re-launch them.
8938                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8939                            && ps.getStopped(userId);
8940                }
8941            }
8942            return false;
8943        }
8944
8945        @Override
8946        protected boolean isPackageForFilter(String packageName,
8947                PackageParser.ActivityIntentInfo info) {
8948            return packageName.equals(info.activity.owner.packageName);
8949        }
8950
8951        @Override
8952        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8953                int match, int userId) {
8954            if (!sUserManager.exists(userId)) return null;
8955            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8956                return null;
8957            }
8958            final PackageParser.Activity activity = info.activity;
8959            if (mSafeMode && (activity.info.applicationInfo.flags
8960                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8961                return null;
8962            }
8963            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8964            if (ps == null) {
8965                return null;
8966            }
8967            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8968                    ps.readUserState(userId), userId);
8969            if (ai == null) {
8970                return null;
8971            }
8972            final ResolveInfo res = new ResolveInfo();
8973            res.activityInfo = ai;
8974            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8975                res.filter = info;
8976            }
8977            if (info != null) {
8978                res.handleAllWebDataURI = info.handleAllWebDataURI();
8979            }
8980            res.priority = info.getPriority();
8981            res.preferredOrder = activity.owner.mPreferredOrder;
8982            //System.out.println("Result: " + res.activityInfo.className +
8983            //                   " = " + res.priority);
8984            res.match = match;
8985            res.isDefault = info.hasDefault;
8986            res.labelRes = info.labelRes;
8987            res.nonLocalizedLabel = info.nonLocalizedLabel;
8988            if (userNeedsBadging(userId)) {
8989                res.noResourceId = true;
8990            } else {
8991                res.icon = info.icon;
8992            }
8993            res.iconResourceId = info.icon;
8994            res.system = res.activityInfo.applicationInfo.isSystemApp();
8995            return res;
8996        }
8997
8998        @Override
8999        protected void sortResults(List<ResolveInfo> results) {
9000            Collections.sort(results, mResolvePrioritySorter);
9001        }
9002
9003        @Override
9004        protected void dumpFilter(PrintWriter out, String prefix,
9005                PackageParser.ActivityIntentInfo filter) {
9006            out.print(prefix); out.print(
9007                    Integer.toHexString(System.identityHashCode(filter.activity)));
9008                    out.print(' ');
9009                    filter.activity.printComponentShortName(out);
9010                    out.print(" filter ");
9011                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9012        }
9013
9014        @Override
9015        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9016            return filter.activity;
9017        }
9018
9019        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9020            PackageParser.Activity activity = (PackageParser.Activity)label;
9021            out.print(prefix); out.print(
9022                    Integer.toHexString(System.identityHashCode(activity)));
9023                    out.print(' ');
9024                    activity.printComponentShortName(out);
9025            if (count > 1) {
9026                out.print(" ("); out.print(count); out.print(" filters)");
9027            }
9028            out.println();
9029        }
9030
9031//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9032//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9033//            final List<ResolveInfo> retList = Lists.newArrayList();
9034//            while (i.hasNext()) {
9035//                final ResolveInfo resolveInfo = i.next();
9036//                if (isEnabledLP(resolveInfo.activityInfo)) {
9037//                    retList.add(resolveInfo);
9038//                }
9039//            }
9040//            return retList;
9041//        }
9042
9043        // Keys are String (activity class name), values are Activity.
9044        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9045                = new ArrayMap<ComponentName, PackageParser.Activity>();
9046        private int mFlags;
9047    }
9048
9049    private final class ServiceIntentResolver
9050            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9051        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9052                boolean defaultOnly, int userId) {
9053            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9054            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9055        }
9056
9057        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9058                int userId) {
9059            if (!sUserManager.exists(userId)) return null;
9060            mFlags = flags;
9061            return super.queryIntent(intent, resolvedType,
9062                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9063        }
9064
9065        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9066                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9067            if (!sUserManager.exists(userId)) return null;
9068            if (packageServices == null) {
9069                return null;
9070            }
9071            mFlags = flags;
9072            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9073            final int N = packageServices.size();
9074            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9075                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9076
9077            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9078            for (int i = 0; i < N; ++i) {
9079                intentFilters = packageServices.get(i).intents;
9080                if (intentFilters != null && intentFilters.size() > 0) {
9081                    PackageParser.ServiceIntentInfo[] array =
9082                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9083                    intentFilters.toArray(array);
9084                    listCut.add(array);
9085                }
9086            }
9087            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9088        }
9089
9090        public final void addService(PackageParser.Service s) {
9091            mServices.put(s.getComponentName(), s);
9092            if (DEBUG_SHOW_INFO) {
9093                Log.v(TAG, "  "
9094                        + (s.info.nonLocalizedLabel != null
9095                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9096                Log.v(TAG, "    Class=" + s.info.name);
9097            }
9098            final int NI = s.intents.size();
9099            int j;
9100            for (j=0; j<NI; j++) {
9101                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9102                if (DEBUG_SHOW_INFO) {
9103                    Log.v(TAG, "    IntentFilter:");
9104                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9105                }
9106                if (!intent.debugCheck()) {
9107                    Log.w(TAG, "==> For Service " + s.info.name);
9108                }
9109                addFilter(intent);
9110            }
9111        }
9112
9113        public final void removeService(PackageParser.Service s) {
9114            mServices.remove(s.getComponentName());
9115            if (DEBUG_SHOW_INFO) {
9116                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9117                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9118                Log.v(TAG, "    Class=" + s.info.name);
9119            }
9120            final int NI = s.intents.size();
9121            int j;
9122            for (j=0; j<NI; j++) {
9123                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9124                if (DEBUG_SHOW_INFO) {
9125                    Log.v(TAG, "    IntentFilter:");
9126                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9127                }
9128                removeFilter(intent);
9129            }
9130        }
9131
9132        @Override
9133        protected boolean allowFilterResult(
9134                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9135            ServiceInfo filterSi = filter.service.info;
9136            for (int i=dest.size()-1; i>=0; i--) {
9137                ServiceInfo destAi = dest.get(i).serviceInfo;
9138                if (destAi.name == filterSi.name
9139                        && destAi.packageName == filterSi.packageName) {
9140                    return false;
9141                }
9142            }
9143            return true;
9144        }
9145
9146        @Override
9147        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9148            return new PackageParser.ServiceIntentInfo[size];
9149        }
9150
9151        @Override
9152        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9153            if (!sUserManager.exists(userId)) return true;
9154            PackageParser.Package p = filter.service.owner;
9155            if (p != null) {
9156                PackageSetting ps = (PackageSetting)p.mExtras;
9157                if (ps != null) {
9158                    // System apps are never considered stopped for purposes of
9159                    // filtering, because there may be no way for the user to
9160                    // actually re-launch them.
9161                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9162                            && ps.getStopped(userId);
9163                }
9164            }
9165            return false;
9166        }
9167
9168        @Override
9169        protected boolean isPackageForFilter(String packageName,
9170                PackageParser.ServiceIntentInfo info) {
9171            return packageName.equals(info.service.owner.packageName);
9172        }
9173
9174        @Override
9175        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9176                int match, int userId) {
9177            if (!sUserManager.exists(userId)) return null;
9178            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9179            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
9180                return null;
9181            }
9182            final PackageParser.Service service = info.service;
9183            if (mSafeMode && (service.info.applicationInfo.flags
9184                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9185                return null;
9186            }
9187            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9188            if (ps == null) {
9189                return null;
9190            }
9191            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9192                    ps.readUserState(userId), userId);
9193            if (si == null) {
9194                return null;
9195            }
9196            final ResolveInfo res = new ResolveInfo();
9197            res.serviceInfo = si;
9198            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9199                res.filter = filter;
9200            }
9201            res.priority = info.getPriority();
9202            res.preferredOrder = service.owner.mPreferredOrder;
9203            res.match = match;
9204            res.isDefault = info.hasDefault;
9205            res.labelRes = info.labelRes;
9206            res.nonLocalizedLabel = info.nonLocalizedLabel;
9207            res.icon = info.icon;
9208            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9209            return res;
9210        }
9211
9212        @Override
9213        protected void sortResults(List<ResolveInfo> results) {
9214            Collections.sort(results, mResolvePrioritySorter);
9215        }
9216
9217        @Override
9218        protected void dumpFilter(PrintWriter out, String prefix,
9219                PackageParser.ServiceIntentInfo filter) {
9220            out.print(prefix); out.print(
9221                    Integer.toHexString(System.identityHashCode(filter.service)));
9222                    out.print(' ');
9223                    filter.service.printComponentShortName(out);
9224                    out.print(" filter ");
9225                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9226        }
9227
9228        @Override
9229        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9230            return filter.service;
9231        }
9232
9233        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9234            PackageParser.Service service = (PackageParser.Service)label;
9235            out.print(prefix); out.print(
9236                    Integer.toHexString(System.identityHashCode(service)));
9237                    out.print(' ');
9238                    service.printComponentShortName(out);
9239            if (count > 1) {
9240                out.print(" ("); out.print(count); out.print(" filters)");
9241            }
9242            out.println();
9243        }
9244
9245//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9246//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9247//            final List<ResolveInfo> retList = Lists.newArrayList();
9248//            while (i.hasNext()) {
9249//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9250//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9251//                    retList.add(resolveInfo);
9252//                }
9253//            }
9254//            return retList;
9255//        }
9256
9257        // Keys are String (activity class name), values are Activity.
9258        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9259                = new ArrayMap<ComponentName, PackageParser.Service>();
9260        private int mFlags;
9261    };
9262
9263    private final class ProviderIntentResolver
9264            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9265        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9266                boolean defaultOnly, int userId) {
9267            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9268            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9269        }
9270
9271        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9272                int userId) {
9273            if (!sUserManager.exists(userId))
9274                return null;
9275            mFlags = flags;
9276            return super.queryIntent(intent, resolvedType,
9277                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9278        }
9279
9280        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9281                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9282            if (!sUserManager.exists(userId))
9283                return null;
9284            if (packageProviders == null) {
9285                return null;
9286            }
9287            mFlags = flags;
9288            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9289            final int N = packageProviders.size();
9290            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9291                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9292
9293            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9294            for (int i = 0; i < N; ++i) {
9295                intentFilters = packageProviders.get(i).intents;
9296                if (intentFilters != null && intentFilters.size() > 0) {
9297                    PackageParser.ProviderIntentInfo[] array =
9298                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9299                    intentFilters.toArray(array);
9300                    listCut.add(array);
9301                }
9302            }
9303            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9304        }
9305
9306        public final void addProvider(PackageParser.Provider p) {
9307            if (mProviders.containsKey(p.getComponentName())) {
9308                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9309                return;
9310            }
9311
9312            mProviders.put(p.getComponentName(), p);
9313            if (DEBUG_SHOW_INFO) {
9314                Log.v(TAG, "  "
9315                        + (p.info.nonLocalizedLabel != null
9316                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9317                Log.v(TAG, "    Class=" + p.info.name);
9318            }
9319            final int NI = p.intents.size();
9320            int j;
9321            for (j = 0; j < NI; j++) {
9322                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9323                if (DEBUG_SHOW_INFO) {
9324                    Log.v(TAG, "    IntentFilter:");
9325                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9326                }
9327                if (!intent.debugCheck()) {
9328                    Log.w(TAG, "==> For Provider " + p.info.name);
9329                }
9330                addFilter(intent);
9331            }
9332        }
9333
9334        public final void removeProvider(PackageParser.Provider p) {
9335            mProviders.remove(p.getComponentName());
9336            if (DEBUG_SHOW_INFO) {
9337                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9338                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9339                Log.v(TAG, "    Class=" + p.info.name);
9340            }
9341            final int NI = p.intents.size();
9342            int j;
9343            for (j = 0; j < NI; j++) {
9344                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9345                if (DEBUG_SHOW_INFO) {
9346                    Log.v(TAG, "    IntentFilter:");
9347                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9348                }
9349                removeFilter(intent);
9350            }
9351        }
9352
9353        @Override
9354        protected boolean allowFilterResult(
9355                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9356            ProviderInfo filterPi = filter.provider.info;
9357            for (int i = dest.size() - 1; i >= 0; i--) {
9358                ProviderInfo destPi = dest.get(i).providerInfo;
9359                if (destPi.name == filterPi.name
9360                        && destPi.packageName == filterPi.packageName) {
9361                    return false;
9362                }
9363            }
9364            return true;
9365        }
9366
9367        @Override
9368        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9369            return new PackageParser.ProviderIntentInfo[size];
9370        }
9371
9372        @Override
9373        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9374            if (!sUserManager.exists(userId))
9375                return true;
9376            PackageParser.Package p = filter.provider.owner;
9377            if (p != null) {
9378                PackageSetting ps = (PackageSetting) p.mExtras;
9379                if (ps != null) {
9380                    // System apps are never considered stopped for purposes of
9381                    // filtering, because there may be no way for the user to
9382                    // actually re-launch them.
9383                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9384                            && ps.getStopped(userId);
9385                }
9386            }
9387            return false;
9388        }
9389
9390        @Override
9391        protected boolean isPackageForFilter(String packageName,
9392                PackageParser.ProviderIntentInfo info) {
9393            return packageName.equals(info.provider.owner.packageName);
9394        }
9395
9396        @Override
9397        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9398                int match, int userId) {
9399            if (!sUserManager.exists(userId))
9400                return null;
9401            final PackageParser.ProviderIntentInfo info = filter;
9402            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
9403                return null;
9404            }
9405            final PackageParser.Provider provider = info.provider;
9406            if (mSafeMode && (provider.info.applicationInfo.flags
9407                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9408                return null;
9409            }
9410            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9411            if (ps == null) {
9412                return null;
9413            }
9414            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9415                    ps.readUserState(userId), userId);
9416            if (pi == null) {
9417                return null;
9418            }
9419            final ResolveInfo res = new ResolveInfo();
9420            res.providerInfo = pi;
9421            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9422                res.filter = filter;
9423            }
9424            res.priority = info.getPriority();
9425            res.preferredOrder = provider.owner.mPreferredOrder;
9426            res.match = match;
9427            res.isDefault = info.hasDefault;
9428            res.labelRes = info.labelRes;
9429            res.nonLocalizedLabel = info.nonLocalizedLabel;
9430            res.icon = info.icon;
9431            res.system = res.providerInfo.applicationInfo.isSystemApp();
9432            return res;
9433        }
9434
9435        @Override
9436        protected void sortResults(List<ResolveInfo> results) {
9437            Collections.sort(results, mResolvePrioritySorter);
9438        }
9439
9440        @Override
9441        protected void dumpFilter(PrintWriter out, String prefix,
9442                PackageParser.ProviderIntentInfo filter) {
9443            out.print(prefix);
9444            out.print(
9445                    Integer.toHexString(System.identityHashCode(filter.provider)));
9446            out.print(' ');
9447            filter.provider.printComponentShortName(out);
9448            out.print(" filter ");
9449            out.println(Integer.toHexString(System.identityHashCode(filter)));
9450        }
9451
9452        @Override
9453        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9454            return filter.provider;
9455        }
9456
9457        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9458            PackageParser.Provider provider = (PackageParser.Provider)label;
9459            out.print(prefix); out.print(
9460                    Integer.toHexString(System.identityHashCode(provider)));
9461                    out.print(' ');
9462                    provider.printComponentShortName(out);
9463            if (count > 1) {
9464                out.print(" ("); out.print(count); out.print(" filters)");
9465            }
9466            out.println();
9467        }
9468
9469        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9470                = new ArrayMap<ComponentName, PackageParser.Provider>();
9471        private int mFlags;
9472    };
9473
9474    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9475            new Comparator<ResolveInfo>() {
9476        public int compare(ResolveInfo r1, ResolveInfo r2) {
9477            int v1 = r1.priority;
9478            int v2 = r2.priority;
9479            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9480            if (v1 != v2) {
9481                return (v1 > v2) ? -1 : 1;
9482            }
9483            v1 = r1.preferredOrder;
9484            v2 = r2.preferredOrder;
9485            if (v1 != v2) {
9486                return (v1 > v2) ? -1 : 1;
9487            }
9488            if (r1.isDefault != r2.isDefault) {
9489                return r1.isDefault ? -1 : 1;
9490            }
9491            v1 = r1.match;
9492            v2 = r2.match;
9493            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9494            if (v1 != v2) {
9495                return (v1 > v2) ? -1 : 1;
9496            }
9497            if (r1.system != r2.system) {
9498                return r1.system ? -1 : 1;
9499            }
9500            return 0;
9501        }
9502    };
9503
9504    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9505            new Comparator<ProviderInfo>() {
9506        public int compare(ProviderInfo p1, ProviderInfo p2) {
9507            final int v1 = p1.initOrder;
9508            final int v2 = p2.initOrder;
9509            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9510        }
9511    };
9512
9513    final void sendPackageBroadcast(final String action, final String pkg,
9514            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
9515            final int[] userIds) {
9516        mHandler.post(new Runnable() {
9517            @Override
9518            public void run() {
9519                try {
9520                    final IActivityManager am = ActivityManagerNative.getDefault();
9521                    if (am == null) return;
9522                    final int[] resolvedUserIds;
9523                    if (userIds == null) {
9524                        resolvedUserIds = am.getRunningUserIds();
9525                    } else {
9526                        resolvedUserIds = userIds;
9527                    }
9528                    for (int id : resolvedUserIds) {
9529                        final Intent intent = new Intent(action,
9530                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9531                        if (extras != null) {
9532                            intent.putExtras(extras);
9533                        }
9534                        if (targetPkg != null) {
9535                            intent.setPackage(targetPkg);
9536                        }
9537                        // Modify the UID when posting to other users
9538                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9539                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9540                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9541                            intent.putExtra(Intent.EXTRA_UID, uid);
9542                        }
9543                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9544                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
9545                        if (DEBUG_BROADCASTS) {
9546                            RuntimeException here = new RuntimeException("here");
9547                            here.fillInStackTrace();
9548                            Slog.d(TAG, "Sending to user " + id + ": "
9549                                    + intent.toShortString(false, true, false, false)
9550                                    + " " + intent.getExtras(), here);
9551                        }
9552                        am.broadcastIntent(null, intent, null, finishedReceiver,
9553                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9554                                null, finishedReceiver != null, false, id);
9555                    }
9556                } catch (RemoteException ex) {
9557                }
9558            }
9559        });
9560    }
9561
9562    /**
9563     * Check if the external storage media is available. This is true if there
9564     * is a mounted external storage medium or if the external storage is
9565     * emulated.
9566     */
9567    private boolean isExternalMediaAvailable() {
9568        return mMediaMounted || Environment.isExternalStorageEmulated();
9569    }
9570
9571    @Override
9572    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9573        // writer
9574        synchronized (mPackages) {
9575            if (!isExternalMediaAvailable()) {
9576                // If the external storage is no longer mounted at this point,
9577                // the caller may not have been able to delete all of this
9578                // packages files and can not delete any more.  Bail.
9579                return null;
9580            }
9581            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9582            if (lastPackage != null) {
9583                pkgs.remove(lastPackage);
9584            }
9585            if (pkgs.size() > 0) {
9586                return pkgs.get(0);
9587            }
9588        }
9589        return null;
9590    }
9591
9592    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9593        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9594                userId, andCode ? 1 : 0, packageName);
9595        if (mSystemReady) {
9596            msg.sendToTarget();
9597        } else {
9598            if (mPostSystemReadyMessages == null) {
9599                mPostSystemReadyMessages = new ArrayList<>();
9600            }
9601            mPostSystemReadyMessages.add(msg);
9602        }
9603    }
9604
9605    void startCleaningPackages() {
9606        // reader
9607        synchronized (mPackages) {
9608            if (!isExternalMediaAvailable()) {
9609                return;
9610            }
9611            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9612                return;
9613            }
9614        }
9615        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9616        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9617        IActivityManager am = ActivityManagerNative.getDefault();
9618        if (am != null) {
9619            try {
9620                am.startService(null, intent, null, mContext.getOpPackageName(),
9621                        UserHandle.USER_SYSTEM);
9622            } catch (RemoteException e) {
9623            }
9624        }
9625    }
9626
9627    @Override
9628    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9629            int installFlags, String installerPackageName, VerificationParams verificationParams,
9630            String packageAbiOverride) {
9631        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9632                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9633    }
9634
9635    @Override
9636    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9637            int installFlags, String installerPackageName, VerificationParams verificationParams,
9638            String packageAbiOverride, int userId) {
9639        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9640
9641        final int callingUid = Binder.getCallingUid();
9642        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9643
9644        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9645            try {
9646                if (observer != null) {
9647                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9648                }
9649            } catch (RemoteException re) {
9650            }
9651            return;
9652        }
9653
9654        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9655            installFlags |= PackageManager.INSTALL_FROM_ADB;
9656
9657        } else {
9658            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9659            // about installerPackageName.
9660
9661            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9662            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9663        }
9664
9665        UserHandle user;
9666        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9667            user = UserHandle.ALL;
9668        } else {
9669            user = new UserHandle(userId);
9670        }
9671
9672        // Only system components can circumvent runtime permissions when installing.
9673        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9674                && mContext.checkCallingOrSelfPermission(Manifest.permission
9675                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9676            throw new SecurityException("You need the "
9677                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9678                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
9679        }
9680
9681        verificationParams.setInstallerUid(callingUid);
9682
9683        final File originFile = new File(originPath);
9684        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
9685
9686        final Message msg = mHandler.obtainMessage(INIT_COPY);
9687        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
9688                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
9689        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
9690        msg.obj = params;
9691
9692        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
9693                System.identityHashCode(msg.obj));
9694        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9695                System.identityHashCode(msg.obj));
9696
9697        mHandler.sendMessage(msg);
9698    }
9699
9700    void installStage(String packageName, File stagedDir, String stagedCid,
9701            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
9702            String installerPackageName, int installerUid, UserHandle user) {
9703        final VerificationParams verifParams = new VerificationParams(
9704                null, sessionParams.originatingUri, sessionParams.referrerUri,
9705                sessionParams.originatingUid, null);
9706        verifParams.setInstallerUid(installerUid);
9707
9708        final OriginInfo origin;
9709        if (stagedDir != null) {
9710            origin = OriginInfo.fromStagedFile(stagedDir);
9711        } else {
9712            origin = OriginInfo.fromStagedContainer(stagedCid);
9713        }
9714
9715        final Message msg = mHandler.obtainMessage(INIT_COPY);
9716        final InstallParams params = new InstallParams(origin, null, observer,
9717                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
9718                verifParams, user, sessionParams.abiOverride,
9719                sessionParams.grantedRuntimePermissions);
9720        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
9721        msg.obj = params;
9722
9723        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
9724                System.identityHashCode(msg.obj));
9725        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
9726                System.identityHashCode(msg.obj));
9727
9728        mHandler.sendMessage(msg);
9729    }
9730
9731    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
9732        Bundle extras = new Bundle(1);
9733        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
9734
9735        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
9736                packageName, extras, null, null, new int[] {userId});
9737        try {
9738            IActivityManager am = ActivityManagerNative.getDefault();
9739            final boolean isSystem =
9740                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
9741            if (isSystem && am.isUserRunning(userId, false)) {
9742                // The just-installed/enabled app is bundled on the system, so presumed
9743                // to be able to run automatically without needing an explicit launch.
9744                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
9745                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
9746                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
9747                        .setPackage(packageName);
9748                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
9749                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
9750            }
9751        } catch (RemoteException e) {
9752            // shouldn't happen
9753            Slog.w(TAG, "Unable to bootstrap installed package", e);
9754        }
9755    }
9756
9757    @Override
9758    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
9759            int userId) {
9760        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9761        PackageSetting pkgSetting;
9762        final int uid = Binder.getCallingUid();
9763        enforceCrossUserPermission(uid, userId, true, true,
9764                "setApplicationHiddenSetting for user " + userId);
9765
9766        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
9767            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
9768            return false;
9769        }
9770
9771        long callingId = Binder.clearCallingIdentity();
9772        try {
9773            boolean sendAdded = false;
9774            boolean sendRemoved = false;
9775            // writer
9776            synchronized (mPackages) {
9777                pkgSetting = mSettings.mPackages.get(packageName);
9778                if (pkgSetting == null) {
9779                    return false;
9780                }
9781                if (pkgSetting.getHidden(userId) != hidden) {
9782                    pkgSetting.setHidden(hidden, userId);
9783                    mSettings.writePackageRestrictionsLPr(userId);
9784                    if (hidden) {
9785                        sendRemoved = true;
9786                    } else {
9787                        sendAdded = true;
9788                    }
9789                }
9790            }
9791            if (sendAdded) {
9792                sendPackageAddedForUser(packageName, pkgSetting, userId);
9793                return true;
9794            }
9795            if (sendRemoved) {
9796                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
9797                        "hiding pkg");
9798                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
9799                return true;
9800            }
9801        } finally {
9802            Binder.restoreCallingIdentity(callingId);
9803        }
9804        return false;
9805    }
9806
9807    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
9808            int userId) {
9809        final PackageRemovedInfo info = new PackageRemovedInfo();
9810        info.removedPackage = packageName;
9811        info.removedUsers = new int[] {userId};
9812        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
9813        info.sendBroadcast(false, false, false);
9814    }
9815
9816    /**
9817     * Returns true if application is not found or there was an error. Otherwise it returns
9818     * the hidden state of the package for the given user.
9819     */
9820    @Override
9821    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
9822        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
9823        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
9824                false, "getApplicationHidden for user " + userId);
9825        PackageSetting pkgSetting;
9826        long callingId = Binder.clearCallingIdentity();
9827        try {
9828            // writer
9829            synchronized (mPackages) {
9830                pkgSetting = mSettings.mPackages.get(packageName);
9831                if (pkgSetting == null) {
9832                    return true;
9833                }
9834                return pkgSetting.getHidden(userId);
9835            }
9836        } finally {
9837            Binder.restoreCallingIdentity(callingId);
9838        }
9839    }
9840
9841    /**
9842     * @hide
9843     */
9844    @Override
9845    public int installExistingPackageAsUser(String packageName, int userId) {
9846        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
9847                null);
9848        PackageSetting pkgSetting;
9849        final int uid = Binder.getCallingUid();
9850        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
9851                + userId);
9852        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9853            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
9854        }
9855
9856        long callingId = Binder.clearCallingIdentity();
9857        try {
9858            boolean sendAdded = false;
9859
9860            // writer
9861            synchronized (mPackages) {
9862                pkgSetting = mSettings.mPackages.get(packageName);
9863                if (pkgSetting == null) {
9864                    return PackageManager.INSTALL_FAILED_INVALID_URI;
9865                }
9866                if (!pkgSetting.getInstalled(userId)) {
9867                    pkgSetting.setInstalled(true, userId);
9868                    pkgSetting.setHidden(false, userId);
9869                    mSettings.writePackageRestrictionsLPr(userId);
9870                    sendAdded = true;
9871                }
9872            }
9873
9874            if (sendAdded) {
9875                sendPackageAddedForUser(packageName, pkgSetting, userId);
9876            }
9877        } finally {
9878            Binder.restoreCallingIdentity(callingId);
9879        }
9880
9881        return PackageManager.INSTALL_SUCCEEDED;
9882    }
9883
9884    boolean isUserRestricted(int userId, String restrictionKey) {
9885        Bundle restrictions = sUserManager.getUserRestrictions(userId);
9886        if (restrictions.getBoolean(restrictionKey, false)) {
9887            Log.w(TAG, "User is restricted: " + restrictionKey);
9888            return true;
9889        }
9890        return false;
9891    }
9892
9893    @Override
9894    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
9895        mContext.enforceCallingOrSelfPermission(
9896                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9897                "Only package verification agents can verify applications");
9898
9899        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9900        final PackageVerificationResponse response = new PackageVerificationResponse(
9901                verificationCode, Binder.getCallingUid());
9902        msg.arg1 = id;
9903        msg.obj = response;
9904        mHandler.sendMessage(msg);
9905    }
9906
9907    @Override
9908    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
9909            long millisecondsToDelay) {
9910        mContext.enforceCallingOrSelfPermission(
9911                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9912                "Only package verification agents can extend verification timeouts");
9913
9914        final PackageVerificationState state = mPendingVerification.get(id);
9915        final PackageVerificationResponse response = new PackageVerificationResponse(
9916                verificationCodeAtTimeout, Binder.getCallingUid());
9917
9918        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
9919            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
9920        }
9921        if (millisecondsToDelay < 0) {
9922            millisecondsToDelay = 0;
9923        }
9924        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9925                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9926            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9927        }
9928
9929        if ((state != null) && !state.timeoutExtended()) {
9930            state.extendTimeout();
9931
9932            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9933            msg.arg1 = id;
9934            msg.obj = response;
9935            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9936        }
9937    }
9938
9939    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9940            int verificationCode, UserHandle user) {
9941        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9942        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9943        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9944        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9945        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9946
9947        mContext.sendBroadcastAsUser(intent, user,
9948                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9949    }
9950
9951    private ComponentName matchComponentForVerifier(String packageName,
9952            List<ResolveInfo> receivers) {
9953        ActivityInfo targetReceiver = null;
9954
9955        final int NR = receivers.size();
9956        for (int i = 0; i < NR; i++) {
9957            final ResolveInfo info = receivers.get(i);
9958            if (info.activityInfo == null) {
9959                continue;
9960            }
9961
9962            if (packageName.equals(info.activityInfo.packageName)) {
9963                targetReceiver = info.activityInfo;
9964                break;
9965            }
9966        }
9967
9968        if (targetReceiver == null) {
9969            return null;
9970        }
9971
9972        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9973    }
9974
9975    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9976            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9977        if (pkgInfo.verifiers.length == 0) {
9978            return null;
9979        }
9980
9981        final int N = pkgInfo.verifiers.length;
9982        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9983        for (int i = 0; i < N; i++) {
9984            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9985
9986            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9987                    receivers);
9988            if (comp == null) {
9989                continue;
9990            }
9991
9992            final int verifierUid = getUidForVerifier(verifierInfo);
9993            if (verifierUid == -1) {
9994                continue;
9995            }
9996
9997            if (DEBUG_VERIFY) {
9998                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9999                        + " with the correct signature");
10000            }
10001            sufficientVerifiers.add(comp);
10002            verificationState.addSufficientVerifier(verifierUid);
10003        }
10004
10005        return sufficientVerifiers;
10006    }
10007
10008    private int getUidForVerifier(VerifierInfo verifierInfo) {
10009        synchronized (mPackages) {
10010            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10011            if (pkg == null) {
10012                return -1;
10013            } else if (pkg.mSignatures.length != 1) {
10014                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10015                        + " has more than one signature; ignoring");
10016                return -1;
10017            }
10018
10019            /*
10020             * If the public key of the package's signature does not match
10021             * our expected public key, then this is a different package and
10022             * we should skip.
10023             */
10024
10025            final byte[] expectedPublicKey;
10026            try {
10027                final Signature verifierSig = pkg.mSignatures[0];
10028                final PublicKey publicKey = verifierSig.getPublicKey();
10029                expectedPublicKey = publicKey.getEncoded();
10030            } catch (CertificateException e) {
10031                return -1;
10032            }
10033
10034            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10035
10036            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10037                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10038                        + " does not have the expected public key; ignoring");
10039                return -1;
10040            }
10041
10042            return pkg.applicationInfo.uid;
10043        }
10044    }
10045
10046    @Override
10047    public void finishPackageInstall(int token) {
10048        enforceSystemOrRoot("Only the system is allowed to finish installs");
10049
10050        if (DEBUG_INSTALL) {
10051            Slog.v(TAG, "BM finishing package install for " + token);
10052        }
10053        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10054
10055        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10056        mHandler.sendMessage(msg);
10057    }
10058
10059    /**
10060     * Get the verification agent timeout.
10061     *
10062     * @return verification timeout in milliseconds
10063     */
10064    private long getVerificationTimeout() {
10065        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10066                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10067                DEFAULT_VERIFICATION_TIMEOUT);
10068    }
10069
10070    /**
10071     * Get the default verification agent response code.
10072     *
10073     * @return default verification response code
10074     */
10075    private int getDefaultVerificationResponse() {
10076        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10077                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10078                DEFAULT_VERIFICATION_RESPONSE);
10079    }
10080
10081    /**
10082     * Check whether or not package verification has been enabled.
10083     *
10084     * @return true if verification should be performed
10085     */
10086    private boolean isVerificationEnabled(int userId, int installFlags) {
10087        if (!DEFAULT_VERIFY_ENABLE) {
10088            return false;
10089        }
10090        // TODO: fix b/25118622; don't bypass verification
10091        if (Build.IS_DEBUGGABLE && (installFlags & PackageManager.INSTALL_QUICK) != 0) {
10092            return false;
10093        }
10094
10095        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10096
10097        // Check if installing from ADB
10098        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10099            // Do not run verification in a test harness environment
10100            if (ActivityManager.isRunningInTestHarness()) {
10101                return false;
10102            }
10103            if (ensureVerifyAppsEnabled) {
10104                return true;
10105            }
10106            // Check if the developer does not want package verification for ADB installs
10107            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10108                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10109                return false;
10110            }
10111        }
10112
10113        if (ensureVerifyAppsEnabled) {
10114            return true;
10115        }
10116
10117        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10118                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10119    }
10120
10121    @Override
10122    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10123            throws RemoteException {
10124        mContext.enforceCallingOrSelfPermission(
10125                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10126                "Only intentfilter verification agents can verify applications");
10127
10128        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10129        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10130                Binder.getCallingUid(), verificationCode, failedDomains);
10131        msg.arg1 = id;
10132        msg.obj = response;
10133        mHandler.sendMessage(msg);
10134    }
10135
10136    @Override
10137    public int getIntentVerificationStatus(String packageName, int userId) {
10138        synchronized (mPackages) {
10139            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10140        }
10141    }
10142
10143    @Override
10144    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10145        mContext.enforceCallingOrSelfPermission(
10146                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10147
10148        boolean result = false;
10149        synchronized (mPackages) {
10150            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10151        }
10152        if (result) {
10153            scheduleWritePackageRestrictionsLocked(userId);
10154        }
10155        return result;
10156    }
10157
10158    @Override
10159    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10160        synchronized (mPackages) {
10161            return mSettings.getIntentFilterVerificationsLPr(packageName);
10162        }
10163    }
10164
10165    @Override
10166    public List<IntentFilter> getAllIntentFilters(String packageName) {
10167        if (TextUtils.isEmpty(packageName)) {
10168            return Collections.<IntentFilter>emptyList();
10169        }
10170        synchronized (mPackages) {
10171            PackageParser.Package pkg = mPackages.get(packageName);
10172            if (pkg == null || pkg.activities == null) {
10173                return Collections.<IntentFilter>emptyList();
10174            }
10175            final int count = pkg.activities.size();
10176            ArrayList<IntentFilter> result = new ArrayList<>();
10177            for (int n=0; n<count; n++) {
10178                PackageParser.Activity activity = pkg.activities.get(n);
10179                if (activity.intents != null || activity.intents.size() > 0) {
10180                    result.addAll(activity.intents);
10181                }
10182            }
10183            return result;
10184        }
10185    }
10186
10187    @Override
10188    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10189        mContext.enforceCallingOrSelfPermission(
10190                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10191
10192        synchronized (mPackages) {
10193            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10194            if (packageName != null) {
10195                result |= updateIntentVerificationStatus(packageName,
10196                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10197                        userId);
10198                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10199                        packageName, userId);
10200            }
10201            return result;
10202        }
10203    }
10204
10205    @Override
10206    public String getDefaultBrowserPackageName(int userId) {
10207        synchronized (mPackages) {
10208            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10209        }
10210    }
10211
10212    /**
10213     * Get the "allow unknown sources" setting.
10214     *
10215     * @return the current "allow unknown sources" setting
10216     */
10217    private int getUnknownSourcesSettings() {
10218        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10219                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10220                -1);
10221    }
10222
10223    @Override
10224    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10225        final int uid = Binder.getCallingUid();
10226        // writer
10227        synchronized (mPackages) {
10228            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10229            if (targetPackageSetting == null) {
10230                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10231            }
10232
10233            PackageSetting installerPackageSetting;
10234            if (installerPackageName != null) {
10235                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10236                if (installerPackageSetting == null) {
10237                    throw new IllegalArgumentException("Unknown installer package: "
10238                            + installerPackageName);
10239                }
10240            } else {
10241                installerPackageSetting = null;
10242            }
10243
10244            Signature[] callerSignature;
10245            Object obj = mSettings.getUserIdLPr(uid);
10246            if (obj != null) {
10247                if (obj instanceof SharedUserSetting) {
10248                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10249                } else if (obj instanceof PackageSetting) {
10250                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10251                } else {
10252                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10253                }
10254            } else {
10255                throw new SecurityException("Unknown calling uid " + uid);
10256            }
10257
10258            // Verify: can't set installerPackageName to a package that is
10259            // not signed with the same cert as the caller.
10260            if (installerPackageSetting != null) {
10261                if (compareSignatures(callerSignature,
10262                        installerPackageSetting.signatures.mSignatures)
10263                        != PackageManager.SIGNATURE_MATCH) {
10264                    throw new SecurityException(
10265                            "Caller does not have same cert as new installer package "
10266                            + installerPackageName);
10267                }
10268            }
10269
10270            // Verify: if target already has an installer package, it must
10271            // be signed with the same cert as the caller.
10272            if (targetPackageSetting.installerPackageName != null) {
10273                PackageSetting setting = mSettings.mPackages.get(
10274                        targetPackageSetting.installerPackageName);
10275                // If the currently set package isn't valid, then it's always
10276                // okay to change it.
10277                if (setting != null) {
10278                    if (compareSignatures(callerSignature,
10279                            setting.signatures.mSignatures)
10280                            != PackageManager.SIGNATURE_MATCH) {
10281                        throw new SecurityException(
10282                                "Caller does not have same cert as old installer package "
10283                                + targetPackageSetting.installerPackageName);
10284                    }
10285                }
10286            }
10287
10288            // Okay!
10289            targetPackageSetting.installerPackageName = installerPackageName;
10290            scheduleWriteSettingsLocked();
10291        }
10292    }
10293
10294    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10295        // Queue up an async operation since the package installation may take a little while.
10296        mHandler.post(new Runnable() {
10297            public void run() {
10298                mHandler.removeCallbacks(this);
10299                 // Result object to be returned
10300                PackageInstalledInfo res = new PackageInstalledInfo();
10301                res.returnCode = currentStatus;
10302                res.uid = -1;
10303                res.pkg = null;
10304                res.removedInfo = new PackageRemovedInfo();
10305                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10306                    args.doPreInstall(res.returnCode);
10307                    synchronized (mInstallLock) {
10308                        installPackageTracedLI(args, res);
10309                    }
10310                    args.doPostInstall(res.returnCode, res.uid);
10311                }
10312
10313                // A restore should be performed at this point if (a) the install
10314                // succeeded, (b) the operation is not an update, and (c) the new
10315                // package has not opted out of backup participation.
10316                final boolean update = res.removedInfo.removedPackage != null;
10317                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10318                boolean doRestore = !update
10319                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10320
10321                // Set up the post-install work request bookkeeping.  This will be used
10322                // and cleaned up by the post-install event handling regardless of whether
10323                // there's a restore pass performed.  Token values are >= 1.
10324                int token;
10325                if (mNextInstallToken < 0) mNextInstallToken = 1;
10326                token = mNextInstallToken++;
10327
10328                PostInstallData data = new PostInstallData(args, res);
10329                mRunningInstalls.put(token, data);
10330                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10331
10332                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10333                    // Pass responsibility to the Backup Manager.  It will perform a
10334                    // restore if appropriate, then pass responsibility back to the
10335                    // Package Manager to run the post-install observer callbacks
10336                    // and broadcasts.
10337                    IBackupManager bm = IBackupManager.Stub.asInterface(
10338                            ServiceManager.getService(Context.BACKUP_SERVICE));
10339                    if (bm != null) {
10340                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10341                                + " to BM for possible restore");
10342                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10343                        try {
10344                            // TODO: http://b/22388012
10345                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10346                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10347                            } else {
10348                                doRestore = false;
10349                            }
10350                        } catch (RemoteException e) {
10351                            // can't happen; the backup manager is local
10352                        } catch (Exception e) {
10353                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10354                            doRestore = false;
10355                        }
10356                    } else {
10357                        Slog.e(TAG, "Backup Manager not found!");
10358                        doRestore = false;
10359                    }
10360                }
10361
10362                if (!doRestore) {
10363                    // No restore possible, or the Backup Manager was mysteriously not
10364                    // available -- just fire the post-install work request directly.
10365                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10366
10367                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10368
10369                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10370                    mHandler.sendMessage(msg);
10371                }
10372            }
10373        });
10374    }
10375
10376    private abstract class HandlerParams {
10377        private static final int MAX_RETRIES = 4;
10378
10379        /**
10380         * Number of times startCopy() has been attempted and had a non-fatal
10381         * error.
10382         */
10383        private int mRetries = 0;
10384
10385        /** User handle for the user requesting the information or installation. */
10386        private final UserHandle mUser;
10387        String traceMethod;
10388        int traceCookie;
10389
10390        HandlerParams(UserHandle user) {
10391            mUser = user;
10392        }
10393
10394        UserHandle getUser() {
10395            return mUser;
10396        }
10397
10398        HandlerParams setTraceMethod(String traceMethod) {
10399            this.traceMethod = traceMethod;
10400            return this;
10401        }
10402
10403        HandlerParams setTraceCookie(int traceCookie) {
10404            this.traceCookie = traceCookie;
10405            return this;
10406        }
10407
10408        final boolean startCopy() {
10409            boolean res;
10410            try {
10411                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10412
10413                if (++mRetries > MAX_RETRIES) {
10414                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10415                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10416                    handleServiceError();
10417                    return false;
10418                } else {
10419                    handleStartCopy();
10420                    res = true;
10421                }
10422            } catch (RemoteException e) {
10423                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10424                mHandler.sendEmptyMessage(MCS_RECONNECT);
10425                res = false;
10426            }
10427            handleReturnCode();
10428            return res;
10429        }
10430
10431        final void serviceError() {
10432            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10433            handleServiceError();
10434            handleReturnCode();
10435        }
10436
10437        abstract void handleStartCopy() throws RemoteException;
10438        abstract void handleServiceError();
10439        abstract void handleReturnCode();
10440    }
10441
10442    class MeasureParams extends HandlerParams {
10443        private final PackageStats mStats;
10444        private boolean mSuccess;
10445
10446        private final IPackageStatsObserver mObserver;
10447
10448        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10449            super(new UserHandle(stats.userHandle));
10450            mObserver = observer;
10451            mStats = stats;
10452        }
10453
10454        @Override
10455        public String toString() {
10456            return "MeasureParams{"
10457                + Integer.toHexString(System.identityHashCode(this))
10458                + " " + mStats.packageName + "}";
10459        }
10460
10461        @Override
10462        void handleStartCopy() throws RemoteException {
10463            synchronized (mInstallLock) {
10464                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10465            }
10466
10467            if (mSuccess) {
10468                final boolean mounted;
10469                if (Environment.isExternalStorageEmulated()) {
10470                    mounted = true;
10471                } else {
10472                    final String status = Environment.getExternalStorageState();
10473                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10474                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10475                }
10476
10477                if (mounted) {
10478                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10479
10480                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10481                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10482
10483                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10484                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10485
10486                    // Always subtract cache size, since it's a subdirectory
10487                    mStats.externalDataSize -= mStats.externalCacheSize;
10488
10489                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10490                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10491
10492                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10493                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10494                }
10495            }
10496        }
10497
10498        @Override
10499        void handleReturnCode() {
10500            if (mObserver != null) {
10501                try {
10502                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10503                } catch (RemoteException e) {
10504                    Slog.i(TAG, "Observer no longer exists.");
10505                }
10506            }
10507        }
10508
10509        @Override
10510        void handleServiceError() {
10511            Slog.e(TAG, "Could not measure application " + mStats.packageName
10512                            + " external storage");
10513        }
10514    }
10515
10516    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10517            throws RemoteException {
10518        long result = 0;
10519        for (File path : paths) {
10520            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10521        }
10522        return result;
10523    }
10524
10525    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10526        for (File path : paths) {
10527            try {
10528                mcs.clearDirectory(path.getAbsolutePath());
10529            } catch (RemoteException e) {
10530            }
10531        }
10532    }
10533
10534    static class OriginInfo {
10535        /**
10536         * Location where install is coming from, before it has been
10537         * copied/renamed into place. This could be a single monolithic APK
10538         * file, or a cluster directory. This location may be untrusted.
10539         */
10540        final File file;
10541        final String cid;
10542
10543        /**
10544         * Flag indicating that {@link #file} or {@link #cid} has already been
10545         * staged, meaning downstream users don't need to defensively copy the
10546         * contents.
10547         */
10548        final boolean staged;
10549
10550        /**
10551         * Flag indicating that {@link #file} or {@link #cid} is an already
10552         * installed app that is being moved.
10553         */
10554        final boolean existing;
10555
10556        final String resolvedPath;
10557        final File resolvedFile;
10558
10559        static OriginInfo fromNothing() {
10560            return new OriginInfo(null, null, false, false);
10561        }
10562
10563        static OriginInfo fromUntrustedFile(File file) {
10564            return new OriginInfo(file, null, false, false);
10565        }
10566
10567        static OriginInfo fromExistingFile(File file) {
10568            return new OriginInfo(file, null, false, true);
10569        }
10570
10571        static OriginInfo fromStagedFile(File file) {
10572            return new OriginInfo(file, null, true, false);
10573        }
10574
10575        static OriginInfo fromStagedContainer(String cid) {
10576            return new OriginInfo(null, cid, true, false);
10577        }
10578
10579        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10580            this.file = file;
10581            this.cid = cid;
10582            this.staged = staged;
10583            this.existing = existing;
10584
10585            if (cid != null) {
10586                resolvedPath = PackageHelper.getSdDir(cid);
10587                resolvedFile = new File(resolvedPath);
10588            } else if (file != null) {
10589                resolvedPath = file.getAbsolutePath();
10590                resolvedFile = file;
10591            } else {
10592                resolvedPath = null;
10593                resolvedFile = null;
10594            }
10595        }
10596    }
10597
10598    class MoveInfo {
10599        final int moveId;
10600        final String fromUuid;
10601        final String toUuid;
10602        final String packageName;
10603        final String dataAppName;
10604        final int appId;
10605        final String seinfo;
10606
10607        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10608                String dataAppName, int appId, String seinfo) {
10609            this.moveId = moveId;
10610            this.fromUuid = fromUuid;
10611            this.toUuid = toUuid;
10612            this.packageName = packageName;
10613            this.dataAppName = dataAppName;
10614            this.appId = appId;
10615            this.seinfo = seinfo;
10616        }
10617    }
10618
10619    class InstallParams extends HandlerParams {
10620        final OriginInfo origin;
10621        final MoveInfo move;
10622        final IPackageInstallObserver2 observer;
10623        int installFlags;
10624        final String installerPackageName;
10625        final String volumeUuid;
10626        final VerificationParams verificationParams;
10627        private InstallArgs mArgs;
10628        private int mRet;
10629        final String packageAbiOverride;
10630        final String[] grantedRuntimePermissions;
10631
10632        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10633                int installFlags, String installerPackageName, String volumeUuid,
10634                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10635                String[] grantedPermissions) {
10636            super(user);
10637            this.origin = origin;
10638            this.move = move;
10639            this.observer = observer;
10640            this.installFlags = installFlags;
10641            this.installerPackageName = installerPackageName;
10642            this.volumeUuid = volumeUuid;
10643            this.verificationParams = verificationParams;
10644            this.packageAbiOverride = packageAbiOverride;
10645            this.grantedRuntimePermissions = grantedPermissions;
10646        }
10647
10648        @Override
10649        public String toString() {
10650            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
10651                    + " file=" + origin.file + " cid=" + origin.cid + "}";
10652        }
10653
10654        public ManifestDigest getManifestDigest() {
10655            if (verificationParams == null) {
10656                return null;
10657            }
10658            return verificationParams.getManifestDigest();
10659        }
10660
10661        private int installLocationPolicy(PackageInfoLite pkgLite) {
10662            String packageName = pkgLite.packageName;
10663            int installLocation = pkgLite.installLocation;
10664            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10665            // reader
10666            synchronized (mPackages) {
10667                PackageParser.Package pkg = mPackages.get(packageName);
10668                if (pkg != null) {
10669                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10670                        // Check for downgrading.
10671                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
10672                            try {
10673                                checkDowngrade(pkg, pkgLite);
10674                            } catch (PackageManagerException e) {
10675                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
10676                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
10677                            }
10678                        }
10679                        // Check for updated system application.
10680                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
10681                            if (onSd) {
10682                                Slog.w(TAG, "Cannot install update to system app on sdcard");
10683                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
10684                            }
10685                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10686                        } else {
10687                            if (onSd) {
10688                                // Install flag overrides everything.
10689                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10690                            }
10691                            // If current upgrade specifies particular preference
10692                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
10693                                // Application explicitly specified internal.
10694                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10695                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
10696                                // App explictly prefers external. Let policy decide
10697                            } else {
10698                                // Prefer previous location
10699                                if (isExternal(pkg)) {
10700                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10701                                }
10702                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
10703                            }
10704                        }
10705                    } else {
10706                        // Invalid install. Return error code
10707                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
10708                    }
10709                }
10710            }
10711            // All the special cases have been taken care of.
10712            // Return result based on recommended install location.
10713            if (onSd) {
10714                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
10715            }
10716            return pkgLite.recommendedInstallLocation;
10717        }
10718
10719        /*
10720         * Invoke remote method to get package information and install
10721         * location values. Override install location based on default
10722         * policy if needed and then create install arguments based
10723         * on the install location.
10724         */
10725        public void handleStartCopy() throws RemoteException {
10726            int ret = PackageManager.INSTALL_SUCCEEDED;
10727
10728            // If we're already staged, we've firmly committed to an install location
10729            if (origin.staged) {
10730                if (origin.file != null) {
10731                    installFlags |= PackageManager.INSTALL_INTERNAL;
10732                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10733                } else if (origin.cid != null) {
10734                    installFlags |= PackageManager.INSTALL_EXTERNAL;
10735                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
10736                } else {
10737                    throw new IllegalStateException("Invalid stage location");
10738                }
10739            }
10740
10741            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10742            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
10743            PackageInfoLite pkgLite = null;
10744
10745            if (onInt && onSd) {
10746                // Check if both bits are set.
10747                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
10748                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10749            } else {
10750                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
10751                        packageAbiOverride);
10752
10753                /*
10754                 * If we have too little free space, try to free cache
10755                 * before giving up.
10756                 */
10757                if (!origin.staged && pkgLite.recommendedInstallLocation
10758                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10759                    // TODO: focus freeing disk space on the target device
10760                    final StorageManager storage = StorageManager.from(mContext);
10761                    final long lowThreshold = storage.getStorageLowBytes(
10762                            Environment.getDataDirectory());
10763
10764                    final long sizeBytes = mContainerService.calculateInstalledSize(
10765                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
10766
10767                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
10768                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
10769                                installFlags, packageAbiOverride);
10770                    }
10771
10772                    /*
10773                     * The cache free must have deleted the file we
10774                     * downloaded to install.
10775                     *
10776                     * TODO: fix the "freeCache" call to not delete
10777                     *       the file we care about.
10778                     */
10779                    if (pkgLite.recommendedInstallLocation
10780                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10781                        pkgLite.recommendedInstallLocation
10782                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
10783                    }
10784                }
10785            }
10786
10787            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10788                int loc = pkgLite.recommendedInstallLocation;
10789                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
10790                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10791                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
10792                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
10793                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
10794                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10795                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
10796                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
10797                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
10798                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
10799                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
10800                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
10801                } else {
10802                    // Override with defaults if needed.
10803                    loc = installLocationPolicy(pkgLite);
10804                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
10805                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
10806                    } else if (!onSd && !onInt) {
10807                        // Override install location with flags
10808                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
10809                            // Set the flag to install on external media.
10810                            installFlags |= PackageManager.INSTALL_EXTERNAL;
10811                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
10812                        } else {
10813                            // Make sure the flag for installing on external
10814                            // media is unset
10815                            installFlags |= PackageManager.INSTALL_INTERNAL;
10816                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
10817                        }
10818                    }
10819                }
10820            }
10821
10822            final InstallArgs args = createInstallArgs(this);
10823            mArgs = args;
10824
10825            if (ret == PackageManager.INSTALL_SUCCEEDED) {
10826                // TODO: http://b/22976637
10827                // Apps installed for "all" users use the device owner to verify the app
10828                UserHandle verifierUser = getUser();
10829                if (verifierUser == UserHandle.ALL) {
10830                    verifierUser = UserHandle.SYSTEM;
10831                }
10832
10833                /*
10834                 * Determine if we have any installed package verifiers. If we
10835                 * do, then we'll defer to them to verify the packages.
10836                 */
10837                final int requiredUid = mRequiredVerifierPackage == null ? -1
10838                        : getPackageUid(mRequiredVerifierPackage, verifierUser.getIdentifier());
10839                if (!origin.existing && requiredUid != -1
10840                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
10841                    final Intent verification = new Intent(
10842                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
10843                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
10844                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
10845                            PACKAGE_MIME_TYPE);
10846                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10847
10848                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
10849                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
10850                            verifierUser.getIdentifier());
10851
10852                    if (DEBUG_VERIFY) {
10853                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
10854                                + verification.toString() + " with " + pkgLite.verifiers.length
10855                                + " optional verifiers");
10856                    }
10857
10858                    final int verificationId = mPendingVerificationToken++;
10859
10860                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10861
10862                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
10863                            installerPackageName);
10864
10865                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
10866                            installFlags);
10867
10868                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
10869                            pkgLite.packageName);
10870
10871                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
10872                            pkgLite.versionCode);
10873
10874                    if (verificationParams != null) {
10875                        if (verificationParams.getVerificationURI() != null) {
10876                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
10877                                 verificationParams.getVerificationURI());
10878                        }
10879                        if (verificationParams.getOriginatingURI() != null) {
10880                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
10881                                  verificationParams.getOriginatingURI());
10882                        }
10883                        if (verificationParams.getReferrer() != null) {
10884                            verification.putExtra(Intent.EXTRA_REFERRER,
10885                                  verificationParams.getReferrer());
10886                        }
10887                        if (verificationParams.getOriginatingUid() >= 0) {
10888                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
10889                                  verificationParams.getOriginatingUid());
10890                        }
10891                        if (verificationParams.getInstallerUid() >= 0) {
10892                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
10893                                  verificationParams.getInstallerUid());
10894                        }
10895                    }
10896
10897                    final PackageVerificationState verificationState = new PackageVerificationState(
10898                            requiredUid, args);
10899
10900                    mPendingVerification.append(verificationId, verificationState);
10901
10902                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
10903                            receivers, verificationState);
10904
10905                    /*
10906                     * If any sufficient verifiers were listed in the package
10907                     * manifest, attempt to ask them.
10908                     */
10909                    if (sufficientVerifiers != null) {
10910                        final int N = sufficientVerifiers.size();
10911                        if (N == 0) {
10912                            Slog.i(TAG, "Additional verifiers required, but none installed.");
10913                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
10914                        } else {
10915                            for (int i = 0; i < N; i++) {
10916                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
10917
10918                                final Intent sufficientIntent = new Intent(verification);
10919                                sufficientIntent.setComponent(verifierComponent);
10920                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
10921                            }
10922                        }
10923                    }
10924
10925                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
10926                            mRequiredVerifierPackage, receivers);
10927                    if (ret == PackageManager.INSTALL_SUCCEEDED
10928                            && mRequiredVerifierPackage != null) {
10929                        Trace.asyncTraceBegin(
10930                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
10931                        /*
10932                         * Send the intent to the required verification agent,
10933                         * but only start the verification timeout after the
10934                         * target BroadcastReceivers have run.
10935                         */
10936                        verification.setComponent(requiredVerifierComponent);
10937                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
10938                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10939                                new BroadcastReceiver() {
10940                                    @Override
10941                                    public void onReceive(Context context, Intent intent) {
10942                                        final Message msg = mHandler
10943                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
10944                                        msg.arg1 = verificationId;
10945                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
10946                                    }
10947                                }, null, 0, null, null);
10948
10949                        /*
10950                         * We don't want the copy to proceed until verification
10951                         * succeeds, so null out this field.
10952                         */
10953                        mArgs = null;
10954                    }
10955                } else {
10956                    /*
10957                     * No package verification is enabled, so immediately start
10958                     * the remote call to initiate copy using temporary file.
10959                     */
10960                    ret = args.copyApk(mContainerService, true);
10961                }
10962            }
10963
10964            mRet = ret;
10965        }
10966
10967        @Override
10968        void handleReturnCode() {
10969            // If mArgs is null, then MCS couldn't be reached. When it
10970            // reconnects, it will try again to install. At that point, this
10971            // will succeed.
10972            if (mArgs != null) {
10973                processPendingInstall(mArgs, mRet);
10974            }
10975        }
10976
10977        @Override
10978        void handleServiceError() {
10979            mArgs = createInstallArgs(this);
10980            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10981        }
10982
10983        public boolean isForwardLocked() {
10984            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10985        }
10986    }
10987
10988    /**
10989     * Used during creation of InstallArgs
10990     *
10991     * @param installFlags package installation flags
10992     * @return true if should be installed on external storage
10993     */
10994    private static boolean installOnExternalAsec(int installFlags) {
10995        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10996            return false;
10997        }
10998        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10999            return true;
11000        }
11001        return false;
11002    }
11003
11004    /**
11005     * Used during creation of InstallArgs
11006     *
11007     * @param installFlags package installation flags
11008     * @return true if should be installed as forward locked
11009     */
11010    private static boolean installForwardLocked(int installFlags) {
11011        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11012    }
11013
11014    private InstallArgs createInstallArgs(InstallParams params) {
11015        if (params.move != null) {
11016            return new MoveInstallArgs(params);
11017        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11018            return new AsecInstallArgs(params);
11019        } else {
11020            return new FileInstallArgs(params);
11021        }
11022    }
11023
11024    /**
11025     * Create args that describe an existing installed package. Typically used
11026     * when cleaning up old installs, or used as a move source.
11027     */
11028    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11029            String resourcePath, String[] instructionSets) {
11030        final boolean isInAsec;
11031        if (installOnExternalAsec(installFlags)) {
11032            /* Apps on SD card are always in ASEC containers. */
11033            isInAsec = true;
11034        } else if (installForwardLocked(installFlags)
11035                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11036            /*
11037             * Forward-locked apps are only in ASEC containers if they're the
11038             * new style
11039             */
11040            isInAsec = true;
11041        } else {
11042            isInAsec = false;
11043        }
11044
11045        if (isInAsec) {
11046            return new AsecInstallArgs(codePath, instructionSets,
11047                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11048        } else {
11049            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11050        }
11051    }
11052
11053    static abstract class InstallArgs {
11054        /** @see InstallParams#origin */
11055        final OriginInfo origin;
11056        /** @see InstallParams#move */
11057        final MoveInfo move;
11058
11059        final IPackageInstallObserver2 observer;
11060        // Always refers to PackageManager flags only
11061        final int installFlags;
11062        final String installerPackageName;
11063        final String volumeUuid;
11064        final ManifestDigest manifestDigest;
11065        final UserHandle user;
11066        final String abiOverride;
11067        final String[] installGrantPermissions;
11068        /** If non-null, drop an async trace when the install completes */
11069        final String traceMethod;
11070        final int traceCookie;
11071
11072        // The list of instruction sets supported by this app. This is currently
11073        // only used during the rmdex() phase to clean up resources. We can get rid of this
11074        // if we move dex files under the common app path.
11075        /* nullable */ String[] instructionSets;
11076
11077        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11078                int installFlags, String installerPackageName, String volumeUuid,
11079                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
11080                String abiOverride, String[] installGrantPermissions,
11081                String traceMethod, int traceCookie) {
11082            this.origin = origin;
11083            this.move = move;
11084            this.installFlags = installFlags;
11085            this.observer = observer;
11086            this.installerPackageName = installerPackageName;
11087            this.volumeUuid = volumeUuid;
11088            this.manifestDigest = manifestDigest;
11089            this.user = user;
11090            this.instructionSets = instructionSets;
11091            this.abiOverride = abiOverride;
11092            this.installGrantPermissions = installGrantPermissions;
11093            this.traceMethod = traceMethod;
11094            this.traceCookie = traceCookie;
11095        }
11096
11097        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11098        abstract int doPreInstall(int status);
11099
11100        /**
11101         * Rename package into final resting place. All paths on the given
11102         * scanned package should be updated to reflect the rename.
11103         */
11104        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11105        abstract int doPostInstall(int status, int uid);
11106
11107        /** @see PackageSettingBase#codePathString */
11108        abstract String getCodePath();
11109        /** @see PackageSettingBase#resourcePathString */
11110        abstract String getResourcePath();
11111
11112        // Need installer lock especially for dex file removal.
11113        abstract void cleanUpResourcesLI();
11114        abstract boolean doPostDeleteLI(boolean delete);
11115
11116        /**
11117         * Called before the source arguments are copied. This is used mostly
11118         * for MoveParams when it needs to read the source file to put it in the
11119         * destination.
11120         */
11121        int doPreCopy() {
11122            return PackageManager.INSTALL_SUCCEEDED;
11123        }
11124
11125        /**
11126         * Called after the source arguments are copied. This is used mostly for
11127         * MoveParams when it needs to read the source file to put it in the
11128         * destination.
11129         *
11130         * @return
11131         */
11132        int doPostCopy(int uid) {
11133            return PackageManager.INSTALL_SUCCEEDED;
11134        }
11135
11136        protected boolean isFwdLocked() {
11137            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11138        }
11139
11140        protected boolean isExternalAsec() {
11141            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11142        }
11143
11144        UserHandle getUser() {
11145            return user;
11146        }
11147    }
11148
11149    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11150        if (!allCodePaths.isEmpty()) {
11151            if (instructionSets == null) {
11152                throw new IllegalStateException("instructionSet == null");
11153            }
11154            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11155            for (String codePath : allCodePaths) {
11156                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11157                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11158                    if (retCode < 0) {
11159                        Slog.w(TAG, "Couldn't remove dex file for package: "
11160                                + " at location " + codePath + ", retcode=" + retCode);
11161                        // we don't consider this to be a failure of the core package deletion
11162                    }
11163                }
11164            }
11165        }
11166    }
11167
11168    /**
11169     * Logic to handle installation of non-ASEC applications, including copying
11170     * and renaming logic.
11171     */
11172    class FileInstallArgs extends InstallArgs {
11173        private File codeFile;
11174        private File resourceFile;
11175
11176        // Example topology:
11177        // /data/app/com.example/base.apk
11178        // /data/app/com.example/split_foo.apk
11179        // /data/app/com.example/lib/arm/libfoo.so
11180        // /data/app/com.example/lib/arm64/libfoo.so
11181        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11182
11183        /** New install */
11184        FileInstallArgs(InstallParams params) {
11185            super(params.origin, params.move, params.observer, params.installFlags,
11186                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11187                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11188                    params.grantedRuntimePermissions,
11189                    params.traceMethod, params.traceCookie);
11190            if (isFwdLocked()) {
11191                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11192            }
11193        }
11194
11195        /** Existing install */
11196        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11197            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
11198                    null, null, null, 0);
11199            this.codeFile = (codePath != null) ? new File(codePath) : null;
11200            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11201        }
11202
11203        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11204            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11205            try {
11206                return doCopyApk(imcs, temp);
11207            } finally {
11208                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11209            }
11210        }
11211
11212        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11213            if (origin.staged) {
11214                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11215                codeFile = origin.file;
11216                resourceFile = origin.file;
11217                return PackageManager.INSTALL_SUCCEEDED;
11218            }
11219
11220            try {
11221                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
11222                codeFile = tempDir;
11223                resourceFile = tempDir;
11224            } catch (IOException e) {
11225                Slog.w(TAG, "Failed to create copy file: " + e);
11226                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11227            }
11228
11229            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11230                @Override
11231                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11232                    if (!FileUtils.isValidExtFilename(name)) {
11233                        throw new IllegalArgumentException("Invalid filename: " + name);
11234                    }
11235                    try {
11236                        final File file = new File(codeFile, name);
11237                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11238                                O_RDWR | O_CREAT, 0644);
11239                        Os.chmod(file.getAbsolutePath(), 0644);
11240                        return new ParcelFileDescriptor(fd);
11241                    } catch (ErrnoException e) {
11242                        throw new RemoteException("Failed to open: " + e.getMessage());
11243                    }
11244                }
11245            };
11246
11247            int ret = PackageManager.INSTALL_SUCCEEDED;
11248            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11249            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11250                Slog.e(TAG, "Failed to copy package");
11251                return ret;
11252            }
11253
11254            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11255            NativeLibraryHelper.Handle handle = null;
11256            try {
11257                handle = NativeLibraryHelper.Handle.create(codeFile);
11258                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11259                        abiOverride);
11260            } catch (IOException e) {
11261                Slog.e(TAG, "Copying native libraries failed", e);
11262                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11263            } finally {
11264                IoUtils.closeQuietly(handle);
11265            }
11266
11267            return ret;
11268        }
11269
11270        int doPreInstall(int status) {
11271            if (status != PackageManager.INSTALL_SUCCEEDED) {
11272                cleanUp();
11273            }
11274            return status;
11275        }
11276
11277        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11278            if (status != PackageManager.INSTALL_SUCCEEDED) {
11279                cleanUp();
11280                return false;
11281            }
11282
11283            final File targetDir = codeFile.getParentFile();
11284            final File beforeCodeFile = codeFile;
11285            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11286
11287            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11288            try {
11289                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11290            } catch (ErrnoException e) {
11291                Slog.w(TAG, "Failed to rename", e);
11292                return false;
11293            }
11294
11295            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11296                Slog.w(TAG, "Failed to restorecon");
11297                return false;
11298            }
11299
11300            // Reflect the rename internally
11301            codeFile = afterCodeFile;
11302            resourceFile = afterCodeFile;
11303
11304            // Reflect the rename in scanned details
11305            pkg.codePath = afterCodeFile.getAbsolutePath();
11306            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11307                    pkg.baseCodePath);
11308            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11309                    pkg.splitCodePaths);
11310
11311            // Reflect the rename in app info
11312            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11313            pkg.applicationInfo.setCodePath(pkg.codePath);
11314            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11315            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11316            pkg.applicationInfo.setResourcePath(pkg.codePath);
11317            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11318            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11319
11320            return true;
11321        }
11322
11323        int doPostInstall(int status, int uid) {
11324            if (status != PackageManager.INSTALL_SUCCEEDED) {
11325                cleanUp();
11326            }
11327            return status;
11328        }
11329
11330        @Override
11331        String getCodePath() {
11332            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11333        }
11334
11335        @Override
11336        String getResourcePath() {
11337            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11338        }
11339
11340        private boolean cleanUp() {
11341            if (codeFile == null || !codeFile.exists()) {
11342                return false;
11343            }
11344
11345            if (codeFile.isDirectory()) {
11346                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11347            } else {
11348                codeFile.delete();
11349            }
11350
11351            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11352                resourceFile.delete();
11353            }
11354
11355            return true;
11356        }
11357
11358        void cleanUpResourcesLI() {
11359            // Try enumerating all code paths before deleting
11360            List<String> allCodePaths = Collections.EMPTY_LIST;
11361            if (codeFile != null && codeFile.exists()) {
11362                try {
11363                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11364                    allCodePaths = pkg.getAllCodePaths();
11365                } catch (PackageParserException e) {
11366                    // Ignored; we tried our best
11367                }
11368            }
11369
11370            cleanUp();
11371            removeDexFiles(allCodePaths, instructionSets);
11372        }
11373
11374        boolean doPostDeleteLI(boolean delete) {
11375            // XXX err, shouldn't we respect the delete flag?
11376            cleanUpResourcesLI();
11377            return true;
11378        }
11379    }
11380
11381    private boolean isAsecExternal(String cid) {
11382        final String asecPath = PackageHelper.getSdFilesystem(cid);
11383        return !asecPath.startsWith(mAsecInternalPath);
11384    }
11385
11386    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11387            PackageManagerException {
11388        if (copyRet < 0) {
11389            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11390                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11391                throw new PackageManagerException(copyRet, message);
11392            }
11393        }
11394    }
11395
11396    /**
11397     * Extract the MountService "container ID" from the full code path of an
11398     * .apk.
11399     */
11400    static String cidFromCodePath(String fullCodePath) {
11401        int eidx = fullCodePath.lastIndexOf("/");
11402        String subStr1 = fullCodePath.substring(0, eidx);
11403        int sidx = subStr1.lastIndexOf("/");
11404        return subStr1.substring(sidx+1, eidx);
11405    }
11406
11407    /**
11408     * Logic to handle installation of ASEC applications, including copying and
11409     * renaming logic.
11410     */
11411    class AsecInstallArgs extends InstallArgs {
11412        static final String RES_FILE_NAME = "pkg.apk";
11413        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11414
11415        String cid;
11416        String packagePath;
11417        String resourcePath;
11418
11419        /** New install */
11420        AsecInstallArgs(InstallParams params) {
11421            super(params.origin, params.move, params.observer, params.installFlags,
11422                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11423                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11424                    params.grantedRuntimePermissions,
11425                    params.traceMethod, params.traceCookie);
11426        }
11427
11428        /** Existing install */
11429        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11430                        boolean isExternal, boolean isForwardLocked) {
11431            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11432                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11433                    instructionSets, null, null, null, 0);
11434            // Hackily pretend we're still looking at a full code path
11435            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11436                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11437            }
11438
11439            // Extract cid from fullCodePath
11440            int eidx = fullCodePath.lastIndexOf("/");
11441            String subStr1 = fullCodePath.substring(0, eidx);
11442            int sidx = subStr1.lastIndexOf("/");
11443            cid = subStr1.substring(sidx+1, eidx);
11444            setMountPath(subStr1);
11445        }
11446
11447        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11448            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11449                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
11450                    instructionSets, null, null, null, 0);
11451            this.cid = cid;
11452            setMountPath(PackageHelper.getSdDir(cid));
11453        }
11454
11455        void createCopyFile() {
11456            cid = mInstallerService.allocateExternalStageCidLegacy();
11457        }
11458
11459        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11460            if (origin.staged) {
11461                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11462                cid = origin.cid;
11463                setMountPath(PackageHelper.getSdDir(cid));
11464                return PackageManager.INSTALL_SUCCEEDED;
11465            }
11466
11467            if (temp) {
11468                createCopyFile();
11469            } else {
11470                /*
11471                 * Pre-emptively destroy the container since it's destroyed if
11472                 * copying fails due to it existing anyway.
11473                 */
11474                PackageHelper.destroySdDir(cid);
11475            }
11476
11477            final String newMountPath = imcs.copyPackageToContainer(
11478                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11479                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11480
11481            if (newMountPath != null) {
11482                setMountPath(newMountPath);
11483                return PackageManager.INSTALL_SUCCEEDED;
11484            } else {
11485                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11486            }
11487        }
11488
11489        @Override
11490        String getCodePath() {
11491            return packagePath;
11492        }
11493
11494        @Override
11495        String getResourcePath() {
11496            return resourcePath;
11497        }
11498
11499        int doPreInstall(int status) {
11500            if (status != PackageManager.INSTALL_SUCCEEDED) {
11501                // Destroy container
11502                PackageHelper.destroySdDir(cid);
11503            } else {
11504                boolean mounted = PackageHelper.isContainerMounted(cid);
11505                if (!mounted) {
11506                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11507                            Process.SYSTEM_UID);
11508                    if (newMountPath != null) {
11509                        setMountPath(newMountPath);
11510                    } else {
11511                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11512                    }
11513                }
11514            }
11515            return status;
11516        }
11517
11518        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11519            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11520            String newMountPath = null;
11521            if (PackageHelper.isContainerMounted(cid)) {
11522                // Unmount the container
11523                if (!PackageHelper.unMountSdDir(cid)) {
11524                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11525                    return false;
11526                }
11527            }
11528            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11529                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11530                        " which might be stale. Will try to clean up.");
11531                // Clean up the stale container and proceed to recreate.
11532                if (!PackageHelper.destroySdDir(newCacheId)) {
11533                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11534                    return false;
11535                }
11536                // Successfully cleaned up stale container. Try to rename again.
11537                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11538                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11539                            + " inspite of cleaning it up.");
11540                    return false;
11541                }
11542            }
11543            if (!PackageHelper.isContainerMounted(newCacheId)) {
11544                Slog.w(TAG, "Mounting container " + newCacheId);
11545                newMountPath = PackageHelper.mountSdDir(newCacheId,
11546                        getEncryptKey(), Process.SYSTEM_UID);
11547            } else {
11548                newMountPath = PackageHelper.getSdDir(newCacheId);
11549            }
11550            if (newMountPath == null) {
11551                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11552                return false;
11553            }
11554            Log.i(TAG, "Succesfully renamed " + cid +
11555                    " to " + newCacheId +
11556                    " at new path: " + newMountPath);
11557            cid = newCacheId;
11558
11559            final File beforeCodeFile = new File(packagePath);
11560            setMountPath(newMountPath);
11561            final File afterCodeFile = new File(packagePath);
11562
11563            // Reflect the rename in scanned details
11564            pkg.codePath = afterCodeFile.getAbsolutePath();
11565            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11566                    pkg.baseCodePath);
11567            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11568                    pkg.splitCodePaths);
11569
11570            // Reflect the rename in app info
11571            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11572            pkg.applicationInfo.setCodePath(pkg.codePath);
11573            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11574            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11575            pkg.applicationInfo.setResourcePath(pkg.codePath);
11576            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11577            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11578
11579            return true;
11580        }
11581
11582        private void setMountPath(String mountPath) {
11583            final File mountFile = new File(mountPath);
11584
11585            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11586            if (monolithicFile.exists()) {
11587                packagePath = monolithicFile.getAbsolutePath();
11588                if (isFwdLocked()) {
11589                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11590                } else {
11591                    resourcePath = packagePath;
11592                }
11593            } else {
11594                packagePath = mountFile.getAbsolutePath();
11595                resourcePath = packagePath;
11596            }
11597        }
11598
11599        int doPostInstall(int status, int uid) {
11600            if (status != PackageManager.INSTALL_SUCCEEDED) {
11601                cleanUp();
11602            } else {
11603                final int groupOwner;
11604                final String protectedFile;
11605                if (isFwdLocked()) {
11606                    groupOwner = UserHandle.getSharedAppGid(uid);
11607                    protectedFile = RES_FILE_NAME;
11608                } else {
11609                    groupOwner = -1;
11610                    protectedFile = null;
11611                }
11612
11613                if (uid < Process.FIRST_APPLICATION_UID
11614                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11615                    Slog.e(TAG, "Failed to finalize " + cid);
11616                    PackageHelper.destroySdDir(cid);
11617                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11618                }
11619
11620                boolean mounted = PackageHelper.isContainerMounted(cid);
11621                if (!mounted) {
11622                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11623                }
11624            }
11625            return status;
11626        }
11627
11628        private void cleanUp() {
11629            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
11630
11631            // Destroy secure container
11632            PackageHelper.destroySdDir(cid);
11633        }
11634
11635        private List<String> getAllCodePaths() {
11636            final File codeFile = new File(getCodePath());
11637            if (codeFile != null && codeFile.exists()) {
11638                try {
11639                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11640                    return pkg.getAllCodePaths();
11641                } catch (PackageParserException e) {
11642                    // Ignored; we tried our best
11643                }
11644            }
11645            return Collections.EMPTY_LIST;
11646        }
11647
11648        void cleanUpResourcesLI() {
11649            // Enumerate all code paths before deleting
11650            cleanUpResourcesLI(getAllCodePaths());
11651        }
11652
11653        private void cleanUpResourcesLI(List<String> allCodePaths) {
11654            cleanUp();
11655            removeDexFiles(allCodePaths, instructionSets);
11656        }
11657
11658        String getPackageName() {
11659            return getAsecPackageName(cid);
11660        }
11661
11662        boolean doPostDeleteLI(boolean delete) {
11663            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
11664            final List<String> allCodePaths = getAllCodePaths();
11665            boolean mounted = PackageHelper.isContainerMounted(cid);
11666            if (mounted) {
11667                // Unmount first
11668                if (PackageHelper.unMountSdDir(cid)) {
11669                    mounted = false;
11670                }
11671            }
11672            if (!mounted && delete) {
11673                cleanUpResourcesLI(allCodePaths);
11674            }
11675            return !mounted;
11676        }
11677
11678        @Override
11679        int doPreCopy() {
11680            if (isFwdLocked()) {
11681                if (!PackageHelper.fixSdPermissions(cid,
11682                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
11683                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11684                }
11685            }
11686
11687            return PackageManager.INSTALL_SUCCEEDED;
11688        }
11689
11690        @Override
11691        int doPostCopy(int uid) {
11692            if (isFwdLocked()) {
11693                if (uid < Process.FIRST_APPLICATION_UID
11694                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
11695                                RES_FILE_NAME)) {
11696                    Slog.e(TAG, "Failed to finalize " + cid);
11697                    PackageHelper.destroySdDir(cid);
11698                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11699                }
11700            }
11701
11702            return PackageManager.INSTALL_SUCCEEDED;
11703        }
11704    }
11705
11706    /**
11707     * Logic to handle movement of existing installed applications.
11708     */
11709    class MoveInstallArgs extends InstallArgs {
11710        private File codeFile;
11711        private File resourceFile;
11712
11713        /** New install */
11714        MoveInstallArgs(InstallParams params) {
11715            super(params.origin, params.move, params.observer, params.installFlags,
11716                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
11717                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11718                    params.grantedRuntimePermissions,
11719                    params.traceMethod, params.traceCookie);
11720        }
11721
11722        int copyApk(IMediaContainerService imcs, boolean temp) {
11723            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
11724                    + move.fromUuid + " to " + move.toUuid);
11725            synchronized (mInstaller) {
11726                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
11727                        move.dataAppName, move.appId, move.seinfo) != 0) {
11728                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11729                }
11730            }
11731
11732            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
11733            resourceFile = codeFile;
11734            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
11735
11736            return PackageManager.INSTALL_SUCCEEDED;
11737        }
11738
11739        int doPreInstall(int status) {
11740            if (status != PackageManager.INSTALL_SUCCEEDED) {
11741                cleanUp(move.toUuid);
11742            }
11743            return status;
11744        }
11745
11746        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11747            if (status != PackageManager.INSTALL_SUCCEEDED) {
11748                cleanUp(move.toUuid);
11749                return false;
11750            }
11751
11752            // Reflect the move in app info
11753            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11754            pkg.applicationInfo.setCodePath(pkg.codePath);
11755            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11756            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11757            pkg.applicationInfo.setResourcePath(pkg.codePath);
11758            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11759            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11760
11761            return true;
11762        }
11763
11764        int doPostInstall(int status, int uid) {
11765            if (status == PackageManager.INSTALL_SUCCEEDED) {
11766                cleanUp(move.fromUuid);
11767            } else {
11768                cleanUp(move.toUuid);
11769            }
11770            return status;
11771        }
11772
11773        @Override
11774        String getCodePath() {
11775            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11776        }
11777
11778        @Override
11779        String getResourcePath() {
11780            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11781        }
11782
11783        private boolean cleanUp(String volumeUuid) {
11784            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
11785                    move.dataAppName);
11786            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
11787            synchronized (mInstallLock) {
11788                // Clean up both app data and code
11789                removeDataDirsLI(volumeUuid, move.packageName);
11790                if (codeFile.isDirectory()) {
11791                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11792                } else {
11793                    codeFile.delete();
11794                }
11795            }
11796            return true;
11797        }
11798
11799        void cleanUpResourcesLI() {
11800            throw new UnsupportedOperationException();
11801        }
11802
11803        boolean doPostDeleteLI(boolean delete) {
11804            throw new UnsupportedOperationException();
11805        }
11806    }
11807
11808    static String getAsecPackageName(String packageCid) {
11809        int idx = packageCid.lastIndexOf("-");
11810        if (idx == -1) {
11811            return packageCid;
11812        }
11813        return packageCid.substring(0, idx);
11814    }
11815
11816    // Utility method used to create code paths based on package name and available index.
11817    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
11818        String idxStr = "";
11819        int idx = 1;
11820        // Fall back to default value of idx=1 if prefix is not
11821        // part of oldCodePath
11822        if (oldCodePath != null) {
11823            String subStr = oldCodePath;
11824            // Drop the suffix right away
11825            if (suffix != null && subStr.endsWith(suffix)) {
11826                subStr = subStr.substring(0, subStr.length() - suffix.length());
11827            }
11828            // If oldCodePath already contains prefix find out the
11829            // ending index to either increment or decrement.
11830            int sidx = subStr.lastIndexOf(prefix);
11831            if (sidx != -1) {
11832                subStr = subStr.substring(sidx + prefix.length());
11833                if (subStr != null) {
11834                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
11835                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
11836                    }
11837                    try {
11838                        idx = Integer.parseInt(subStr);
11839                        if (idx <= 1) {
11840                            idx++;
11841                        } else {
11842                            idx--;
11843                        }
11844                    } catch(NumberFormatException e) {
11845                    }
11846                }
11847            }
11848        }
11849        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
11850        return prefix + idxStr;
11851    }
11852
11853    private File getNextCodePath(File targetDir, String packageName) {
11854        int suffix = 1;
11855        File result;
11856        do {
11857            result = new File(targetDir, packageName + "-" + suffix);
11858            suffix++;
11859        } while (result.exists());
11860        return result;
11861    }
11862
11863    // Utility method that returns the relative package path with respect
11864    // to the installation directory. Like say for /data/data/com.test-1.apk
11865    // string com.test-1 is returned.
11866    static String deriveCodePathName(String codePath) {
11867        if (codePath == null) {
11868            return null;
11869        }
11870        final File codeFile = new File(codePath);
11871        final String name = codeFile.getName();
11872        if (codeFile.isDirectory()) {
11873            return name;
11874        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
11875            final int lastDot = name.lastIndexOf('.');
11876            return name.substring(0, lastDot);
11877        } else {
11878            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
11879            return null;
11880        }
11881    }
11882
11883    class PackageInstalledInfo {
11884        String name;
11885        int uid;
11886        // The set of users that originally had this package installed.
11887        int[] origUsers;
11888        // The set of users that now have this package installed.
11889        int[] newUsers;
11890        PackageParser.Package pkg;
11891        int returnCode;
11892        String returnMsg;
11893        PackageRemovedInfo removedInfo;
11894
11895        public void setError(int code, String msg) {
11896            returnCode = code;
11897            returnMsg = msg;
11898            Slog.w(TAG, msg);
11899        }
11900
11901        public void setError(String msg, PackageParserException e) {
11902            returnCode = e.error;
11903            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11904            Slog.w(TAG, msg, e);
11905        }
11906
11907        public void setError(String msg, PackageManagerException e) {
11908            returnCode = e.error;
11909            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
11910            Slog.w(TAG, msg, e);
11911        }
11912
11913        // In some error cases we want to convey more info back to the observer
11914        String origPackage;
11915        String origPermission;
11916    }
11917
11918    /*
11919     * Install a non-existing package.
11920     */
11921    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11922            UserHandle user, String installerPackageName, String volumeUuid,
11923            PackageInstalledInfo res) {
11924        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
11925
11926        // Remember this for later, in case we need to rollback this install
11927        String pkgName = pkg.packageName;
11928
11929        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
11930        // TODO: b/23350563
11931        final boolean dataDirExists = Environment
11932                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
11933
11934        synchronized(mPackages) {
11935            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
11936                // A package with the same name is already installed, though
11937                // it has been renamed to an older name.  The package we
11938                // are trying to install should be installed as an update to
11939                // the existing one, but that has not been requested, so bail.
11940                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11941                        + " without first uninstalling package running as "
11942                        + mSettings.mRenamedPackages.get(pkgName));
11943                return;
11944            }
11945            if (mPackages.containsKey(pkgName)) {
11946                // Don't allow installation over an existing package with the same name.
11947                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
11948                        + " without first uninstalling.");
11949                return;
11950            }
11951        }
11952
11953        try {
11954            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
11955                    System.currentTimeMillis(), user);
11956
11957            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
11958            // delete the partially installed application. the data directory will have to be
11959            // restored if it was already existing
11960            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11961                // remove package from internal structures.  Note that we want deletePackageX to
11962                // delete the package data and cache directories that it created in
11963                // scanPackageLocked, unless those directories existed before we even tried to
11964                // install.
11965                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
11966                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
11967                                res.removedInfo, true);
11968            }
11969
11970        } catch (PackageManagerException e) {
11971            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11972        }
11973
11974        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11975    }
11976
11977    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
11978        // Can't rotate keys during boot or if sharedUser.
11979        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
11980                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
11981            return false;
11982        }
11983        // app is using upgradeKeySets; make sure all are valid
11984        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11985        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
11986        for (int i = 0; i < upgradeKeySets.length; i++) {
11987            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
11988                Slog.wtf(TAG, "Package "
11989                         + (oldPs.name != null ? oldPs.name : "<null>")
11990                         + " contains upgrade-key-set reference to unknown key-set: "
11991                         + upgradeKeySets[i]
11992                         + " reverting to signatures check.");
11993                return false;
11994            }
11995        }
11996        return true;
11997    }
11998
11999    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12000        // Upgrade keysets are being used.  Determine if new package has a superset of the
12001        // required keys.
12002        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12003        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12004        for (int i = 0; i < upgradeKeySets.length; i++) {
12005            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12006            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12007                return true;
12008            }
12009        }
12010        return false;
12011    }
12012
12013    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12014            UserHandle user, String installerPackageName, String volumeUuid,
12015            PackageInstalledInfo res) {
12016        final PackageParser.Package oldPackage;
12017        final String pkgName = pkg.packageName;
12018        final int[] allUsers;
12019        final boolean[] perUserInstalled;
12020
12021        // First find the old package info and check signatures
12022        synchronized(mPackages) {
12023            oldPackage = mPackages.get(pkgName);
12024            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12025            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12026            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12027                if(!checkUpgradeKeySetLP(ps, pkg)) {
12028                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12029                            "New package not signed by keys specified by upgrade-keysets: "
12030                            + pkgName);
12031                    return;
12032                }
12033            } else {
12034                // default to original signature matching
12035                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12036                    != PackageManager.SIGNATURE_MATCH) {
12037                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12038                            "New package has a different signature: " + pkgName);
12039                    return;
12040                }
12041            }
12042
12043            // In case of rollback, remember per-user/profile install state
12044            allUsers = sUserManager.getUserIds();
12045            perUserInstalled = new boolean[allUsers.length];
12046            for (int i = 0; i < allUsers.length; i++) {
12047                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12048            }
12049        }
12050
12051        boolean sysPkg = (isSystemApp(oldPackage));
12052        if (sysPkg) {
12053            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12054                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12055        } else {
12056            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12057                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12058        }
12059    }
12060
12061    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12062            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12063            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12064            String volumeUuid, PackageInstalledInfo res) {
12065        String pkgName = deletedPackage.packageName;
12066        boolean deletedPkg = true;
12067        boolean updatedSettings = false;
12068
12069        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12070                + deletedPackage);
12071        long origUpdateTime;
12072        if (pkg.mExtras != null) {
12073            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12074        } else {
12075            origUpdateTime = 0;
12076        }
12077
12078        // First delete the existing package while retaining the data directory
12079        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12080                res.removedInfo, true)) {
12081            // If the existing package wasn't successfully deleted
12082            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12083            deletedPkg = false;
12084        } else {
12085            // Successfully deleted the old package; proceed with replace.
12086
12087            // If deleted package lived in a container, give users a chance to
12088            // relinquish resources before killing.
12089            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12090                if (DEBUG_INSTALL) {
12091                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12092                }
12093                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12094                final ArrayList<String> pkgList = new ArrayList<String>(1);
12095                pkgList.add(deletedPackage.applicationInfo.packageName);
12096                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12097            }
12098
12099            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12100            try {
12101                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12102                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12103                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12104                        perUserInstalled, res, user);
12105                updatedSettings = true;
12106            } catch (PackageManagerException e) {
12107                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12108            }
12109        }
12110
12111        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12112            // remove package from internal structures.  Note that we want deletePackageX to
12113            // delete the package data and cache directories that it created in
12114            // scanPackageLocked, unless those directories existed before we even tried to
12115            // install.
12116            if(updatedSettings) {
12117                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12118                deletePackageLI(
12119                        pkgName, null, true, allUsers, perUserInstalled,
12120                        PackageManager.DELETE_KEEP_DATA,
12121                                res.removedInfo, true);
12122            }
12123            // Since we failed to install the new package we need to restore the old
12124            // package that we deleted.
12125            if (deletedPkg) {
12126                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12127                File restoreFile = new File(deletedPackage.codePath);
12128                // Parse old package
12129                boolean oldExternal = isExternal(deletedPackage);
12130                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12131                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12132                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12133                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12134                try {
12135                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12136                            UserHandle.SYSTEM);
12137                } catch (PackageManagerException e) {
12138                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12139                            + e.getMessage());
12140                    return;
12141                }
12142                // Restore of old package succeeded. Update permissions.
12143                // writer
12144                synchronized (mPackages) {
12145                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12146                            UPDATE_PERMISSIONS_ALL);
12147                    // can downgrade to reader
12148                    mSettings.writeLPr();
12149                }
12150                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12151            }
12152        }
12153    }
12154
12155    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12156            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12157            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12158            String volumeUuid, PackageInstalledInfo res) {
12159        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12160                + ", old=" + deletedPackage);
12161        boolean disabledSystem = false;
12162        boolean updatedSettings = false;
12163        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12164        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12165                != 0) {
12166            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12167        }
12168        String packageName = deletedPackage.packageName;
12169        if (packageName == null) {
12170            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12171                    "Attempt to delete null packageName.");
12172            return;
12173        }
12174        PackageParser.Package oldPkg;
12175        PackageSetting oldPkgSetting;
12176        // reader
12177        synchronized (mPackages) {
12178            oldPkg = mPackages.get(packageName);
12179            oldPkgSetting = mSettings.mPackages.get(packageName);
12180            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12181                    (oldPkgSetting == null)) {
12182                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12183                        "Couldn't find package:" + packageName + " information");
12184                return;
12185            }
12186        }
12187
12188        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12189
12190        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12191        res.removedInfo.removedPackage = packageName;
12192        // Remove existing system package
12193        removePackageLI(oldPkgSetting, true);
12194        // writer
12195        synchronized (mPackages) {
12196            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12197            if (!disabledSystem && deletedPackage != null) {
12198                // We didn't need to disable the .apk as a current system package,
12199                // which means we are replacing another update that is already
12200                // installed.  We need to make sure to delete the older one's .apk.
12201                res.removedInfo.args = createInstallArgsForExisting(0,
12202                        deletedPackage.applicationInfo.getCodePath(),
12203                        deletedPackage.applicationInfo.getResourcePath(),
12204                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12205            } else {
12206                res.removedInfo.args = null;
12207            }
12208        }
12209
12210        // Successfully disabled the old package. Now proceed with re-installation
12211        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12212
12213        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12214        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12215
12216        PackageParser.Package newPackage = null;
12217        try {
12218            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12219            if (newPackage.mExtras != null) {
12220                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12221                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12222                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12223
12224                // is the update attempting to change shared user? that isn't going to work...
12225                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12226                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12227                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12228                            + " to " + newPkgSetting.sharedUser);
12229                    updatedSettings = true;
12230                }
12231            }
12232
12233            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12234                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12235                        perUserInstalled, res, user);
12236                updatedSettings = true;
12237            }
12238
12239        } catch (PackageManagerException e) {
12240            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12241        }
12242
12243        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12244            // Re installation failed. Restore old information
12245            // Remove new pkg information
12246            if (newPackage != null) {
12247                removeInstalledPackageLI(newPackage, true);
12248            }
12249            // Add back the old system package
12250            try {
12251                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12252            } catch (PackageManagerException e) {
12253                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12254            }
12255            // Restore the old system information in Settings
12256            synchronized (mPackages) {
12257                if (disabledSystem) {
12258                    mSettings.enableSystemPackageLPw(packageName);
12259                }
12260                if (updatedSettings) {
12261                    mSettings.setInstallerPackageName(packageName,
12262                            oldPkgSetting.installerPackageName);
12263                }
12264                mSettings.writeLPr();
12265            }
12266        }
12267    }
12268
12269    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12270        // Collect all used permissions in the UID
12271        ArraySet<String> usedPermissions = new ArraySet<>();
12272        final int packageCount = su.packages.size();
12273        for (int i = 0; i < packageCount; i++) {
12274            PackageSetting ps = su.packages.valueAt(i);
12275            if (ps.pkg == null) {
12276                continue;
12277            }
12278            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12279            for (int j = 0; j < requestedPermCount; j++) {
12280                String permission = ps.pkg.requestedPermissions.get(j);
12281                BasePermission bp = mSettings.mPermissions.get(permission);
12282                if (bp != null) {
12283                    usedPermissions.add(permission);
12284                }
12285            }
12286        }
12287
12288        PermissionsState permissionsState = su.getPermissionsState();
12289        // Prune install permissions
12290        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12291        final int installPermCount = installPermStates.size();
12292        for (int i = installPermCount - 1; i >= 0;  i--) {
12293            PermissionState permissionState = installPermStates.get(i);
12294            if (!usedPermissions.contains(permissionState.getName())) {
12295                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12296                if (bp != null) {
12297                    permissionsState.revokeInstallPermission(bp);
12298                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12299                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12300                }
12301            }
12302        }
12303
12304        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12305
12306        // Prune runtime permissions
12307        for (int userId : allUserIds) {
12308            List<PermissionState> runtimePermStates = permissionsState
12309                    .getRuntimePermissionStates(userId);
12310            final int runtimePermCount = runtimePermStates.size();
12311            for (int i = runtimePermCount - 1; i >= 0; i--) {
12312                PermissionState permissionState = runtimePermStates.get(i);
12313                if (!usedPermissions.contains(permissionState.getName())) {
12314                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12315                    if (bp != null) {
12316                        permissionsState.revokeRuntimePermission(bp, userId);
12317                        permissionsState.updatePermissionFlags(bp, userId,
12318                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12319                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12320                                runtimePermissionChangedUserIds, userId);
12321                    }
12322                }
12323            }
12324        }
12325
12326        return runtimePermissionChangedUserIds;
12327    }
12328
12329    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12330            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12331            UserHandle user) {
12332        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12333
12334        String pkgName = newPackage.packageName;
12335        synchronized (mPackages) {
12336            //write settings. the installStatus will be incomplete at this stage.
12337            //note that the new package setting would have already been
12338            //added to mPackages. It hasn't been persisted yet.
12339            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12340            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12341            mSettings.writeLPr();
12342            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12343        }
12344
12345        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12346        synchronized (mPackages) {
12347            updatePermissionsLPw(newPackage.packageName, newPackage,
12348                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12349                            ? UPDATE_PERMISSIONS_ALL : 0));
12350            // For system-bundled packages, we assume that installing an upgraded version
12351            // of the package implies that the user actually wants to run that new code,
12352            // so we enable the package.
12353            PackageSetting ps = mSettings.mPackages.get(pkgName);
12354            if (ps != null) {
12355                if (isSystemApp(newPackage)) {
12356                    // NB: implicit assumption that system package upgrades apply to all users
12357                    if (DEBUG_INSTALL) {
12358                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12359                    }
12360                    if (res.origUsers != null) {
12361                        for (int userHandle : res.origUsers) {
12362                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12363                                    userHandle, installerPackageName);
12364                        }
12365                    }
12366                    // Also convey the prior install/uninstall state
12367                    if (allUsers != null && perUserInstalled != null) {
12368                        for (int i = 0; i < allUsers.length; i++) {
12369                            if (DEBUG_INSTALL) {
12370                                Slog.d(TAG, "    user " + allUsers[i]
12371                                        + " => " + perUserInstalled[i]);
12372                            }
12373                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12374                        }
12375                        // these install state changes will be persisted in the
12376                        // upcoming call to mSettings.writeLPr().
12377                    }
12378                }
12379                // It's implied that when a user requests installation, they want the app to be
12380                // installed and enabled.
12381                int userId = user.getIdentifier();
12382                if (userId != UserHandle.USER_ALL) {
12383                    ps.setInstalled(true, userId);
12384                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12385                }
12386            }
12387            res.name = pkgName;
12388            res.uid = newPackage.applicationInfo.uid;
12389            res.pkg = newPackage;
12390            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12391            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12392            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12393            //to update install status
12394            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12395            mSettings.writeLPr();
12396            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12397        }
12398
12399        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12400    }
12401
12402    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12403        try {
12404            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12405            installPackageLI(args, res);
12406        } finally {
12407            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12408        }
12409    }
12410
12411    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12412        final int installFlags = args.installFlags;
12413        final String installerPackageName = args.installerPackageName;
12414        final String volumeUuid = args.volumeUuid;
12415        final File tmpPackageFile = new File(args.getCodePath());
12416        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12417        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12418                || (args.volumeUuid != null));
12419        final boolean quickInstall = ((installFlags & PackageManager.INSTALL_QUICK) != 0);
12420        boolean replace = false;
12421        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12422        if (args.move != null) {
12423            // moving a complete application; perfom an initial scan on the new install location
12424            scanFlags |= SCAN_INITIAL;
12425        }
12426        // Result object to be returned
12427        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12428
12429        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12430
12431        // Retrieve PackageSettings and parse package
12432        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12433                | PackageParser.PARSE_ENFORCE_CODE
12434                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12435                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12436                | (quickInstall ? PackageParser.PARSE_SKIP_VERIFICATION : 0);
12437        PackageParser pp = new PackageParser();
12438        pp.setSeparateProcesses(mSeparateProcesses);
12439        pp.setDisplayMetrics(mMetrics);
12440
12441        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12442        final PackageParser.Package pkg;
12443        try {
12444            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12445        } catch (PackageParserException e) {
12446            res.setError("Failed parse during installPackageLI", e);
12447            return;
12448        } finally {
12449            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12450        }
12451
12452        // Mark that we have an install time CPU ABI override.
12453        pkg.cpuAbiOverride = args.abiOverride;
12454
12455        String pkgName = res.name = pkg.packageName;
12456        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12457            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12458                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12459                return;
12460            }
12461        }
12462
12463        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12464        try {
12465            pp.collectCertificates(pkg, parseFlags);
12466        } catch (PackageParserException e) {
12467            res.setError("Failed collect during installPackageLI", e);
12468            return;
12469        } finally {
12470            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12471        }
12472
12473        /* If the installer passed in a manifest digest, compare it now. */
12474        if (args.manifestDigest != null) {
12475            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectManifestDigest");
12476            try {
12477                pp.collectManifestDigest(pkg);
12478            } catch (PackageParserException e) {
12479                res.setError("Failed collect during installPackageLI", e);
12480                return;
12481            } finally {
12482                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12483            }
12484
12485            if (DEBUG_INSTALL) {
12486                final String parsedManifest = pkg.manifestDigest == null ? "null"
12487                        : pkg.manifestDigest.toString();
12488                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
12489                        + parsedManifest);
12490            }
12491
12492            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
12493                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
12494                return;
12495            }
12496        } else if (DEBUG_INSTALL) {
12497            final String parsedManifest = pkg.manifestDigest == null
12498                    ? "null" : pkg.manifestDigest.toString();
12499            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
12500        }
12501
12502        // Get rid of all references to package scan path via parser.
12503        pp = null;
12504        String oldCodePath = null;
12505        boolean systemApp = false;
12506        synchronized (mPackages) {
12507            // Check if installing already existing package
12508            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12509                String oldName = mSettings.mRenamedPackages.get(pkgName);
12510                if (pkg.mOriginalPackages != null
12511                        && pkg.mOriginalPackages.contains(oldName)
12512                        && mPackages.containsKey(oldName)) {
12513                    // This package is derived from an original package,
12514                    // and this device has been updating from that original
12515                    // name.  We must continue using the original name, so
12516                    // rename the new package here.
12517                    pkg.setPackageName(oldName);
12518                    pkgName = pkg.packageName;
12519                    replace = true;
12520                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12521                            + oldName + " pkgName=" + pkgName);
12522                } else if (mPackages.containsKey(pkgName)) {
12523                    // This package, under its official name, already exists
12524                    // on the device; we should replace it.
12525                    replace = true;
12526                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12527                }
12528
12529                // Prevent apps opting out from runtime permissions
12530                if (replace) {
12531                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12532                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12533                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12534                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12535                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12536                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12537                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12538                                        + " doesn't support runtime permissions but the old"
12539                                        + " target SDK " + oldTargetSdk + " does.");
12540                        return;
12541                    }
12542                }
12543            }
12544
12545            PackageSetting ps = mSettings.mPackages.get(pkgName);
12546            if (ps != null) {
12547                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12548
12549                // Quick sanity check that we're signed correctly if updating;
12550                // we'll check this again later when scanning, but we want to
12551                // bail early here before tripping over redefined permissions.
12552                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12553                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12554                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12555                                + pkg.packageName + " upgrade keys do not match the "
12556                                + "previously installed version");
12557                        return;
12558                    }
12559                } else {
12560                    try {
12561                        verifySignaturesLP(ps, pkg);
12562                    } catch (PackageManagerException e) {
12563                        res.setError(e.error, e.getMessage());
12564                        return;
12565                    }
12566                }
12567
12568                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12569                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12570                    systemApp = (ps.pkg.applicationInfo.flags &
12571                            ApplicationInfo.FLAG_SYSTEM) != 0;
12572                }
12573                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12574            }
12575
12576            // Check whether the newly-scanned package wants to define an already-defined perm
12577            int N = pkg.permissions.size();
12578            for (int i = N-1; i >= 0; i--) {
12579                PackageParser.Permission perm = pkg.permissions.get(i);
12580                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12581                if (bp != null) {
12582                    // If the defining package is signed with our cert, it's okay.  This
12583                    // also includes the "updating the same package" case, of course.
12584                    // "updating same package" could also involve key-rotation.
12585                    final boolean sigsOk;
12586                    if (bp.sourcePackage.equals(pkg.packageName)
12587                            && (bp.packageSetting instanceof PackageSetting)
12588                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12589                                    scanFlags))) {
12590                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12591                    } else {
12592                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12593                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12594                    }
12595                    if (!sigsOk) {
12596                        // If the owning package is the system itself, we log but allow
12597                        // install to proceed; we fail the install on all other permission
12598                        // redefinitions.
12599                        if (!bp.sourcePackage.equals("android")) {
12600                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12601                                    + pkg.packageName + " attempting to redeclare permission "
12602                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12603                            res.origPermission = perm.info.name;
12604                            res.origPackage = bp.sourcePackage;
12605                            return;
12606                        } else {
12607                            Slog.w(TAG, "Package " + pkg.packageName
12608                                    + " attempting to redeclare system permission "
12609                                    + perm.info.name + "; ignoring new declaration");
12610                            pkg.permissions.remove(i);
12611                        }
12612                    }
12613                }
12614            }
12615
12616        }
12617
12618        if (systemApp && onExternal) {
12619            // Disable updates to system apps on sdcard
12620            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12621                    "Cannot install updates to system apps on sdcard");
12622            return;
12623        }
12624
12625        if (args.move != null) {
12626            // We did an in-place move, so dex is ready to roll
12627            scanFlags |= SCAN_NO_DEX;
12628            scanFlags |= SCAN_MOVE;
12629
12630            synchronized (mPackages) {
12631                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12632                if (ps == null) {
12633                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
12634                            "Missing settings for moved package " + pkgName);
12635                }
12636
12637                // We moved the entire application as-is, so bring over the
12638                // previously derived ABI information.
12639                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
12640                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
12641            }
12642
12643        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
12644            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
12645            scanFlags |= SCAN_NO_DEX;
12646
12647            try {
12648                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
12649                        true /* extract libs */);
12650            } catch (PackageManagerException pme) {
12651                Slog.e(TAG, "Error deriving application ABI", pme);
12652                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
12653                return;
12654            }
12655
12656            // Run dexopt before old package gets removed, to minimize time when app is unavailable
12657            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
12658
12659            int result = mPackageDexOptimizer
12660                    .performDexOpt(pkg, null /* instruction sets */, false /* forceDex */,
12661                            false /* defer */, false /* inclDependencies */,
12662                            true /*bootComplete*/, quickInstall /*useJit*/);
12663            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12664            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
12665                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
12666                return;
12667            }
12668        }
12669
12670        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
12671            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
12672            return;
12673        }
12674
12675        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
12676
12677        if (replace) {
12678            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
12679                    installerPackageName, volumeUuid, res);
12680        } else {
12681            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
12682                    args.user, installerPackageName, volumeUuid, res);
12683        }
12684        synchronized (mPackages) {
12685            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12686            if (ps != null) {
12687                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12688            }
12689        }
12690    }
12691
12692    private void startIntentFilterVerifications(int userId, boolean replacing,
12693            PackageParser.Package pkg) {
12694        if (mIntentFilterVerifierComponent == null) {
12695            Slog.w(TAG, "No IntentFilter verification will not be done as "
12696                    + "there is no IntentFilterVerifier available!");
12697            return;
12698        }
12699
12700        final int verifierUid = getPackageUid(
12701                mIntentFilterVerifierComponent.getPackageName(),
12702                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
12703
12704        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
12705        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
12706        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
12707        mHandler.sendMessage(msg);
12708    }
12709
12710    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
12711            PackageParser.Package pkg) {
12712        int size = pkg.activities.size();
12713        if (size == 0) {
12714            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12715                    "No activity, so no need to verify any IntentFilter!");
12716            return;
12717        }
12718
12719        final boolean hasDomainURLs = hasDomainURLs(pkg);
12720        if (!hasDomainURLs) {
12721            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12722                    "No domain URLs, so no need to verify any IntentFilter!");
12723            return;
12724        }
12725
12726        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
12727                + " if any IntentFilter from the " + size
12728                + " Activities needs verification ...");
12729
12730        int count = 0;
12731        final String packageName = pkg.packageName;
12732
12733        synchronized (mPackages) {
12734            // If this is a new install and we see that we've already run verification for this
12735            // package, we have nothing to do: it means the state was restored from backup.
12736            if (!replacing) {
12737                IntentFilterVerificationInfo ivi =
12738                        mSettings.getIntentFilterVerificationLPr(packageName);
12739                if (ivi != null) {
12740                    if (DEBUG_DOMAIN_VERIFICATION) {
12741                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
12742                                + ivi.getStatusString());
12743                    }
12744                    return;
12745                }
12746            }
12747
12748            // If any filters need to be verified, then all need to be.
12749            boolean needToVerify = false;
12750            for (PackageParser.Activity a : pkg.activities) {
12751                for (ActivityIntentInfo filter : a.intents) {
12752                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
12753                        if (DEBUG_DOMAIN_VERIFICATION) {
12754                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
12755                        }
12756                        needToVerify = true;
12757                        break;
12758                    }
12759                }
12760            }
12761
12762            if (needToVerify) {
12763                final int verificationId = mIntentFilterVerificationToken++;
12764                for (PackageParser.Activity a : pkg.activities) {
12765                    for (ActivityIntentInfo filter : a.intents) {
12766                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
12767                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
12768                                    "Verification needed for IntentFilter:" + filter.toString());
12769                            mIntentFilterVerifier.addOneIntentFilterVerification(
12770                                    verifierUid, userId, verificationId, filter, packageName);
12771                            count++;
12772                        }
12773                    }
12774                }
12775            }
12776        }
12777
12778        if (count > 0) {
12779            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
12780                    + " IntentFilter verification" + (count > 1 ? "s" : "")
12781                    +  " for userId:" + userId);
12782            mIntentFilterVerifier.startVerifications(userId);
12783        } else {
12784            if (DEBUG_DOMAIN_VERIFICATION) {
12785                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
12786            }
12787        }
12788    }
12789
12790    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
12791        final ComponentName cn  = filter.activity.getComponentName();
12792        final String packageName = cn.getPackageName();
12793
12794        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
12795                packageName);
12796        if (ivi == null) {
12797            return true;
12798        }
12799        int status = ivi.getStatus();
12800        switch (status) {
12801            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
12802            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
12803                return true;
12804
12805            default:
12806                // Nothing to do
12807                return false;
12808        }
12809    }
12810
12811    private static boolean isMultiArch(PackageSetting ps) {
12812        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12813    }
12814
12815    private static boolean isMultiArch(ApplicationInfo info) {
12816        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
12817    }
12818
12819    private static boolean isExternal(PackageParser.Package pkg) {
12820        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12821    }
12822
12823    private static boolean isExternal(PackageSetting ps) {
12824        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12825    }
12826
12827    private static boolean isExternal(ApplicationInfo info) {
12828        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
12829    }
12830
12831    private static boolean isSystemApp(PackageParser.Package pkg) {
12832        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
12833    }
12834
12835    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
12836        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
12837    }
12838
12839    private static boolean hasDomainURLs(PackageParser.Package pkg) {
12840        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
12841    }
12842
12843    private static boolean isSystemApp(PackageSetting ps) {
12844        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
12845    }
12846
12847    private static boolean isUpdatedSystemApp(PackageSetting ps) {
12848        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
12849    }
12850
12851    private int packageFlagsToInstallFlags(PackageSetting ps) {
12852        int installFlags = 0;
12853        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
12854            // This existing package was an external ASEC install when we have
12855            // the external flag without a UUID
12856            installFlags |= PackageManager.INSTALL_EXTERNAL;
12857        }
12858        if (ps.isForwardLocked()) {
12859            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12860        }
12861        return installFlags;
12862    }
12863
12864    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
12865        if (isExternal(pkg)) {
12866            if (TextUtils.isEmpty(pkg.volumeUuid)) {
12867                return mSettings.getExternalVersion();
12868            } else {
12869                return mSettings.findOrCreateVersion(pkg.volumeUuid);
12870            }
12871        } else {
12872            return mSettings.getInternalVersion();
12873        }
12874    }
12875
12876    private void deleteTempPackageFiles() {
12877        final FilenameFilter filter = new FilenameFilter() {
12878            public boolean accept(File dir, String name) {
12879                return name.startsWith("vmdl") && name.endsWith(".tmp");
12880            }
12881        };
12882        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
12883            file.delete();
12884        }
12885    }
12886
12887    @Override
12888    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
12889            int flags) {
12890        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
12891                flags);
12892    }
12893
12894    @Override
12895    public void deletePackage(final String packageName,
12896            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
12897        mContext.enforceCallingOrSelfPermission(
12898                android.Manifest.permission.DELETE_PACKAGES, null);
12899        Preconditions.checkNotNull(packageName);
12900        Preconditions.checkNotNull(observer);
12901        final int uid = Binder.getCallingUid();
12902        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
12903        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
12904        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
12905            mContext.enforceCallingPermission(
12906                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12907                    "deletePackage for user " + userId);
12908        }
12909
12910        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
12911            try {
12912                observer.onPackageDeleted(packageName,
12913                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
12914            } catch (RemoteException re) {
12915            }
12916            return;
12917        }
12918
12919        for (int currentUserId : users) {
12920            if (getBlockUninstallForUser(packageName, currentUserId)) {
12921                try {
12922                    observer.onPackageDeleted(packageName,
12923                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
12924                } catch (RemoteException re) {
12925                }
12926                return;
12927            }
12928        }
12929
12930        if (DEBUG_REMOVE) {
12931            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
12932        }
12933        // Queue up an async operation since the package deletion may take a little while.
12934        mHandler.post(new Runnable() {
12935            public void run() {
12936                mHandler.removeCallbacks(this);
12937                final int returnCode = deletePackageX(packageName, userId, flags);
12938                try {
12939                    observer.onPackageDeleted(packageName, returnCode, null);
12940                } catch (RemoteException e) {
12941                    Log.i(TAG, "Observer no longer exists.");
12942                } //end catch
12943            } //end run
12944        });
12945    }
12946
12947    private boolean isPackageDeviceAdmin(String packageName, int userId) {
12948        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
12949                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
12950        try {
12951            if (dpm != null) {
12952                // Does the package contains the device owner?
12953                if (dpm.isDeviceOwnerPackage(packageName)) {
12954                    return true;
12955                }
12956                // Does it contain a device admin for any user?
12957                int[] users;
12958                if (userId == UserHandle.USER_ALL) {
12959                    users = sUserManager.getUserIds();
12960                } else {
12961                    users = new int[]{userId};
12962                }
12963                for (int i = 0; i < users.length; ++i) {
12964                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
12965                        return true;
12966                    }
12967                }
12968            }
12969        } catch (RemoteException e) {
12970        }
12971        return false;
12972    }
12973
12974    /**
12975     *  This method is an internal method that could be get invoked either
12976     *  to delete an installed package or to clean up a failed installation.
12977     *  After deleting an installed package, a broadcast is sent to notify any
12978     *  listeners that the package has been installed. For cleaning up a failed
12979     *  installation, the broadcast is not necessary since the package's
12980     *  installation wouldn't have sent the initial broadcast either
12981     *  The key steps in deleting a package are
12982     *  deleting the package information in internal structures like mPackages,
12983     *  deleting the packages base directories through installd
12984     *  updating mSettings to reflect current status
12985     *  persisting settings for later use
12986     *  sending a broadcast if necessary
12987     */
12988    private int deletePackageX(String packageName, int userId, int flags) {
12989        final PackageRemovedInfo info = new PackageRemovedInfo();
12990        final boolean res;
12991
12992        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
12993                ? UserHandle.ALL : new UserHandle(userId);
12994
12995        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
12996            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
12997            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
12998        }
12999
13000        boolean removedForAllUsers = false;
13001        boolean systemUpdate = false;
13002
13003        // for the uninstall-updates case and restricted profiles, remember the per-
13004        // userhandle installed state
13005        int[] allUsers;
13006        boolean[] perUserInstalled;
13007        synchronized (mPackages) {
13008            PackageSetting ps = mSettings.mPackages.get(packageName);
13009            allUsers = sUserManager.getUserIds();
13010            perUserInstalled = new boolean[allUsers.length];
13011            for (int i = 0; i < allUsers.length; i++) {
13012                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13013            }
13014        }
13015
13016        synchronized (mInstallLock) {
13017            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13018            res = deletePackageLI(packageName, removeForUser,
13019                    true, allUsers, perUserInstalled,
13020                    flags | REMOVE_CHATTY, info, true);
13021            systemUpdate = info.isRemovedPackageSystemUpdate;
13022            if (res && !systemUpdate && mPackages.get(packageName) == null) {
13023                removedForAllUsers = true;
13024            }
13025            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13026                    + " removedForAllUsers=" + removedForAllUsers);
13027        }
13028
13029        if (res) {
13030            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13031
13032            // If the removed package was a system update, the old system package
13033            // was re-enabled; we need to broadcast this information
13034            if (systemUpdate) {
13035                Bundle extras = new Bundle(1);
13036                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13037                        ? info.removedAppId : info.uid);
13038                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13039
13040                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13041                        extras, null, null, null);
13042                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13043                        extras, null, null, null);
13044                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13045                        null, packageName, null, null);
13046            }
13047        }
13048        // Force a gc here.
13049        Runtime.getRuntime().gc();
13050        // Delete the resources here after sending the broadcast to let
13051        // other processes clean up before deleting resources.
13052        if (info.args != null) {
13053            synchronized (mInstallLock) {
13054                info.args.doPostDeleteLI(true);
13055            }
13056        }
13057
13058        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13059    }
13060
13061    class PackageRemovedInfo {
13062        String removedPackage;
13063        int uid = -1;
13064        int removedAppId = -1;
13065        int[] removedUsers = null;
13066        boolean isRemovedPackageSystemUpdate = false;
13067        // Clean up resources deleted packages.
13068        InstallArgs args = null;
13069
13070        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13071            Bundle extras = new Bundle(1);
13072            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13073            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13074            if (replacing) {
13075                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13076            }
13077            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13078            if (removedPackage != null) {
13079                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13080                        extras, null, null, removedUsers);
13081                if (fullRemove && !replacing) {
13082                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13083                            extras, null, null, removedUsers);
13084                }
13085            }
13086            if (removedAppId >= 0) {
13087                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
13088                        removedUsers);
13089            }
13090        }
13091    }
13092
13093    /*
13094     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13095     * flag is not set, the data directory is removed as well.
13096     * make sure this flag is set for partially installed apps. If not its meaningless to
13097     * delete a partially installed application.
13098     */
13099    private void removePackageDataLI(PackageSetting ps,
13100            int[] allUserHandles, boolean[] perUserInstalled,
13101            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13102        String packageName = ps.name;
13103        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13104        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13105        // Retrieve object to delete permissions for shared user later on
13106        final PackageSetting deletedPs;
13107        // reader
13108        synchronized (mPackages) {
13109            deletedPs = mSettings.mPackages.get(packageName);
13110            if (outInfo != null) {
13111                outInfo.removedPackage = packageName;
13112                outInfo.removedUsers = deletedPs != null
13113                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13114                        : null;
13115            }
13116        }
13117        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13118            removeDataDirsLI(ps.volumeUuid, packageName);
13119            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13120        }
13121        // writer
13122        synchronized (mPackages) {
13123            if (deletedPs != null) {
13124                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13125                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13126                    clearDefaultBrowserIfNeeded(packageName);
13127                    if (outInfo != null) {
13128                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13129                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13130                    }
13131                    updatePermissionsLPw(deletedPs.name, null, 0);
13132                    if (deletedPs.sharedUser != null) {
13133                        // Remove permissions associated with package. Since runtime
13134                        // permissions are per user we have to kill the removed package
13135                        // or packages running under the shared user of the removed
13136                        // package if revoking the permissions requested only by the removed
13137                        // package is successful and this causes a change in gids.
13138                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13139                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13140                                    userId);
13141                            if (userIdToKill == UserHandle.USER_ALL
13142                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13143                                // If gids changed for this user, kill all affected packages.
13144                                mHandler.post(new Runnable() {
13145                                    @Override
13146                                    public void run() {
13147                                        // This has to happen with no lock held.
13148                                        killApplication(deletedPs.name, deletedPs.appId,
13149                                                KILL_APP_REASON_GIDS_CHANGED);
13150                                    }
13151                                });
13152                                break;
13153                            }
13154                        }
13155                    }
13156                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13157                }
13158                // make sure to preserve per-user disabled state if this removal was just
13159                // a downgrade of a system app to the factory package
13160                if (allUserHandles != null && perUserInstalled != null) {
13161                    if (DEBUG_REMOVE) {
13162                        Slog.d(TAG, "Propagating install state across downgrade");
13163                    }
13164                    for (int i = 0; i < allUserHandles.length; i++) {
13165                        if (DEBUG_REMOVE) {
13166                            Slog.d(TAG, "    user " + allUserHandles[i]
13167                                    + " => " + perUserInstalled[i]);
13168                        }
13169                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13170                    }
13171                }
13172            }
13173            // can downgrade to reader
13174            if (writeSettings) {
13175                // Save settings now
13176                mSettings.writeLPr();
13177            }
13178        }
13179        if (outInfo != null) {
13180            // A user ID was deleted here. Go through all users and remove it
13181            // from KeyStore.
13182            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13183        }
13184    }
13185
13186    static boolean locationIsPrivileged(File path) {
13187        try {
13188            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13189                    .getCanonicalPath();
13190            return path.getCanonicalPath().startsWith(privilegedAppDir);
13191        } catch (IOException e) {
13192            Slog.e(TAG, "Unable to access code path " + path);
13193        }
13194        return false;
13195    }
13196
13197    /*
13198     * Tries to delete system package.
13199     */
13200    private boolean deleteSystemPackageLI(PackageSetting newPs,
13201            int[] allUserHandles, boolean[] perUserInstalled,
13202            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13203        final boolean applyUserRestrictions
13204                = (allUserHandles != null) && (perUserInstalled != null);
13205        PackageSetting disabledPs = null;
13206        // Confirm if the system package has been updated
13207        // An updated system app can be deleted. This will also have to restore
13208        // the system pkg from system partition
13209        // reader
13210        synchronized (mPackages) {
13211            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13212        }
13213        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13214                + " disabledPs=" + disabledPs);
13215        if (disabledPs == null) {
13216            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13217            return false;
13218        } else if (DEBUG_REMOVE) {
13219            Slog.d(TAG, "Deleting system pkg from data partition");
13220        }
13221        if (DEBUG_REMOVE) {
13222            if (applyUserRestrictions) {
13223                Slog.d(TAG, "Remembering install states:");
13224                for (int i = 0; i < allUserHandles.length; i++) {
13225                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13226                }
13227            }
13228        }
13229        // Delete the updated package
13230        outInfo.isRemovedPackageSystemUpdate = true;
13231        if (disabledPs.versionCode < newPs.versionCode) {
13232            // Delete data for downgrades
13233            flags &= ~PackageManager.DELETE_KEEP_DATA;
13234        } else {
13235            // Preserve data by setting flag
13236            flags |= PackageManager.DELETE_KEEP_DATA;
13237        }
13238        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13239                allUserHandles, perUserInstalled, outInfo, writeSettings);
13240        if (!ret) {
13241            return false;
13242        }
13243        // writer
13244        synchronized (mPackages) {
13245            // Reinstate the old system package
13246            mSettings.enableSystemPackageLPw(newPs.name);
13247            // Remove any native libraries from the upgraded package.
13248            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13249        }
13250        // Install the system package
13251        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13252        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13253        if (locationIsPrivileged(disabledPs.codePath)) {
13254            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13255        }
13256
13257        final PackageParser.Package newPkg;
13258        try {
13259            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0,
13260                    UserHandle.SYSTEM);
13261        } catch (PackageManagerException e) {
13262            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
13263            return false;
13264        }
13265
13266        // writer
13267        synchronized (mPackages) {
13268            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13269
13270            // Propagate the permissions state as we do not want to drop on the floor
13271            // runtime permissions. The update permissions method below will take
13272            // care of removing obsolete permissions and grant install permissions.
13273            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13274            updatePermissionsLPw(newPkg.packageName, newPkg,
13275                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13276
13277            if (applyUserRestrictions) {
13278                if (DEBUG_REMOVE) {
13279                    Slog.d(TAG, "Propagating install state across reinstall");
13280                }
13281                for (int i = 0; i < allUserHandles.length; i++) {
13282                    if (DEBUG_REMOVE) {
13283                        Slog.d(TAG, "    user " + allUserHandles[i]
13284                                + " => " + perUserInstalled[i]);
13285                    }
13286                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13287
13288                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13289                }
13290                // Regardless of writeSettings we need to ensure that this restriction
13291                // state propagation is persisted
13292                mSettings.writeAllUsersPackageRestrictionsLPr();
13293            }
13294            // can downgrade to reader here
13295            if (writeSettings) {
13296                mSettings.writeLPr();
13297            }
13298        }
13299        return true;
13300    }
13301
13302    private boolean deleteInstalledPackageLI(PackageSetting ps,
13303            boolean deleteCodeAndResources, int flags,
13304            int[] allUserHandles, boolean[] perUserInstalled,
13305            PackageRemovedInfo outInfo, boolean writeSettings) {
13306        if (outInfo != null) {
13307            outInfo.uid = ps.appId;
13308        }
13309
13310        // Delete package data from internal structures and also remove data if flag is set
13311        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13312
13313        // Delete application code and resources
13314        if (deleteCodeAndResources && (outInfo != null)) {
13315            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13316                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13317            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13318        }
13319        return true;
13320    }
13321
13322    @Override
13323    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13324            int userId) {
13325        mContext.enforceCallingOrSelfPermission(
13326                android.Manifest.permission.DELETE_PACKAGES, null);
13327        synchronized (mPackages) {
13328            PackageSetting ps = mSettings.mPackages.get(packageName);
13329            if (ps == null) {
13330                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13331                return false;
13332            }
13333            if (!ps.getInstalled(userId)) {
13334                // Can't block uninstall for an app that is not installed or enabled.
13335                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13336                return false;
13337            }
13338            ps.setBlockUninstall(blockUninstall, userId);
13339            mSettings.writePackageRestrictionsLPr(userId);
13340        }
13341        return true;
13342    }
13343
13344    @Override
13345    public boolean getBlockUninstallForUser(String packageName, int userId) {
13346        synchronized (mPackages) {
13347            PackageSetting ps = mSettings.mPackages.get(packageName);
13348            if (ps == null) {
13349                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13350                return false;
13351            }
13352            return ps.getBlockUninstall(userId);
13353        }
13354    }
13355
13356    /*
13357     * This method handles package deletion in general
13358     */
13359    private boolean deletePackageLI(String packageName, UserHandle user,
13360            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13361            int flags, PackageRemovedInfo outInfo,
13362            boolean writeSettings) {
13363        if (packageName == null) {
13364            Slog.w(TAG, "Attempt to delete null packageName.");
13365            return false;
13366        }
13367        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13368        PackageSetting ps;
13369        boolean dataOnly = false;
13370        int removeUser = -1;
13371        int appId = -1;
13372        synchronized (mPackages) {
13373            ps = mSettings.mPackages.get(packageName);
13374            if (ps == null) {
13375                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13376                return false;
13377            }
13378            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13379                    && user.getIdentifier() != UserHandle.USER_ALL) {
13380                // The caller is asking that the package only be deleted for a single
13381                // user.  To do this, we just mark its uninstalled state and delete
13382                // its data.  If this is a system app, we only allow this to happen if
13383                // they have set the special DELETE_SYSTEM_APP which requests different
13384                // semantics than normal for uninstalling system apps.
13385                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13386                final int userId = user.getIdentifier();
13387                ps.setUserState(userId,
13388                        COMPONENT_ENABLED_STATE_DEFAULT,
13389                        false, //installed
13390                        true,  //stopped
13391                        true,  //notLaunched
13392                        false, //hidden
13393                        null, null, null,
13394                        false, // blockUninstall
13395                        ps.readUserState(userId).domainVerificationStatus, 0);
13396                if (!isSystemApp(ps)) {
13397                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
13398                        // Other user still have this package installed, so all
13399                        // we need to do is clear this user's data and save that
13400                        // it is uninstalled.
13401                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13402                        removeUser = user.getIdentifier();
13403                        appId = ps.appId;
13404                        scheduleWritePackageRestrictionsLocked(removeUser);
13405                    } else {
13406                        // We need to set it back to 'installed' so the uninstall
13407                        // broadcasts will be sent correctly.
13408                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13409                        ps.setInstalled(true, user.getIdentifier());
13410                    }
13411                } else {
13412                    // This is a system app, so we assume that the
13413                    // other users still have this package installed, so all
13414                    // we need to do is clear this user's data and save that
13415                    // it is uninstalled.
13416                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13417                    removeUser = user.getIdentifier();
13418                    appId = ps.appId;
13419                    scheduleWritePackageRestrictionsLocked(removeUser);
13420                }
13421            }
13422        }
13423
13424        if (removeUser >= 0) {
13425            // From above, we determined that we are deleting this only
13426            // for a single user.  Continue the work here.
13427            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13428            if (outInfo != null) {
13429                outInfo.removedPackage = packageName;
13430                outInfo.removedAppId = appId;
13431                outInfo.removedUsers = new int[] {removeUser};
13432            }
13433            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13434            removeKeystoreDataIfNeeded(removeUser, appId);
13435            schedulePackageCleaning(packageName, removeUser, false);
13436            synchronized (mPackages) {
13437                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13438                    scheduleWritePackageRestrictionsLocked(removeUser);
13439                }
13440                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13441            }
13442            return true;
13443        }
13444
13445        if (dataOnly) {
13446            // Delete application data first
13447            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13448            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13449            return true;
13450        }
13451
13452        boolean ret = false;
13453        if (isSystemApp(ps)) {
13454            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
13455            // When an updated system application is deleted we delete the existing resources as well and
13456            // fall back to existing code in system partition
13457            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13458                    flags, outInfo, writeSettings);
13459        } else {
13460            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
13461            // Kill application pre-emptively especially for apps on sd.
13462            killApplication(packageName, ps.appId, "uninstall pkg");
13463            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13464                    allUserHandles, perUserInstalled,
13465                    outInfo, writeSettings);
13466        }
13467
13468        return ret;
13469    }
13470
13471    private final class ClearStorageConnection implements ServiceConnection {
13472        IMediaContainerService mContainerService;
13473
13474        @Override
13475        public void onServiceConnected(ComponentName name, IBinder service) {
13476            synchronized (this) {
13477                mContainerService = IMediaContainerService.Stub.asInterface(service);
13478                notifyAll();
13479            }
13480        }
13481
13482        @Override
13483        public void onServiceDisconnected(ComponentName name) {
13484        }
13485    }
13486
13487    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13488        final boolean mounted;
13489        if (Environment.isExternalStorageEmulated()) {
13490            mounted = true;
13491        } else {
13492            final String status = Environment.getExternalStorageState();
13493
13494            mounted = status.equals(Environment.MEDIA_MOUNTED)
13495                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13496        }
13497
13498        if (!mounted) {
13499            return;
13500        }
13501
13502        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13503        int[] users;
13504        if (userId == UserHandle.USER_ALL) {
13505            users = sUserManager.getUserIds();
13506        } else {
13507            users = new int[] { userId };
13508        }
13509        final ClearStorageConnection conn = new ClearStorageConnection();
13510        if (mContext.bindServiceAsUser(
13511                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13512            try {
13513                for (int curUser : users) {
13514                    long timeout = SystemClock.uptimeMillis() + 5000;
13515                    synchronized (conn) {
13516                        long now = SystemClock.uptimeMillis();
13517                        while (conn.mContainerService == null && now < timeout) {
13518                            try {
13519                                conn.wait(timeout - now);
13520                            } catch (InterruptedException e) {
13521                            }
13522                        }
13523                    }
13524                    if (conn.mContainerService == null) {
13525                        return;
13526                    }
13527
13528                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13529                    clearDirectory(conn.mContainerService,
13530                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13531                    if (allData) {
13532                        clearDirectory(conn.mContainerService,
13533                                userEnv.buildExternalStorageAppDataDirs(packageName));
13534                        clearDirectory(conn.mContainerService,
13535                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13536                    }
13537                }
13538            } finally {
13539                mContext.unbindService(conn);
13540            }
13541        }
13542    }
13543
13544    @Override
13545    public void clearApplicationUserData(final String packageName,
13546            final IPackageDataObserver observer, final int userId) {
13547        mContext.enforceCallingOrSelfPermission(
13548                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13549        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13550        // Queue up an async operation since the package deletion may take a little while.
13551        mHandler.post(new Runnable() {
13552            public void run() {
13553                mHandler.removeCallbacks(this);
13554                final boolean succeeded;
13555                synchronized (mInstallLock) {
13556                    succeeded = clearApplicationUserDataLI(packageName, userId);
13557                }
13558                clearExternalStorageDataSync(packageName, userId, true);
13559                if (succeeded) {
13560                    // invoke DeviceStorageMonitor's update method to clear any notifications
13561                    DeviceStorageMonitorInternal
13562                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13563                    if (dsm != null) {
13564                        dsm.checkMemory();
13565                    }
13566                }
13567                if(observer != null) {
13568                    try {
13569                        observer.onRemoveCompleted(packageName, succeeded);
13570                    } catch (RemoteException e) {
13571                        Log.i(TAG, "Observer no longer exists.");
13572                    }
13573                } //end if observer
13574            } //end run
13575        });
13576    }
13577
13578    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13579        if (packageName == null) {
13580            Slog.w(TAG, "Attempt to delete null packageName.");
13581            return false;
13582        }
13583
13584        // Try finding details about the requested package
13585        PackageParser.Package pkg;
13586        synchronized (mPackages) {
13587            pkg = mPackages.get(packageName);
13588            if (pkg == null) {
13589                final PackageSetting ps = mSettings.mPackages.get(packageName);
13590                if (ps != null) {
13591                    pkg = ps.pkg;
13592                }
13593            }
13594
13595            if (pkg == null) {
13596                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13597                return false;
13598            }
13599
13600            PackageSetting ps = (PackageSetting) pkg.mExtras;
13601            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13602        }
13603
13604        // Always delete data directories for package, even if we found no other
13605        // record of app. This helps users recover from UID mismatches without
13606        // resorting to a full data wipe.
13607        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
13608        if (retCode < 0) {
13609            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
13610            return false;
13611        }
13612
13613        final int appId = pkg.applicationInfo.uid;
13614        removeKeystoreDataIfNeeded(userId, appId);
13615
13616        // Create a native library symlink only if we have native libraries
13617        // and if the native libraries are 32 bit libraries. We do not provide
13618        // this symlink for 64 bit libraries.
13619        if (pkg.applicationInfo.primaryCpuAbi != null &&
13620                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
13621            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
13622            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
13623                    nativeLibPath, userId) < 0) {
13624                Slog.w(TAG, "Failed linking native library dir");
13625                return false;
13626            }
13627        }
13628
13629        return true;
13630    }
13631
13632    /**
13633     * Reverts user permission state changes (permissions and flags) in
13634     * all packages for a given user.
13635     *
13636     * @param userId The device user for which to do a reset.
13637     */
13638    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
13639        final int packageCount = mPackages.size();
13640        for (int i = 0; i < packageCount; i++) {
13641            PackageParser.Package pkg = mPackages.valueAt(i);
13642            PackageSetting ps = (PackageSetting) pkg.mExtras;
13643            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
13644        }
13645    }
13646
13647    /**
13648     * Reverts user permission state changes (permissions and flags).
13649     *
13650     * @param ps The package for which to reset.
13651     * @param userId The device user for which to do a reset.
13652     */
13653    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
13654            final PackageSetting ps, final int userId) {
13655        if (ps.pkg == null) {
13656            return;
13657        }
13658
13659        final int userSettableFlags = FLAG_PERMISSION_USER_SET
13660                | FLAG_PERMISSION_USER_FIXED
13661                | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
13662
13663        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
13664                | FLAG_PERMISSION_POLICY_FIXED;
13665
13666        boolean writeInstallPermissions = false;
13667        boolean writeRuntimePermissions = false;
13668
13669        final int permissionCount = ps.pkg.requestedPermissions.size();
13670        for (int i = 0; i < permissionCount; i++) {
13671            String permission = ps.pkg.requestedPermissions.get(i);
13672
13673            BasePermission bp = mSettings.mPermissions.get(permission);
13674            if (bp == null) {
13675                continue;
13676            }
13677
13678            // If shared user we just reset the state to which only this app contributed.
13679            if (ps.sharedUser != null) {
13680                boolean used = false;
13681                final int packageCount = ps.sharedUser.packages.size();
13682                for (int j = 0; j < packageCount; j++) {
13683                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
13684                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
13685                            && pkg.pkg.requestedPermissions.contains(permission)) {
13686                        used = true;
13687                        break;
13688                    }
13689                }
13690                if (used) {
13691                    continue;
13692                }
13693            }
13694
13695            PermissionsState permissionsState = ps.getPermissionsState();
13696
13697            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
13698
13699            // Always clear the user settable flags.
13700            final boolean hasInstallState = permissionsState.getInstallPermissionState(
13701                    bp.name) != null;
13702            if (permissionsState.updatePermissionFlags(bp, userId, userSettableFlags, 0)) {
13703                if (hasInstallState) {
13704                    writeInstallPermissions = true;
13705                } else {
13706                    writeRuntimePermissions = true;
13707                }
13708            }
13709
13710            // Below is only runtime permission handling.
13711            if (!bp.isRuntime()) {
13712                continue;
13713            }
13714
13715            // Never clobber system or policy.
13716            if ((oldFlags & policyOrSystemFlags) != 0) {
13717                continue;
13718            }
13719
13720            // If this permission was granted by default, make sure it is.
13721            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
13722                if (permissionsState.grantRuntimePermission(bp, userId)
13723                        != PERMISSION_OPERATION_FAILURE) {
13724                    writeRuntimePermissions = true;
13725                }
13726            } else {
13727                // Otherwise, reset the permission.
13728                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
13729                switch (revokeResult) {
13730                    case PERMISSION_OPERATION_SUCCESS: {
13731                        writeRuntimePermissions = true;
13732                    } break;
13733
13734                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
13735                        writeRuntimePermissions = true;
13736                        final int appId = ps.appId;
13737                        mHandler.post(new Runnable() {
13738                            @Override
13739                            public void run() {
13740                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
13741                            }
13742                        });
13743                    } break;
13744                }
13745            }
13746        }
13747
13748        // Synchronously write as we are taking permissions away.
13749        if (writeRuntimePermissions) {
13750            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
13751        }
13752
13753        // Synchronously write as we are taking permissions away.
13754        if (writeInstallPermissions) {
13755            mSettings.writeLPr();
13756        }
13757    }
13758
13759    /**
13760     * Remove entries from the keystore daemon. Will only remove it if the
13761     * {@code appId} is valid.
13762     */
13763    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
13764        if (appId < 0) {
13765            return;
13766        }
13767
13768        final KeyStore keyStore = KeyStore.getInstance();
13769        if (keyStore != null) {
13770            if (userId == UserHandle.USER_ALL) {
13771                for (final int individual : sUserManager.getUserIds()) {
13772                    keyStore.clearUid(UserHandle.getUid(individual, appId));
13773                }
13774            } else {
13775                keyStore.clearUid(UserHandle.getUid(userId, appId));
13776            }
13777        } else {
13778            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
13779        }
13780    }
13781
13782    @Override
13783    public void deleteApplicationCacheFiles(final String packageName,
13784            final IPackageDataObserver observer) {
13785        mContext.enforceCallingOrSelfPermission(
13786                android.Manifest.permission.DELETE_CACHE_FILES, null);
13787        // Queue up an async operation since the package deletion may take a little while.
13788        final int userId = UserHandle.getCallingUserId();
13789        mHandler.post(new Runnable() {
13790            public void run() {
13791                mHandler.removeCallbacks(this);
13792                final boolean succeded;
13793                synchronized (mInstallLock) {
13794                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
13795                }
13796                clearExternalStorageDataSync(packageName, userId, false);
13797                if (observer != null) {
13798                    try {
13799                        observer.onRemoveCompleted(packageName, succeded);
13800                    } catch (RemoteException e) {
13801                        Log.i(TAG, "Observer no longer exists.");
13802                    }
13803                } //end if observer
13804            } //end run
13805        });
13806    }
13807
13808    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
13809        if (packageName == null) {
13810            Slog.w(TAG, "Attempt to delete null packageName.");
13811            return false;
13812        }
13813        PackageParser.Package p;
13814        synchronized (mPackages) {
13815            p = mPackages.get(packageName);
13816        }
13817        if (p == null) {
13818            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13819            return false;
13820        }
13821        final ApplicationInfo applicationInfo = p.applicationInfo;
13822        if (applicationInfo == null) {
13823            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13824            return false;
13825        }
13826        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
13827        if (retCode < 0) {
13828            Slog.w(TAG, "Couldn't remove cache files for package: "
13829                       + packageName + " u" + userId);
13830            return false;
13831        }
13832        return true;
13833    }
13834
13835    @Override
13836    public void getPackageSizeInfo(final String packageName, int userHandle,
13837            final IPackageStatsObserver observer) {
13838        mContext.enforceCallingOrSelfPermission(
13839                android.Manifest.permission.GET_PACKAGE_SIZE, null);
13840        if (packageName == null) {
13841            throw new IllegalArgumentException("Attempt to get size of null packageName");
13842        }
13843
13844        PackageStats stats = new PackageStats(packageName, userHandle);
13845
13846        /*
13847         * Queue up an async operation since the package measurement may take a
13848         * little while.
13849         */
13850        Message msg = mHandler.obtainMessage(INIT_COPY);
13851        msg.obj = new MeasureParams(stats, observer);
13852        mHandler.sendMessage(msg);
13853    }
13854
13855    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
13856            PackageStats pStats) {
13857        if (packageName == null) {
13858            Slog.w(TAG, "Attempt to get size of null packageName.");
13859            return false;
13860        }
13861        PackageParser.Package p;
13862        boolean dataOnly = false;
13863        String libDirRoot = null;
13864        String asecPath = null;
13865        PackageSetting ps = null;
13866        synchronized (mPackages) {
13867            p = mPackages.get(packageName);
13868            ps = mSettings.mPackages.get(packageName);
13869            if(p == null) {
13870                dataOnly = true;
13871                if((ps == null) || (ps.pkg == null)) {
13872                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
13873                    return false;
13874                }
13875                p = ps.pkg;
13876            }
13877            if (ps != null) {
13878                libDirRoot = ps.legacyNativeLibraryPathString;
13879            }
13880            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
13881                final long token = Binder.clearCallingIdentity();
13882                try {
13883                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
13884                    if (secureContainerId != null) {
13885                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
13886                    }
13887                } finally {
13888                    Binder.restoreCallingIdentity(token);
13889                }
13890            }
13891        }
13892        String publicSrcDir = null;
13893        if(!dataOnly) {
13894            final ApplicationInfo applicationInfo = p.applicationInfo;
13895            if (applicationInfo == null) {
13896                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
13897                return false;
13898            }
13899            if (p.isForwardLocked()) {
13900                publicSrcDir = applicationInfo.getBaseResourcePath();
13901            }
13902        }
13903        // TODO: extend to measure size of split APKs
13904        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
13905        // not just the first level.
13906        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
13907        // just the primary.
13908        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
13909
13910        String apkPath;
13911        File packageDir = new File(p.codePath);
13912
13913        if (packageDir.isDirectory() && p.canHaveOatDir()) {
13914            apkPath = packageDir.getAbsolutePath();
13915            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
13916            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
13917                libDirRoot = null;
13918            }
13919        } else {
13920            apkPath = p.baseCodePath;
13921        }
13922
13923        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
13924                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
13925        if (res < 0) {
13926            return false;
13927        }
13928
13929        // Fix-up for forward-locked applications in ASEC containers.
13930        if (!isExternal(p)) {
13931            pStats.codeSize += pStats.externalCodeSize;
13932            pStats.externalCodeSize = 0L;
13933        }
13934
13935        return true;
13936    }
13937
13938
13939    @Override
13940    public void addPackageToPreferred(String packageName) {
13941        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
13942    }
13943
13944    @Override
13945    public void removePackageFromPreferred(String packageName) {
13946        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
13947    }
13948
13949    @Override
13950    public List<PackageInfo> getPreferredPackages(int flags) {
13951        return new ArrayList<PackageInfo>();
13952    }
13953
13954    private int getUidTargetSdkVersionLockedLPr(int uid) {
13955        Object obj = mSettings.getUserIdLPr(uid);
13956        if (obj instanceof SharedUserSetting) {
13957            final SharedUserSetting sus = (SharedUserSetting) obj;
13958            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
13959            final Iterator<PackageSetting> it = sus.packages.iterator();
13960            while (it.hasNext()) {
13961                final PackageSetting ps = it.next();
13962                if (ps.pkg != null) {
13963                    int v = ps.pkg.applicationInfo.targetSdkVersion;
13964                    if (v < vers) vers = v;
13965                }
13966            }
13967            return vers;
13968        } else if (obj instanceof PackageSetting) {
13969            final PackageSetting ps = (PackageSetting) obj;
13970            if (ps.pkg != null) {
13971                return ps.pkg.applicationInfo.targetSdkVersion;
13972            }
13973        }
13974        return Build.VERSION_CODES.CUR_DEVELOPMENT;
13975    }
13976
13977    @Override
13978    public void addPreferredActivity(IntentFilter filter, int match,
13979            ComponentName[] set, ComponentName activity, int userId) {
13980        addPreferredActivityInternal(filter, match, set, activity, true, userId,
13981                "Adding preferred");
13982    }
13983
13984    private void addPreferredActivityInternal(IntentFilter filter, int match,
13985            ComponentName[] set, ComponentName activity, boolean always, int userId,
13986            String opname) {
13987        // writer
13988        int callingUid = Binder.getCallingUid();
13989        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
13990        if (filter.countActions() == 0) {
13991            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
13992            return;
13993        }
13994        synchronized (mPackages) {
13995            if (mContext.checkCallingOrSelfPermission(
13996                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
13997                    != PackageManager.PERMISSION_GRANTED) {
13998                if (getUidTargetSdkVersionLockedLPr(callingUid)
13999                        < Build.VERSION_CODES.FROYO) {
14000                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14001                            + callingUid);
14002                    return;
14003                }
14004                mContext.enforceCallingOrSelfPermission(
14005                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14006            }
14007
14008            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14009            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14010                    + userId + ":");
14011            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14012            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14013            scheduleWritePackageRestrictionsLocked(userId);
14014        }
14015    }
14016
14017    @Override
14018    public void replacePreferredActivity(IntentFilter filter, int match,
14019            ComponentName[] set, ComponentName activity, int userId) {
14020        if (filter.countActions() != 1) {
14021            throw new IllegalArgumentException(
14022                    "replacePreferredActivity expects filter to have only 1 action.");
14023        }
14024        if (filter.countDataAuthorities() != 0
14025                || filter.countDataPaths() != 0
14026                || filter.countDataSchemes() > 1
14027                || filter.countDataTypes() != 0) {
14028            throw new IllegalArgumentException(
14029                    "replacePreferredActivity expects filter to have no data authorities, " +
14030                    "paths, or types; and at most one scheme.");
14031        }
14032
14033        final int callingUid = Binder.getCallingUid();
14034        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14035        synchronized (mPackages) {
14036            if (mContext.checkCallingOrSelfPermission(
14037                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14038                    != PackageManager.PERMISSION_GRANTED) {
14039                if (getUidTargetSdkVersionLockedLPr(callingUid)
14040                        < Build.VERSION_CODES.FROYO) {
14041                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14042                            + Binder.getCallingUid());
14043                    return;
14044                }
14045                mContext.enforceCallingOrSelfPermission(
14046                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14047            }
14048
14049            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14050            if (pir != null) {
14051                // Get all of the existing entries that exactly match this filter.
14052                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14053                if (existing != null && existing.size() == 1) {
14054                    PreferredActivity cur = existing.get(0);
14055                    if (DEBUG_PREFERRED) {
14056                        Slog.i(TAG, "Checking replace of preferred:");
14057                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14058                        if (!cur.mPref.mAlways) {
14059                            Slog.i(TAG, "  -- CUR; not mAlways!");
14060                        } else {
14061                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14062                            Slog.i(TAG, "  -- CUR: mSet="
14063                                    + Arrays.toString(cur.mPref.mSetComponents));
14064                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14065                            Slog.i(TAG, "  -- NEW: mMatch="
14066                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14067                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14068                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14069                        }
14070                    }
14071                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14072                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14073                            && cur.mPref.sameSet(set)) {
14074                        // Setting the preferred activity to what it happens to be already
14075                        if (DEBUG_PREFERRED) {
14076                            Slog.i(TAG, "Replacing with same preferred activity "
14077                                    + cur.mPref.mShortComponent + " for user "
14078                                    + userId + ":");
14079                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14080                        }
14081                        return;
14082                    }
14083                }
14084
14085                if (existing != null) {
14086                    if (DEBUG_PREFERRED) {
14087                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14088                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14089                    }
14090                    for (int i = 0; i < existing.size(); i++) {
14091                        PreferredActivity pa = existing.get(i);
14092                        if (DEBUG_PREFERRED) {
14093                            Slog.i(TAG, "Removing existing preferred activity "
14094                                    + pa.mPref.mComponent + ":");
14095                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14096                        }
14097                        pir.removeFilter(pa);
14098                    }
14099                }
14100            }
14101            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14102                    "Replacing preferred");
14103        }
14104    }
14105
14106    @Override
14107    public void clearPackagePreferredActivities(String packageName) {
14108        final int uid = Binder.getCallingUid();
14109        // writer
14110        synchronized (mPackages) {
14111            PackageParser.Package pkg = mPackages.get(packageName);
14112            if (pkg == null || pkg.applicationInfo.uid != uid) {
14113                if (mContext.checkCallingOrSelfPermission(
14114                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14115                        != PackageManager.PERMISSION_GRANTED) {
14116                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14117                            < Build.VERSION_CODES.FROYO) {
14118                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14119                                + Binder.getCallingUid());
14120                        return;
14121                    }
14122                    mContext.enforceCallingOrSelfPermission(
14123                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14124                }
14125            }
14126
14127            int user = UserHandle.getCallingUserId();
14128            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14129                scheduleWritePackageRestrictionsLocked(user);
14130            }
14131        }
14132    }
14133
14134    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14135    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14136        ArrayList<PreferredActivity> removed = null;
14137        boolean changed = false;
14138        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14139            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14140            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14141            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14142                continue;
14143            }
14144            Iterator<PreferredActivity> it = pir.filterIterator();
14145            while (it.hasNext()) {
14146                PreferredActivity pa = it.next();
14147                // Mark entry for removal only if it matches the package name
14148                // and the entry is of type "always".
14149                if (packageName == null ||
14150                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14151                                && pa.mPref.mAlways)) {
14152                    if (removed == null) {
14153                        removed = new ArrayList<PreferredActivity>();
14154                    }
14155                    removed.add(pa);
14156                }
14157            }
14158            if (removed != null) {
14159                for (int j=0; j<removed.size(); j++) {
14160                    PreferredActivity pa = removed.get(j);
14161                    pir.removeFilter(pa);
14162                }
14163                changed = true;
14164            }
14165        }
14166        return changed;
14167    }
14168
14169    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14170    private void clearIntentFilterVerificationsLPw(int userId) {
14171        final int packageCount = mPackages.size();
14172        for (int i = 0; i < packageCount; i++) {
14173            PackageParser.Package pkg = mPackages.valueAt(i);
14174            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14175        }
14176    }
14177
14178    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14179    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14180        if (userId == UserHandle.USER_ALL) {
14181            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14182                    sUserManager.getUserIds())) {
14183                for (int oneUserId : sUserManager.getUserIds()) {
14184                    scheduleWritePackageRestrictionsLocked(oneUserId);
14185                }
14186            }
14187        } else {
14188            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14189                scheduleWritePackageRestrictionsLocked(userId);
14190            }
14191        }
14192    }
14193
14194    void clearDefaultBrowserIfNeeded(String packageName) {
14195        for (int oneUserId : sUserManager.getUserIds()) {
14196            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14197            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14198            if (packageName.equals(defaultBrowserPackageName)) {
14199                setDefaultBrowserPackageName(null, oneUserId);
14200            }
14201        }
14202    }
14203
14204    @Override
14205    public void resetApplicationPreferences(int userId) {
14206        mContext.enforceCallingOrSelfPermission(
14207                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14208        // writer
14209        synchronized (mPackages) {
14210            final long identity = Binder.clearCallingIdentity();
14211            try {
14212                clearPackagePreferredActivitiesLPw(null, userId);
14213                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14214                // TODO: We have to reset the default SMS and Phone. This requires
14215                // significant refactoring to keep all default apps in the package
14216                // manager (cleaner but more work) or have the services provide
14217                // callbacks to the package manager to request a default app reset.
14218                applyFactoryDefaultBrowserLPw(userId);
14219                clearIntentFilterVerificationsLPw(userId);
14220                primeDomainVerificationsLPw(userId);
14221                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14222                scheduleWritePackageRestrictionsLocked(userId);
14223            } finally {
14224                Binder.restoreCallingIdentity(identity);
14225            }
14226        }
14227    }
14228
14229    @Override
14230    public int getPreferredActivities(List<IntentFilter> outFilters,
14231            List<ComponentName> outActivities, String packageName) {
14232
14233        int num = 0;
14234        final int userId = UserHandle.getCallingUserId();
14235        // reader
14236        synchronized (mPackages) {
14237            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14238            if (pir != null) {
14239                final Iterator<PreferredActivity> it = pir.filterIterator();
14240                while (it.hasNext()) {
14241                    final PreferredActivity pa = it.next();
14242                    if (packageName == null
14243                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14244                                    && pa.mPref.mAlways)) {
14245                        if (outFilters != null) {
14246                            outFilters.add(new IntentFilter(pa));
14247                        }
14248                        if (outActivities != null) {
14249                            outActivities.add(pa.mPref.mComponent);
14250                        }
14251                    }
14252                }
14253            }
14254        }
14255
14256        return num;
14257    }
14258
14259    @Override
14260    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14261            int userId) {
14262        int callingUid = Binder.getCallingUid();
14263        if (callingUid != Process.SYSTEM_UID) {
14264            throw new SecurityException(
14265                    "addPersistentPreferredActivity can only be run by the system");
14266        }
14267        if (filter.countActions() == 0) {
14268            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14269            return;
14270        }
14271        synchronized (mPackages) {
14272            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14273                    " :");
14274            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14275            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14276                    new PersistentPreferredActivity(filter, activity));
14277            scheduleWritePackageRestrictionsLocked(userId);
14278        }
14279    }
14280
14281    @Override
14282    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14283        int callingUid = Binder.getCallingUid();
14284        if (callingUid != Process.SYSTEM_UID) {
14285            throw new SecurityException(
14286                    "clearPackagePersistentPreferredActivities can only be run by the system");
14287        }
14288        ArrayList<PersistentPreferredActivity> removed = null;
14289        boolean changed = false;
14290        synchronized (mPackages) {
14291            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14292                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14293                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14294                        .valueAt(i);
14295                if (userId != thisUserId) {
14296                    continue;
14297                }
14298                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14299                while (it.hasNext()) {
14300                    PersistentPreferredActivity ppa = it.next();
14301                    // Mark entry for removal only if it matches the package name.
14302                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14303                        if (removed == null) {
14304                            removed = new ArrayList<PersistentPreferredActivity>();
14305                        }
14306                        removed.add(ppa);
14307                    }
14308                }
14309                if (removed != null) {
14310                    for (int j=0; j<removed.size(); j++) {
14311                        PersistentPreferredActivity ppa = removed.get(j);
14312                        ppir.removeFilter(ppa);
14313                    }
14314                    changed = true;
14315                }
14316            }
14317
14318            if (changed) {
14319                scheduleWritePackageRestrictionsLocked(userId);
14320            }
14321        }
14322    }
14323
14324    /**
14325     * Common machinery for picking apart a restored XML blob and passing
14326     * it to a caller-supplied functor to be applied to the running system.
14327     */
14328    private void restoreFromXml(XmlPullParser parser, int userId,
14329            String expectedStartTag, BlobXmlRestorer functor)
14330            throws IOException, XmlPullParserException {
14331        int type;
14332        while ((type = parser.next()) != XmlPullParser.START_TAG
14333                && type != XmlPullParser.END_DOCUMENT) {
14334        }
14335        if (type != XmlPullParser.START_TAG) {
14336            // oops didn't find a start tag?!
14337            if (DEBUG_BACKUP) {
14338                Slog.e(TAG, "Didn't find start tag during restore");
14339            }
14340            return;
14341        }
14342
14343        // this is supposed to be TAG_PREFERRED_BACKUP
14344        if (!expectedStartTag.equals(parser.getName())) {
14345            if (DEBUG_BACKUP) {
14346                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14347            }
14348            return;
14349        }
14350
14351        // skip interfering stuff, then we're aligned with the backing implementation
14352        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14353        functor.apply(parser, userId);
14354    }
14355
14356    private interface BlobXmlRestorer {
14357        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14358    }
14359
14360    /**
14361     * Non-Binder method, support for the backup/restore mechanism: write the
14362     * full set of preferred activities in its canonical XML format.  Returns the
14363     * XML output as a byte array, or null if there is none.
14364     */
14365    @Override
14366    public byte[] getPreferredActivityBackup(int userId) {
14367        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14368            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14369        }
14370
14371        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14372        try {
14373            final XmlSerializer serializer = new FastXmlSerializer();
14374            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14375            serializer.startDocument(null, true);
14376            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14377
14378            synchronized (mPackages) {
14379                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14380            }
14381
14382            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14383            serializer.endDocument();
14384            serializer.flush();
14385        } catch (Exception e) {
14386            if (DEBUG_BACKUP) {
14387                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14388            }
14389            return null;
14390        }
14391
14392        return dataStream.toByteArray();
14393    }
14394
14395    @Override
14396    public void restorePreferredActivities(byte[] backup, int userId) {
14397        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14398            throw new SecurityException("Only the system may call restorePreferredActivities()");
14399        }
14400
14401        try {
14402            final XmlPullParser parser = Xml.newPullParser();
14403            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14404            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14405                    new BlobXmlRestorer() {
14406                        @Override
14407                        public void apply(XmlPullParser parser, int userId)
14408                                throws XmlPullParserException, IOException {
14409                            synchronized (mPackages) {
14410                                mSettings.readPreferredActivitiesLPw(parser, userId);
14411                            }
14412                        }
14413                    } );
14414        } catch (Exception e) {
14415            if (DEBUG_BACKUP) {
14416                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14417            }
14418        }
14419    }
14420
14421    /**
14422     * Non-Binder method, support for the backup/restore mechanism: write the
14423     * default browser (etc) settings in its canonical XML format.  Returns the default
14424     * browser XML representation as a byte array, or null if there is none.
14425     */
14426    @Override
14427    public byte[] getDefaultAppsBackup(int userId) {
14428        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14429            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14430        }
14431
14432        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14433        try {
14434            final XmlSerializer serializer = new FastXmlSerializer();
14435            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14436            serializer.startDocument(null, true);
14437            serializer.startTag(null, TAG_DEFAULT_APPS);
14438
14439            synchronized (mPackages) {
14440                mSettings.writeDefaultAppsLPr(serializer, userId);
14441            }
14442
14443            serializer.endTag(null, TAG_DEFAULT_APPS);
14444            serializer.endDocument();
14445            serializer.flush();
14446        } catch (Exception e) {
14447            if (DEBUG_BACKUP) {
14448                Slog.e(TAG, "Unable to write default apps for backup", e);
14449            }
14450            return null;
14451        }
14452
14453        return dataStream.toByteArray();
14454    }
14455
14456    @Override
14457    public void restoreDefaultApps(byte[] backup, int userId) {
14458        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14459            throw new SecurityException("Only the system may call restoreDefaultApps()");
14460        }
14461
14462        try {
14463            final XmlPullParser parser = Xml.newPullParser();
14464            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14465            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14466                    new BlobXmlRestorer() {
14467                        @Override
14468                        public void apply(XmlPullParser parser, int userId)
14469                                throws XmlPullParserException, IOException {
14470                            synchronized (mPackages) {
14471                                mSettings.readDefaultAppsLPw(parser, userId);
14472                            }
14473                        }
14474                    } );
14475        } catch (Exception e) {
14476            if (DEBUG_BACKUP) {
14477                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14478            }
14479        }
14480    }
14481
14482    @Override
14483    public byte[] getIntentFilterVerificationBackup(int userId) {
14484        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14485            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14486        }
14487
14488        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14489        try {
14490            final XmlSerializer serializer = new FastXmlSerializer();
14491            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14492            serializer.startDocument(null, true);
14493            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14494
14495            synchronized (mPackages) {
14496                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14497            }
14498
14499            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14500            serializer.endDocument();
14501            serializer.flush();
14502        } catch (Exception e) {
14503            if (DEBUG_BACKUP) {
14504                Slog.e(TAG, "Unable to write default apps for backup", e);
14505            }
14506            return null;
14507        }
14508
14509        return dataStream.toByteArray();
14510    }
14511
14512    @Override
14513    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14514        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14515            throw new SecurityException("Only the system may call restorePreferredActivities()");
14516        }
14517
14518        try {
14519            final XmlPullParser parser = Xml.newPullParser();
14520            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14521            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14522                    new BlobXmlRestorer() {
14523                        @Override
14524                        public void apply(XmlPullParser parser, int userId)
14525                                throws XmlPullParserException, IOException {
14526                            synchronized (mPackages) {
14527                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14528                                mSettings.writeLPr();
14529                            }
14530                        }
14531                    } );
14532        } catch (Exception e) {
14533            if (DEBUG_BACKUP) {
14534                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14535            }
14536        }
14537    }
14538
14539    @Override
14540    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14541            int sourceUserId, int targetUserId, int flags) {
14542        mContext.enforceCallingOrSelfPermission(
14543                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14544        int callingUid = Binder.getCallingUid();
14545        enforceOwnerRights(ownerPackage, callingUid);
14546        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14547        if (intentFilter.countActions() == 0) {
14548            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14549            return;
14550        }
14551        synchronized (mPackages) {
14552            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14553                    ownerPackage, targetUserId, flags);
14554            CrossProfileIntentResolver resolver =
14555                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14556            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14557            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14558            if (existing != null) {
14559                int size = existing.size();
14560                for (int i = 0; i < size; i++) {
14561                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14562                        return;
14563                    }
14564                }
14565            }
14566            resolver.addFilter(newFilter);
14567            scheduleWritePackageRestrictionsLocked(sourceUserId);
14568        }
14569    }
14570
14571    @Override
14572    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14573        mContext.enforceCallingOrSelfPermission(
14574                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14575        int callingUid = Binder.getCallingUid();
14576        enforceOwnerRights(ownerPackage, callingUid);
14577        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14578        synchronized (mPackages) {
14579            CrossProfileIntentResolver resolver =
14580                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14581            ArraySet<CrossProfileIntentFilter> set =
14582                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
14583            for (CrossProfileIntentFilter filter : set) {
14584                if (filter.getOwnerPackage().equals(ownerPackage)) {
14585                    resolver.removeFilter(filter);
14586                }
14587            }
14588            scheduleWritePackageRestrictionsLocked(sourceUserId);
14589        }
14590    }
14591
14592    // Enforcing that callingUid is owning pkg on userId
14593    private void enforceOwnerRights(String pkg, int callingUid) {
14594        // The system owns everything.
14595        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
14596            return;
14597        }
14598        int callingUserId = UserHandle.getUserId(callingUid);
14599        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
14600        if (pi == null) {
14601            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
14602                    + callingUserId);
14603        }
14604        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
14605            throw new SecurityException("Calling uid " + callingUid
14606                    + " does not own package " + pkg);
14607        }
14608    }
14609
14610    @Override
14611    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
14612        Intent intent = new Intent(Intent.ACTION_MAIN);
14613        intent.addCategory(Intent.CATEGORY_HOME);
14614
14615        final int callingUserId = UserHandle.getCallingUserId();
14616        List<ResolveInfo> list = queryIntentActivities(intent, null,
14617                PackageManager.GET_META_DATA, callingUserId);
14618        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
14619                true, false, false, callingUserId);
14620
14621        allHomeCandidates.clear();
14622        if (list != null) {
14623            for (ResolveInfo ri : list) {
14624                allHomeCandidates.add(ri);
14625            }
14626        }
14627        return (preferred == null || preferred.activityInfo == null)
14628                ? null
14629                : new ComponentName(preferred.activityInfo.packageName,
14630                        preferred.activityInfo.name);
14631    }
14632
14633    @Override
14634    public void setApplicationEnabledSetting(String appPackageName,
14635            int newState, int flags, int userId, String callingPackage) {
14636        if (!sUserManager.exists(userId)) return;
14637        if (callingPackage == null) {
14638            callingPackage = Integer.toString(Binder.getCallingUid());
14639        }
14640        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
14641    }
14642
14643    @Override
14644    public void setComponentEnabledSetting(ComponentName componentName,
14645            int newState, int flags, int userId) {
14646        if (!sUserManager.exists(userId)) return;
14647        setEnabledSetting(componentName.getPackageName(),
14648                componentName.getClassName(), newState, flags, userId, null);
14649    }
14650
14651    private void setEnabledSetting(final String packageName, String className, int newState,
14652            final int flags, int userId, String callingPackage) {
14653        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
14654              || newState == COMPONENT_ENABLED_STATE_ENABLED
14655              || newState == COMPONENT_ENABLED_STATE_DISABLED
14656              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
14657              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
14658            throw new IllegalArgumentException("Invalid new component state: "
14659                    + newState);
14660        }
14661        PackageSetting pkgSetting;
14662        final int uid = Binder.getCallingUid();
14663        final int permission = mContext.checkCallingOrSelfPermission(
14664                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14665        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
14666        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14667        boolean sendNow = false;
14668        boolean isApp = (className == null);
14669        String componentName = isApp ? packageName : className;
14670        int packageUid = -1;
14671        ArrayList<String> components;
14672
14673        // writer
14674        synchronized (mPackages) {
14675            pkgSetting = mSettings.mPackages.get(packageName);
14676            if (pkgSetting == null) {
14677                if (className == null) {
14678                    throw new IllegalArgumentException(
14679                            "Unknown package: " + packageName);
14680                }
14681                throw new IllegalArgumentException(
14682                        "Unknown component: " + packageName
14683                        + "/" + className);
14684            }
14685            // Allow root and verify that userId is not being specified by a different user
14686            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
14687                throw new SecurityException(
14688                        "Permission Denial: attempt to change component state from pid="
14689                        + Binder.getCallingPid()
14690                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
14691            }
14692            if (className == null) {
14693                // We're dealing with an application/package level state change
14694                if (pkgSetting.getEnabled(userId) == newState) {
14695                    // Nothing to do
14696                    return;
14697                }
14698                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
14699                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
14700                    // Don't care about who enables an app.
14701                    callingPackage = null;
14702                }
14703                pkgSetting.setEnabled(newState, userId, callingPackage);
14704                // pkgSetting.pkg.mSetEnabled = newState;
14705            } else {
14706                // We're dealing with a component level state change
14707                // First, verify that this is a valid class name.
14708                PackageParser.Package pkg = pkgSetting.pkg;
14709                if (pkg == null || !pkg.hasComponentClassName(className)) {
14710                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
14711                        throw new IllegalArgumentException("Component class " + className
14712                                + " does not exist in " + packageName);
14713                    } else {
14714                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
14715                                + className + " does not exist in " + packageName);
14716                    }
14717                }
14718                switch (newState) {
14719                case COMPONENT_ENABLED_STATE_ENABLED:
14720                    if (!pkgSetting.enableComponentLPw(className, userId)) {
14721                        return;
14722                    }
14723                    break;
14724                case COMPONENT_ENABLED_STATE_DISABLED:
14725                    if (!pkgSetting.disableComponentLPw(className, userId)) {
14726                        return;
14727                    }
14728                    break;
14729                case COMPONENT_ENABLED_STATE_DEFAULT:
14730                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
14731                        return;
14732                    }
14733                    break;
14734                default:
14735                    Slog.e(TAG, "Invalid new component state: " + newState);
14736                    return;
14737                }
14738            }
14739            scheduleWritePackageRestrictionsLocked(userId);
14740            components = mPendingBroadcasts.get(userId, packageName);
14741            final boolean newPackage = components == null;
14742            if (newPackage) {
14743                components = new ArrayList<String>();
14744            }
14745            if (!components.contains(componentName)) {
14746                components.add(componentName);
14747            }
14748            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
14749                sendNow = true;
14750                // Purge entry from pending broadcast list if another one exists already
14751                // since we are sending one right away.
14752                mPendingBroadcasts.remove(userId, packageName);
14753            } else {
14754                if (newPackage) {
14755                    mPendingBroadcasts.put(userId, packageName, components);
14756                }
14757                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
14758                    // Schedule a message
14759                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
14760                }
14761            }
14762        }
14763
14764        long callingId = Binder.clearCallingIdentity();
14765        try {
14766            if (sendNow) {
14767                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
14768                sendPackageChangedBroadcast(packageName,
14769                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
14770            }
14771        } finally {
14772            Binder.restoreCallingIdentity(callingId);
14773        }
14774    }
14775
14776    private void sendPackageChangedBroadcast(String packageName,
14777            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
14778        if (DEBUG_INSTALL)
14779            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
14780                    + componentNames);
14781        Bundle extras = new Bundle(4);
14782        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
14783        String nameList[] = new String[componentNames.size()];
14784        componentNames.toArray(nameList);
14785        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
14786        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
14787        extras.putInt(Intent.EXTRA_UID, packageUid);
14788        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
14789                new int[] {UserHandle.getUserId(packageUid)});
14790    }
14791
14792    @Override
14793    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
14794        if (!sUserManager.exists(userId)) return;
14795        final int uid = Binder.getCallingUid();
14796        final int permission = mContext.checkCallingOrSelfPermission(
14797                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
14798        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
14799        enforceCrossUserPermission(uid, userId, true, true, "stop package");
14800        // writer
14801        synchronized (mPackages) {
14802            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
14803                    allowedByPermission, uid, userId)) {
14804                scheduleWritePackageRestrictionsLocked(userId);
14805            }
14806        }
14807    }
14808
14809    @Override
14810    public String getInstallerPackageName(String packageName) {
14811        // reader
14812        synchronized (mPackages) {
14813            return mSettings.getInstallerPackageNameLPr(packageName);
14814        }
14815    }
14816
14817    @Override
14818    public int getApplicationEnabledSetting(String packageName, int userId) {
14819        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14820        int uid = Binder.getCallingUid();
14821        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
14822        // reader
14823        synchronized (mPackages) {
14824            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
14825        }
14826    }
14827
14828    @Override
14829    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
14830        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
14831        int uid = Binder.getCallingUid();
14832        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
14833        // reader
14834        synchronized (mPackages) {
14835            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
14836        }
14837    }
14838
14839    @Override
14840    public void enterSafeMode() {
14841        enforceSystemOrRoot("Only the system can request entering safe mode");
14842
14843        if (!mSystemReady) {
14844            mSafeMode = true;
14845        }
14846    }
14847
14848    @Override
14849    public void systemReady() {
14850        mSystemReady = true;
14851
14852        // Read the compatibilty setting when the system is ready.
14853        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
14854                mContext.getContentResolver(),
14855                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
14856        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
14857        if (DEBUG_SETTINGS) {
14858            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
14859        }
14860
14861        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
14862
14863        synchronized (mPackages) {
14864            // Verify that all of the preferred activity components actually
14865            // exist.  It is possible for applications to be updated and at
14866            // that point remove a previously declared activity component that
14867            // had been set as a preferred activity.  We try to clean this up
14868            // the next time we encounter that preferred activity, but it is
14869            // possible for the user flow to never be able to return to that
14870            // situation so here we do a sanity check to make sure we haven't
14871            // left any junk around.
14872            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
14873            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14874                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14875                removed.clear();
14876                for (PreferredActivity pa : pir.filterSet()) {
14877                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
14878                        removed.add(pa);
14879                    }
14880                }
14881                if (removed.size() > 0) {
14882                    for (int r=0; r<removed.size(); r++) {
14883                        PreferredActivity pa = removed.get(r);
14884                        Slog.w(TAG, "Removing dangling preferred activity: "
14885                                + pa.mPref.mComponent);
14886                        pir.removeFilter(pa);
14887                    }
14888                    mSettings.writePackageRestrictionsLPr(
14889                            mSettings.mPreferredActivities.keyAt(i));
14890                }
14891            }
14892
14893            for (int userId : UserManagerService.getInstance().getUserIds()) {
14894                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
14895                    grantPermissionsUserIds = ArrayUtils.appendInt(
14896                            grantPermissionsUserIds, userId);
14897                }
14898            }
14899        }
14900        sUserManager.systemReady();
14901
14902        // If we upgraded grant all default permissions before kicking off.
14903        for (int userId : grantPermissionsUserIds) {
14904            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
14905        }
14906
14907        // Kick off any messages waiting for system ready
14908        if (mPostSystemReadyMessages != null) {
14909            for (Message msg : mPostSystemReadyMessages) {
14910                msg.sendToTarget();
14911            }
14912            mPostSystemReadyMessages = null;
14913        }
14914
14915        // Watch for external volumes that come and go over time
14916        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14917        storage.registerListener(mStorageListener);
14918
14919        mInstallerService.systemReady();
14920        mPackageDexOptimizer.systemReady();
14921
14922        MountServiceInternal mountServiceInternal = LocalServices.getService(
14923                MountServiceInternal.class);
14924        mountServiceInternal.addExternalStoragePolicy(
14925                new MountServiceInternal.ExternalStorageMountPolicy() {
14926            @Override
14927            public int getMountMode(int uid, String packageName) {
14928                if (Process.isIsolated(uid)) {
14929                    return Zygote.MOUNT_EXTERNAL_NONE;
14930                }
14931                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
14932                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14933                }
14934                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14935                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
14936                }
14937                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
14938                    return Zygote.MOUNT_EXTERNAL_READ;
14939                }
14940                return Zygote.MOUNT_EXTERNAL_WRITE;
14941            }
14942
14943            @Override
14944            public boolean hasExternalStorage(int uid, String packageName) {
14945                return true;
14946            }
14947        });
14948    }
14949
14950    @Override
14951    public boolean isSafeMode() {
14952        return mSafeMode;
14953    }
14954
14955    @Override
14956    public boolean hasSystemUidErrors() {
14957        return mHasSystemUidErrors;
14958    }
14959
14960    static String arrayToString(int[] array) {
14961        StringBuffer buf = new StringBuffer(128);
14962        buf.append('[');
14963        if (array != null) {
14964            for (int i=0; i<array.length; i++) {
14965                if (i > 0) buf.append(", ");
14966                buf.append(array[i]);
14967            }
14968        }
14969        buf.append(']');
14970        return buf.toString();
14971    }
14972
14973    static class DumpState {
14974        public static final int DUMP_LIBS = 1 << 0;
14975        public static final int DUMP_FEATURES = 1 << 1;
14976        public static final int DUMP_RESOLVERS = 1 << 2;
14977        public static final int DUMP_PERMISSIONS = 1 << 3;
14978        public static final int DUMP_PACKAGES = 1 << 4;
14979        public static final int DUMP_SHARED_USERS = 1 << 5;
14980        public static final int DUMP_MESSAGES = 1 << 6;
14981        public static final int DUMP_PROVIDERS = 1 << 7;
14982        public static final int DUMP_VERIFIERS = 1 << 8;
14983        public static final int DUMP_PREFERRED = 1 << 9;
14984        public static final int DUMP_PREFERRED_XML = 1 << 10;
14985        public static final int DUMP_KEYSETS = 1 << 11;
14986        public static final int DUMP_VERSION = 1 << 12;
14987        public static final int DUMP_INSTALLS = 1 << 13;
14988        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
14989        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
14990
14991        public static final int OPTION_SHOW_FILTERS = 1 << 0;
14992
14993        private int mTypes;
14994
14995        private int mOptions;
14996
14997        private boolean mTitlePrinted;
14998
14999        private SharedUserSetting mSharedUser;
15000
15001        public boolean isDumping(int type) {
15002            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15003                return true;
15004            }
15005
15006            return (mTypes & type) != 0;
15007        }
15008
15009        public void setDump(int type) {
15010            mTypes |= type;
15011        }
15012
15013        public boolean isOptionEnabled(int option) {
15014            return (mOptions & option) != 0;
15015        }
15016
15017        public void setOptionEnabled(int option) {
15018            mOptions |= option;
15019        }
15020
15021        public boolean onTitlePrinted() {
15022            final boolean printed = mTitlePrinted;
15023            mTitlePrinted = true;
15024            return printed;
15025        }
15026
15027        public boolean getTitlePrinted() {
15028            return mTitlePrinted;
15029        }
15030
15031        public void setTitlePrinted(boolean enabled) {
15032            mTitlePrinted = enabled;
15033        }
15034
15035        public SharedUserSetting getSharedUser() {
15036            return mSharedUser;
15037        }
15038
15039        public void setSharedUser(SharedUserSetting user) {
15040            mSharedUser = user;
15041        }
15042    }
15043
15044    @Override
15045    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15046        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15047                != PackageManager.PERMISSION_GRANTED) {
15048            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15049                    + Binder.getCallingPid()
15050                    + ", uid=" + Binder.getCallingUid()
15051                    + " without permission "
15052                    + android.Manifest.permission.DUMP);
15053            return;
15054        }
15055
15056        DumpState dumpState = new DumpState();
15057        boolean fullPreferred = false;
15058        boolean checkin = false;
15059
15060        String packageName = null;
15061        ArraySet<String> permissionNames = null;
15062
15063        int opti = 0;
15064        while (opti < args.length) {
15065            String opt = args[opti];
15066            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15067                break;
15068            }
15069            opti++;
15070
15071            if ("-a".equals(opt)) {
15072                // Right now we only know how to print all.
15073            } else if ("-h".equals(opt)) {
15074                pw.println("Package manager dump options:");
15075                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15076                pw.println("    --checkin: dump for a checkin");
15077                pw.println("    -f: print details of intent filters");
15078                pw.println("    -h: print this help");
15079                pw.println("  cmd may be one of:");
15080                pw.println("    l[ibraries]: list known shared libraries");
15081                pw.println("    f[ibraries]: list device features");
15082                pw.println("    k[eysets]: print known keysets");
15083                pw.println("    r[esolvers]: dump intent resolvers");
15084                pw.println("    perm[issions]: dump permissions");
15085                pw.println("    permission [name ...]: dump declaration and use of given permission");
15086                pw.println("    pref[erred]: print preferred package settings");
15087                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15088                pw.println("    prov[iders]: dump content providers");
15089                pw.println("    p[ackages]: dump installed packages");
15090                pw.println("    s[hared-users]: dump shared user IDs");
15091                pw.println("    m[essages]: print collected runtime messages");
15092                pw.println("    v[erifiers]: print package verifier info");
15093                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15094                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15095                pw.println("    version: print database version info");
15096                pw.println("    write: write current settings now");
15097                pw.println("    installs: details about install sessions");
15098                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15099                pw.println("    <package.name>: info about given package");
15100                return;
15101            } else if ("--checkin".equals(opt)) {
15102                checkin = true;
15103            } else if ("-f".equals(opt)) {
15104                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15105            } else {
15106                pw.println("Unknown argument: " + opt + "; use -h for help");
15107            }
15108        }
15109
15110        // Is the caller requesting to dump a particular piece of data?
15111        if (opti < args.length) {
15112            String cmd = args[opti];
15113            opti++;
15114            // Is this a package name?
15115            if ("android".equals(cmd) || cmd.contains(".")) {
15116                packageName = cmd;
15117                // When dumping a single package, we always dump all of its
15118                // filter information since the amount of data will be reasonable.
15119                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15120            } else if ("check-permission".equals(cmd)) {
15121                if (opti >= args.length) {
15122                    pw.println("Error: check-permission missing permission argument");
15123                    return;
15124                }
15125                String perm = args[opti];
15126                opti++;
15127                if (opti >= args.length) {
15128                    pw.println("Error: check-permission missing package argument");
15129                    return;
15130                }
15131                String pkg = args[opti];
15132                opti++;
15133                int user = UserHandle.getUserId(Binder.getCallingUid());
15134                if (opti < args.length) {
15135                    try {
15136                        user = Integer.parseInt(args[opti]);
15137                    } catch (NumberFormatException e) {
15138                        pw.println("Error: check-permission user argument is not a number: "
15139                                + args[opti]);
15140                        return;
15141                    }
15142                }
15143                pw.println(checkPermission(perm, pkg, user));
15144                return;
15145            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15146                dumpState.setDump(DumpState.DUMP_LIBS);
15147            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15148                dumpState.setDump(DumpState.DUMP_FEATURES);
15149            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15150                dumpState.setDump(DumpState.DUMP_RESOLVERS);
15151            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15152                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15153            } else if ("permission".equals(cmd)) {
15154                if (opti >= args.length) {
15155                    pw.println("Error: permission requires permission name");
15156                    return;
15157                }
15158                permissionNames = new ArraySet<>();
15159                while (opti < args.length) {
15160                    permissionNames.add(args[opti]);
15161                    opti++;
15162                }
15163                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15164                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15165            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15166                dumpState.setDump(DumpState.DUMP_PREFERRED);
15167            } else if ("preferred-xml".equals(cmd)) {
15168                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15169                if (opti < args.length && "--full".equals(args[opti])) {
15170                    fullPreferred = true;
15171                    opti++;
15172                }
15173            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15174                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15175            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15176                dumpState.setDump(DumpState.DUMP_PACKAGES);
15177            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15178                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15179            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15180                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15181            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15182                dumpState.setDump(DumpState.DUMP_MESSAGES);
15183            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15184                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15185            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15186                    || "intent-filter-verifiers".equals(cmd)) {
15187                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15188            } else if ("version".equals(cmd)) {
15189                dumpState.setDump(DumpState.DUMP_VERSION);
15190            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15191                dumpState.setDump(DumpState.DUMP_KEYSETS);
15192            } else if ("installs".equals(cmd)) {
15193                dumpState.setDump(DumpState.DUMP_INSTALLS);
15194            } else if ("write".equals(cmd)) {
15195                synchronized (mPackages) {
15196                    mSettings.writeLPr();
15197                    pw.println("Settings written.");
15198                    return;
15199                }
15200            }
15201        }
15202
15203        if (checkin) {
15204            pw.println("vers,1");
15205        }
15206
15207        // reader
15208        synchronized (mPackages) {
15209            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15210                if (!checkin) {
15211                    if (dumpState.onTitlePrinted())
15212                        pw.println();
15213                    pw.println("Database versions:");
15214                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15215                }
15216            }
15217
15218            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15219                if (!checkin) {
15220                    if (dumpState.onTitlePrinted())
15221                        pw.println();
15222                    pw.println("Verifiers:");
15223                    pw.print("  Required: ");
15224                    pw.print(mRequiredVerifierPackage);
15225                    pw.print(" (uid=");
15226                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
15227                    pw.println(")");
15228                } else if (mRequiredVerifierPackage != null) {
15229                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15230                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
15231                }
15232            }
15233
15234            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15235                    packageName == null) {
15236                if (mIntentFilterVerifierComponent != null) {
15237                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15238                    if (!checkin) {
15239                        if (dumpState.onTitlePrinted())
15240                            pw.println();
15241                        pw.println("Intent Filter Verifier:");
15242                        pw.print("  Using: ");
15243                        pw.print(verifierPackageName);
15244                        pw.print(" (uid=");
15245                        pw.print(getPackageUid(verifierPackageName, 0));
15246                        pw.println(")");
15247                    } else if (verifierPackageName != null) {
15248                        pw.print("ifv,"); pw.print(verifierPackageName);
15249                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
15250                    }
15251                } else {
15252                    pw.println();
15253                    pw.println("No Intent Filter Verifier available!");
15254                }
15255            }
15256
15257            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15258                boolean printedHeader = false;
15259                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15260                while (it.hasNext()) {
15261                    String name = it.next();
15262                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15263                    if (!checkin) {
15264                        if (!printedHeader) {
15265                            if (dumpState.onTitlePrinted())
15266                                pw.println();
15267                            pw.println("Libraries:");
15268                            printedHeader = true;
15269                        }
15270                        pw.print("  ");
15271                    } else {
15272                        pw.print("lib,");
15273                    }
15274                    pw.print(name);
15275                    if (!checkin) {
15276                        pw.print(" -> ");
15277                    }
15278                    if (ent.path != null) {
15279                        if (!checkin) {
15280                            pw.print("(jar) ");
15281                            pw.print(ent.path);
15282                        } else {
15283                            pw.print(",jar,");
15284                            pw.print(ent.path);
15285                        }
15286                    } else {
15287                        if (!checkin) {
15288                            pw.print("(apk) ");
15289                            pw.print(ent.apk);
15290                        } else {
15291                            pw.print(",apk,");
15292                            pw.print(ent.apk);
15293                        }
15294                    }
15295                    pw.println();
15296                }
15297            }
15298
15299            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15300                if (dumpState.onTitlePrinted())
15301                    pw.println();
15302                if (!checkin) {
15303                    pw.println("Features:");
15304                }
15305                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15306                while (it.hasNext()) {
15307                    String name = it.next();
15308                    if (!checkin) {
15309                        pw.print("  ");
15310                    } else {
15311                        pw.print("feat,");
15312                    }
15313                    pw.println(name);
15314                }
15315            }
15316
15317            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
15318                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15319                        : "Activity Resolver Table:", "  ", packageName,
15320                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15321                    dumpState.setTitlePrinted(true);
15322                }
15323                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15324                        : "Receiver Resolver Table:", "  ", packageName,
15325                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15326                    dumpState.setTitlePrinted(true);
15327                }
15328                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15329                        : "Service Resolver Table:", "  ", packageName,
15330                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15331                    dumpState.setTitlePrinted(true);
15332                }
15333                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15334                        : "Provider Resolver Table:", "  ", packageName,
15335                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15336                    dumpState.setTitlePrinted(true);
15337                }
15338            }
15339
15340            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15341                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15342                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15343                    int user = mSettings.mPreferredActivities.keyAt(i);
15344                    if (pir.dump(pw,
15345                            dumpState.getTitlePrinted()
15346                                ? "\nPreferred Activities User " + user + ":"
15347                                : "Preferred Activities User " + user + ":", "  ",
15348                            packageName, true, false)) {
15349                        dumpState.setTitlePrinted(true);
15350                    }
15351                }
15352            }
15353
15354            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15355                pw.flush();
15356                FileOutputStream fout = new FileOutputStream(fd);
15357                BufferedOutputStream str = new BufferedOutputStream(fout);
15358                XmlSerializer serializer = new FastXmlSerializer();
15359                try {
15360                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15361                    serializer.startDocument(null, true);
15362                    serializer.setFeature(
15363                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15364                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15365                    serializer.endDocument();
15366                    serializer.flush();
15367                } catch (IllegalArgumentException e) {
15368                    pw.println("Failed writing: " + e);
15369                } catch (IllegalStateException e) {
15370                    pw.println("Failed writing: " + e);
15371                } catch (IOException e) {
15372                    pw.println("Failed writing: " + e);
15373                }
15374            }
15375
15376            if (!checkin
15377                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15378                    && packageName == null) {
15379                pw.println();
15380                int count = mSettings.mPackages.size();
15381                if (count == 0) {
15382                    pw.println("No applications!");
15383                    pw.println();
15384                } else {
15385                    final String prefix = "  ";
15386                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15387                    if (allPackageSettings.size() == 0) {
15388                        pw.println("No domain preferred apps!");
15389                        pw.println();
15390                    } else {
15391                        pw.println("App verification status:");
15392                        pw.println();
15393                        count = 0;
15394                        for (PackageSetting ps : allPackageSettings) {
15395                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15396                            if (ivi == null || ivi.getPackageName() == null) continue;
15397                            pw.println(prefix + "Package: " + ivi.getPackageName());
15398                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15399                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15400                            pw.println();
15401                            count++;
15402                        }
15403                        if (count == 0) {
15404                            pw.println(prefix + "No app verification established.");
15405                            pw.println();
15406                        }
15407                        for (int userId : sUserManager.getUserIds()) {
15408                            pw.println("App linkages for user " + userId + ":");
15409                            pw.println();
15410                            count = 0;
15411                            for (PackageSetting ps : allPackageSettings) {
15412                                final long status = ps.getDomainVerificationStatusForUser(userId);
15413                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15414                                    continue;
15415                                }
15416                                pw.println(prefix + "Package: " + ps.name);
15417                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15418                                String statusStr = IntentFilterVerificationInfo.
15419                                        getStatusStringFromValue(status);
15420                                pw.println(prefix + "Status:  " + statusStr);
15421                                pw.println();
15422                                count++;
15423                            }
15424                            if (count == 0) {
15425                                pw.println(prefix + "No configured app linkages.");
15426                                pw.println();
15427                            }
15428                        }
15429                    }
15430                }
15431            }
15432
15433            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15434                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15435                if (packageName == null && permissionNames == null) {
15436                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15437                        if (iperm == 0) {
15438                            if (dumpState.onTitlePrinted())
15439                                pw.println();
15440                            pw.println("AppOp Permissions:");
15441                        }
15442                        pw.print("  AppOp Permission ");
15443                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15444                        pw.println(":");
15445                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15446                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15447                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15448                        }
15449                    }
15450                }
15451            }
15452
15453            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15454                boolean printedSomething = false;
15455                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15456                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15457                        continue;
15458                    }
15459                    if (!printedSomething) {
15460                        if (dumpState.onTitlePrinted())
15461                            pw.println();
15462                        pw.println("Registered ContentProviders:");
15463                        printedSomething = true;
15464                    }
15465                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15466                    pw.print("    "); pw.println(p.toString());
15467                }
15468                printedSomething = false;
15469                for (Map.Entry<String, PackageParser.Provider> entry :
15470                        mProvidersByAuthority.entrySet()) {
15471                    PackageParser.Provider p = entry.getValue();
15472                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15473                        continue;
15474                    }
15475                    if (!printedSomething) {
15476                        if (dumpState.onTitlePrinted())
15477                            pw.println();
15478                        pw.println("ContentProvider Authorities:");
15479                        printedSomething = true;
15480                    }
15481                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15482                    pw.print("    "); pw.println(p.toString());
15483                    if (p.info != null && p.info.applicationInfo != null) {
15484                        final String appInfo = p.info.applicationInfo.toString();
15485                        pw.print("      applicationInfo="); pw.println(appInfo);
15486                    }
15487                }
15488            }
15489
15490            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15491                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15492            }
15493
15494            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15495                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15496            }
15497
15498            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15499                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15500            }
15501
15502            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15503                // XXX should handle packageName != null by dumping only install data that
15504                // the given package is involved with.
15505                if (dumpState.onTitlePrinted()) pw.println();
15506                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15507            }
15508
15509            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15510                if (dumpState.onTitlePrinted()) pw.println();
15511                mSettings.dumpReadMessagesLPr(pw, dumpState);
15512
15513                pw.println();
15514                pw.println("Package warning messages:");
15515                BufferedReader in = null;
15516                String line = null;
15517                try {
15518                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15519                    while ((line = in.readLine()) != null) {
15520                        if (line.contains("ignored: updated version")) continue;
15521                        pw.println(line);
15522                    }
15523                } catch (IOException ignored) {
15524                } finally {
15525                    IoUtils.closeQuietly(in);
15526                }
15527            }
15528
15529            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
15530                BufferedReader in = null;
15531                String line = null;
15532                try {
15533                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15534                    while ((line = in.readLine()) != null) {
15535                        if (line.contains("ignored: updated version")) continue;
15536                        pw.print("msg,");
15537                        pw.println(line);
15538                    }
15539                } catch (IOException ignored) {
15540                } finally {
15541                    IoUtils.closeQuietly(in);
15542                }
15543            }
15544        }
15545    }
15546
15547    private String dumpDomainString(String packageName) {
15548        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
15549        List<IntentFilter> filters = getAllIntentFilters(packageName);
15550
15551        ArraySet<String> result = new ArraySet<>();
15552        if (iviList.size() > 0) {
15553            for (IntentFilterVerificationInfo ivi : iviList) {
15554                for (String host : ivi.getDomains()) {
15555                    result.add(host);
15556                }
15557            }
15558        }
15559        if (filters != null && filters.size() > 0) {
15560            for (IntentFilter filter : filters) {
15561                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
15562                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
15563                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
15564                    result.addAll(filter.getHostsList());
15565                }
15566            }
15567        }
15568
15569        StringBuilder sb = new StringBuilder(result.size() * 16);
15570        for (String domain : result) {
15571            if (sb.length() > 0) sb.append(" ");
15572            sb.append(domain);
15573        }
15574        return sb.toString();
15575    }
15576
15577    // ------- apps on sdcard specific code -------
15578    static final boolean DEBUG_SD_INSTALL = false;
15579
15580    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
15581
15582    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
15583
15584    private boolean mMediaMounted = false;
15585
15586    static String getEncryptKey() {
15587        try {
15588            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
15589                    SD_ENCRYPTION_KEYSTORE_NAME);
15590            if (sdEncKey == null) {
15591                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
15592                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
15593                if (sdEncKey == null) {
15594                    Slog.e(TAG, "Failed to create encryption keys");
15595                    return null;
15596                }
15597            }
15598            return sdEncKey;
15599        } catch (NoSuchAlgorithmException nsae) {
15600            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
15601            return null;
15602        } catch (IOException ioe) {
15603            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
15604            return null;
15605        }
15606    }
15607
15608    /*
15609     * Update media status on PackageManager.
15610     */
15611    @Override
15612    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
15613        int callingUid = Binder.getCallingUid();
15614        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
15615            throw new SecurityException("Media status can only be updated by the system");
15616        }
15617        // reader; this apparently protects mMediaMounted, but should probably
15618        // be a different lock in that case.
15619        synchronized (mPackages) {
15620            Log.i(TAG, "Updating external media status from "
15621                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
15622                    + (mediaStatus ? "mounted" : "unmounted"));
15623            if (DEBUG_SD_INSTALL)
15624                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
15625                        + ", mMediaMounted=" + mMediaMounted);
15626            if (mediaStatus == mMediaMounted) {
15627                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
15628                        : 0, -1);
15629                mHandler.sendMessage(msg);
15630                return;
15631            }
15632            mMediaMounted = mediaStatus;
15633        }
15634        // Queue up an async operation since the package installation may take a
15635        // little while.
15636        mHandler.post(new Runnable() {
15637            public void run() {
15638                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
15639            }
15640        });
15641    }
15642
15643    /**
15644     * Called by MountService when the initial ASECs to scan are available.
15645     * Should block until all the ASEC containers are finished being scanned.
15646     */
15647    public void scanAvailableAsecs() {
15648        updateExternalMediaStatusInner(true, false, false);
15649        if (mShouldRestoreconData) {
15650            SELinuxMMAC.setRestoreconDone();
15651            mShouldRestoreconData = false;
15652        }
15653    }
15654
15655    /*
15656     * Collect information of applications on external media, map them against
15657     * existing containers and update information based on current mount status.
15658     * Please note that we always have to report status if reportStatus has been
15659     * set to true especially when unloading packages.
15660     */
15661    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
15662            boolean externalStorage) {
15663        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
15664        int[] uidArr = EmptyArray.INT;
15665
15666        final String[] list = PackageHelper.getSecureContainerList();
15667        if (ArrayUtils.isEmpty(list)) {
15668            Log.i(TAG, "No secure containers found");
15669        } else {
15670            // Process list of secure containers and categorize them
15671            // as active or stale based on their package internal state.
15672
15673            // reader
15674            synchronized (mPackages) {
15675                for (String cid : list) {
15676                    // Leave stages untouched for now; installer service owns them
15677                    if (PackageInstallerService.isStageName(cid)) continue;
15678
15679                    if (DEBUG_SD_INSTALL)
15680                        Log.i(TAG, "Processing container " + cid);
15681                    String pkgName = getAsecPackageName(cid);
15682                    if (pkgName == null) {
15683                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
15684                        continue;
15685                    }
15686                    if (DEBUG_SD_INSTALL)
15687                        Log.i(TAG, "Looking for pkg : " + pkgName);
15688
15689                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
15690                    if (ps == null) {
15691                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
15692                        continue;
15693                    }
15694
15695                    /*
15696                     * Skip packages that are not external if we're unmounting
15697                     * external storage.
15698                     */
15699                    if (externalStorage && !isMounted && !isExternal(ps)) {
15700                        continue;
15701                    }
15702
15703                    final AsecInstallArgs args = new AsecInstallArgs(cid,
15704                            getAppDexInstructionSets(ps), ps.isForwardLocked());
15705                    // The package status is changed only if the code path
15706                    // matches between settings and the container id.
15707                    if (ps.codePathString != null
15708                            && ps.codePathString.startsWith(args.getCodePath())) {
15709                        if (DEBUG_SD_INSTALL) {
15710                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
15711                                    + " at code path: " + ps.codePathString);
15712                        }
15713
15714                        // We do have a valid package installed on sdcard
15715                        processCids.put(args, ps.codePathString);
15716                        final int uid = ps.appId;
15717                        if (uid != -1) {
15718                            uidArr = ArrayUtils.appendInt(uidArr, uid);
15719                        }
15720                    } else {
15721                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
15722                                + ps.codePathString);
15723                    }
15724                }
15725            }
15726
15727            Arrays.sort(uidArr);
15728        }
15729
15730        // Process packages with valid entries.
15731        if (isMounted) {
15732            if (DEBUG_SD_INSTALL)
15733                Log.i(TAG, "Loading packages");
15734            loadMediaPackages(processCids, uidArr);
15735            startCleaningPackages();
15736            mInstallerService.onSecureContainersAvailable();
15737        } else {
15738            if (DEBUG_SD_INSTALL)
15739                Log.i(TAG, "Unloading packages");
15740            unloadMediaPackages(processCids, uidArr, reportStatus);
15741        }
15742    }
15743
15744    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15745            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
15746        final int size = infos.size();
15747        final String[] packageNames = new String[size];
15748        final int[] packageUids = new int[size];
15749        for (int i = 0; i < size; i++) {
15750            final ApplicationInfo info = infos.get(i);
15751            packageNames[i] = info.packageName;
15752            packageUids[i] = info.uid;
15753        }
15754        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
15755                finishedReceiver);
15756    }
15757
15758    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15759            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15760        sendResourcesChangedBroadcast(mediaStatus, replacing,
15761                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
15762    }
15763
15764    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
15765            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
15766        int size = pkgList.length;
15767        if (size > 0) {
15768            // Send broadcasts here
15769            Bundle extras = new Bundle();
15770            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
15771            if (uidArr != null) {
15772                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
15773            }
15774            if (replacing) {
15775                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
15776            }
15777            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
15778                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
15779            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
15780        }
15781    }
15782
15783   /*
15784     * Look at potentially valid container ids from processCids If package
15785     * information doesn't match the one on record or package scanning fails,
15786     * the cid is added to list of removeCids. We currently don't delete stale
15787     * containers.
15788     */
15789    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
15790        ArrayList<String> pkgList = new ArrayList<String>();
15791        Set<AsecInstallArgs> keys = processCids.keySet();
15792
15793        for (AsecInstallArgs args : keys) {
15794            String codePath = processCids.get(args);
15795            if (DEBUG_SD_INSTALL)
15796                Log.i(TAG, "Loading container : " + args.cid);
15797            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
15798            try {
15799                // Make sure there are no container errors first.
15800                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
15801                    Slog.e(TAG, "Failed to mount cid : " + args.cid
15802                            + " when installing from sdcard");
15803                    continue;
15804                }
15805                // Check code path here.
15806                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
15807                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
15808                            + " does not match one in settings " + codePath);
15809                    continue;
15810                }
15811                // Parse package
15812                int parseFlags = mDefParseFlags;
15813                if (args.isExternalAsec()) {
15814                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
15815                }
15816                if (args.isFwdLocked()) {
15817                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
15818                }
15819
15820                synchronized (mInstallLock) {
15821                    PackageParser.Package pkg = null;
15822                    try {
15823                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0,
15824                                UserHandle.SYSTEM);
15825                    } catch (PackageManagerException e) {
15826                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
15827                    }
15828                    // Scan the package
15829                    if (pkg != null) {
15830                        /*
15831                         * TODO why is the lock being held? doPostInstall is
15832                         * called in other places without the lock. This needs
15833                         * to be straightened out.
15834                         */
15835                        // writer
15836                        synchronized (mPackages) {
15837                            retCode = PackageManager.INSTALL_SUCCEEDED;
15838                            pkgList.add(pkg.packageName);
15839                            // Post process args
15840                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
15841                                    pkg.applicationInfo.uid);
15842                        }
15843                    } else {
15844                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
15845                    }
15846                }
15847
15848            } finally {
15849                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
15850                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
15851                }
15852            }
15853        }
15854        // writer
15855        synchronized (mPackages) {
15856            // If the platform SDK has changed since the last time we booted,
15857            // we need to re-grant app permission to catch any new ones that
15858            // appear. This is really a hack, and means that apps can in some
15859            // cases get permissions that the user didn't initially explicitly
15860            // allow... it would be nice to have some better way to handle
15861            // this situation.
15862            final VersionInfo ver = mSettings.getExternalVersion();
15863
15864            int updateFlags = UPDATE_PERMISSIONS_ALL;
15865            if (ver.sdkVersion != mSdkVersion) {
15866                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
15867                        + mSdkVersion + "; regranting permissions for external");
15868                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
15869            }
15870            updatePermissionsLPw(null, null, updateFlags);
15871
15872            // Yay, everything is now upgraded
15873            ver.forceCurrent();
15874
15875            // can downgrade to reader
15876            // Persist settings
15877            mSettings.writeLPr();
15878        }
15879        // Send a broadcast to let everyone know we are done processing
15880        if (pkgList.size() > 0) {
15881            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
15882        }
15883    }
15884
15885   /*
15886     * Utility method to unload a list of specified containers
15887     */
15888    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
15889        // Just unmount all valid containers.
15890        for (AsecInstallArgs arg : cidArgs) {
15891            synchronized (mInstallLock) {
15892                arg.doPostDeleteLI(false);
15893           }
15894       }
15895   }
15896
15897    /*
15898     * Unload packages mounted on external media. This involves deleting package
15899     * data from internal structures, sending broadcasts about diabled packages,
15900     * gc'ing to free up references, unmounting all secure containers
15901     * corresponding to packages on external media, and posting a
15902     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
15903     * that we always have to post this message if status has been requested no
15904     * matter what.
15905     */
15906    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
15907            final boolean reportStatus) {
15908        if (DEBUG_SD_INSTALL)
15909            Log.i(TAG, "unloading media packages");
15910        ArrayList<String> pkgList = new ArrayList<String>();
15911        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
15912        final Set<AsecInstallArgs> keys = processCids.keySet();
15913        for (AsecInstallArgs args : keys) {
15914            String pkgName = args.getPackageName();
15915            if (DEBUG_SD_INSTALL)
15916                Log.i(TAG, "Trying to unload pkg : " + pkgName);
15917            // Delete package internally
15918            PackageRemovedInfo outInfo = new PackageRemovedInfo();
15919            synchronized (mInstallLock) {
15920                boolean res = deletePackageLI(pkgName, null, false, null, null,
15921                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
15922                if (res) {
15923                    pkgList.add(pkgName);
15924                } else {
15925                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
15926                    failedList.add(args);
15927                }
15928            }
15929        }
15930
15931        // reader
15932        synchronized (mPackages) {
15933            // We didn't update the settings after removing each package;
15934            // write them now for all packages.
15935            mSettings.writeLPr();
15936        }
15937
15938        // We have to absolutely send UPDATED_MEDIA_STATUS only
15939        // after confirming that all the receivers processed the ordered
15940        // broadcast when packages get disabled, force a gc to clean things up.
15941        // and unload all the containers.
15942        if (pkgList.size() > 0) {
15943            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
15944                    new IIntentReceiver.Stub() {
15945                public void performReceive(Intent intent, int resultCode, String data,
15946                        Bundle extras, boolean ordered, boolean sticky,
15947                        int sendingUser) throws RemoteException {
15948                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
15949                            reportStatus ? 1 : 0, 1, keys);
15950                    mHandler.sendMessage(msg);
15951                }
15952            });
15953        } else {
15954            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
15955                    keys);
15956            mHandler.sendMessage(msg);
15957        }
15958    }
15959
15960    private void loadPrivatePackages(final VolumeInfo vol) {
15961        mHandler.post(new Runnable() {
15962            @Override
15963            public void run() {
15964                loadPrivatePackagesInner(vol);
15965            }
15966        });
15967    }
15968
15969    private void loadPrivatePackagesInner(VolumeInfo vol) {
15970        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
15971        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
15972
15973        final VersionInfo ver;
15974        final List<PackageSetting> packages;
15975        synchronized (mPackages) {
15976            ver = mSettings.findOrCreateVersion(vol.fsUuid);
15977            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
15978        }
15979
15980        for (PackageSetting ps : packages) {
15981            synchronized (mInstallLock) {
15982                final PackageParser.Package pkg;
15983                try {
15984                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0,
15985                            UserHandle.SYSTEM);
15986                    loaded.add(pkg.applicationInfo);
15987                } catch (PackageManagerException e) {
15988                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
15989                }
15990
15991                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
15992                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
15993                }
15994            }
15995        }
15996
15997        synchronized (mPackages) {
15998            int updateFlags = UPDATE_PERMISSIONS_ALL;
15999            if (ver.sdkVersion != mSdkVersion) {
16000                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16001                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16002                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16003            }
16004            updatePermissionsLPw(null, null, updateFlags);
16005
16006            // Yay, everything is now upgraded
16007            ver.forceCurrent();
16008
16009            mSettings.writeLPr();
16010        }
16011
16012        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16013        sendResourcesChangedBroadcast(true, false, loaded, null);
16014    }
16015
16016    private void unloadPrivatePackages(final VolumeInfo vol) {
16017        mHandler.post(new Runnable() {
16018            @Override
16019            public void run() {
16020                unloadPrivatePackagesInner(vol);
16021            }
16022        });
16023    }
16024
16025    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16026        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16027        synchronized (mInstallLock) {
16028        synchronized (mPackages) {
16029            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16030            for (PackageSetting ps : packages) {
16031                if (ps.pkg == null) continue;
16032
16033                final ApplicationInfo info = ps.pkg.applicationInfo;
16034                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16035                if (deletePackageLI(ps.name, null, false, null, null,
16036                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16037                    unloaded.add(info);
16038                } else {
16039                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16040                }
16041            }
16042
16043            mSettings.writeLPr();
16044        }
16045        }
16046
16047        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16048        sendResourcesChangedBroadcast(false, false, unloaded, null);
16049    }
16050
16051    /**
16052     * Examine all users present on given mounted volume, and destroy data
16053     * belonging to users that are no longer valid, or whose user ID has been
16054     * recycled.
16055     */
16056    private void reconcileUsers(String volumeUuid) {
16057        final File[] files = FileUtils
16058                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16059        for (File file : files) {
16060            if (!file.isDirectory()) continue;
16061
16062            final int userId;
16063            final UserInfo info;
16064            try {
16065                userId = Integer.parseInt(file.getName());
16066                info = sUserManager.getUserInfo(userId);
16067            } catch (NumberFormatException e) {
16068                Slog.w(TAG, "Invalid user directory " + file);
16069                continue;
16070            }
16071
16072            boolean destroyUser = false;
16073            if (info == null) {
16074                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16075                        + " because no matching user was found");
16076                destroyUser = true;
16077            } else {
16078                try {
16079                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16080                } catch (IOException e) {
16081                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16082                            + " because we failed to enforce serial number: " + e);
16083                    destroyUser = true;
16084                }
16085            }
16086
16087            if (destroyUser) {
16088                synchronized (mInstallLock) {
16089                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16090                }
16091            }
16092        }
16093
16094        final UserManager um = mContext.getSystemService(UserManager.class);
16095        for (UserInfo user : um.getUsers()) {
16096            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16097            if (userDir.exists()) continue;
16098
16099            try {
16100                UserManagerService.prepareUserDirectory(mContext, volumeUuid, user.id);
16101                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16102            } catch (IOException e) {
16103                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16104            }
16105        }
16106    }
16107
16108    /**
16109     * Examine all apps present on given mounted volume, and destroy apps that
16110     * aren't expected, either due to uninstallation or reinstallation on
16111     * another volume.
16112     */
16113    private void reconcileApps(String volumeUuid) {
16114        final File[] files = FileUtils
16115                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16116        for (File file : files) {
16117            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16118                    && !PackageInstallerService.isStageName(file.getName());
16119            if (!isPackage) {
16120                // Ignore entries which are not packages
16121                continue;
16122            }
16123
16124            boolean destroyApp = false;
16125            String packageName = null;
16126            try {
16127                final PackageLite pkg = PackageParser.parsePackageLite(file,
16128                        PackageParser.PARSE_MUST_BE_APK);
16129                packageName = pkg.packageName;
16130
16131                synchronized (mPackages) {
16132                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16133                    if (ps == null) {
16134                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16135                                + volumeUuid + " because we found no install record");
16136                        destroyApp = true;
16137                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16138                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16139                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16140                        destroyApp = true;
16141                    }
16142                }
16143
16144            } catch (PackageParserException e) {
16145                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16146                destroyApp = true;
16147            }
16148
16149            if (destroyApp) {
16150                synchronized (mInstallLock) {
16151                    if (packageName != null) {
16152                        removeDataDirsLI(volumeUuid, packageName);
16153                    }
16154                    if (file.isDirectory()) {
16155                        mInstaller.rmPackageDir(file.getAbsolutePath());
16156                    } else {
16157                        file.delete();
16158                    }
16159                }
16160            }
16161        }
16162    }
16163
16164    private void unfreezePackage(String packageName) {
16165        synchronized (mPackages) {
16166            final PackageSetting ps = mSettings.mPackages.get(packageName);
16167            if (ps != null) {
16168                ps.frozen = false;
16169            }
16170        }
16171    }
16172
16173    @Override
16174    public int movePackage(final String packageName, final String volumeUuid) {
16175        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16176
16177        final int moveId = mNextMoveId.getAndIncrement();
16178        try {
16179            movePackageInternal(packageName, volumeUuid, moveId);
16180        } catch (PackageManagerException e) {
16181            Slog.w(TAG, "Failed to move " + packageName, e);
16182            mMoveCallbacks.notifyStatusChanged(moveId,
16183                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16184        }
16185        return moveId;
16186    }
16187
16188    private void movePackageInternal(final String packageName, final String volumeUuid,
16189            final int moveId) throws PackageManagerException {
16190        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16191        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16192        final PackageManager pm = mContext.getPackageManager();
16193
16194        final boolean currentAsec;
16195        final String currentVolumeUuid;
16196        final File codeFile;
16197        final String installerPackageName;
16198        final String packageAbiOverride;
16199        final int appId;
16200        final String seinfo;
16201        final String label;
16202
16203        // reader
16204        synchronized (mPackages) {
16205            final PackageParser.Package pkg = mPackages.get(packageName);
16206            final PackageSetting ps = mSettings.mPackages.get(packageName);
16207            if (pkg == null || ps == null) {
16208                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16209            }
16210
16211            if (pkg.applicationInfo.isSystemApp()) {
16212                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16213                        "Cannot move system application");
16214            }
16215
16216            if (pkg.applicationInfo.isExternalAsec()) {
16217                currentAsec = true;
16218                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16219            } else if (pkg.applicationInfo.isForwardLocked()) {
16220                currentAsec = true;
16221                currentVolumeUuid = "forward_locked";
16222            } else {
16223                currentAsec = false;
16224                currentVolumeUuid = ps.volumeUuid;
16225
16226                final File probe = new File(pkg.codePath);
16227                final File probeOat = new File(probe, "oat");
16228                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16229                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16230                            "Move only supported for modern cluster style installs");
16231                }
16232            }
16233
16234            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16235                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16236                        "Package already moved to " + volumeUuid);
16237            }
16238
16239            if (ps.frozen) {
16240                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16241                        "Failed to move already frozen package");
16242            }
16243            ps.frozen = true;
16244
16245            codeFile = new File(pkg.codePath);
16246            installerPackageName = ps.installerPackageName;
16247            packageAbiOverride = ps.cpuAbiOverrideString;
16248            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16249            seinfo = pkg.applicationInfo.seinfo;
16250            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16251        }
16252
16253        // Now that we're guarded by frozen state, kill app during move
16254        final long token = Binder.clearCallingIdentity();
16255        try {
16256            killApplication(packageName, appId, "move pkg");
16257        } finally {
16258            Binder.restoreCallingIdentity(token);
16259        }
16260
16261        final Bundle extras = new Bundle();
16262        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16263        extras.putString(Intent.EXTRA_TITLE, label);
16264        mMoveCallbacks.notifyCreated(moveId, extras);
16265
16266        int installFlags;
16267        final boolean moveCompleteApp;
16268        final File measurePath;
16269
16270        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16271            installFlags = INSTALL_INTERNAL;
16272            moveCompleteApp = !currentAsec;
16273            measurePath = Environment.getDataAppDirectory(volumeUuid);
16274        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16275            installFlags = INSTALL_EXTERNAL;
16276            moveCompleteApp = false;
16277            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16278        } else {
16279            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16280            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16281                    || !volume.isMountedWritable()) {
16282                unfreezePackage(packageName);
16283                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16284                        "Move location not mounted private volume");
16285            }
16286
16287            Preconditions.checkState(!currentAsec);
16288
16289            installFlags = INSTALL_INTERNAL;
16290            moveCompleteApp = true;
16291            measurePath = Environment.getDataAppDirectory(volumeUuid);
16292        }
16293
16294        final PackageStats stats = new PackageStats(null, -1);
16295        synchronized (mInstaller) {
16296            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16297                unfreezePackage(packageName);
16298                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16299                        "Failed to measure package size");
16300            }
16301        }
16302
16303        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16304                + stats.dataSize);
16305
16306        final long startFreeBytes = measurePath.getFreeSpace();
16307        final long sizeBytes;
16308        if (moveCompleteApp) {
16309            sizeBytes = stats.codeSize + stats.dataSize;
16310        } else {
16311            sizeBytes = stats.codeSize;
16312        }
16313
16314        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16315            unfreezePackage(packageName);
16316            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16317                    "Not enough free space to move");
16318        }
16319
16320        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16321
16322        final CountDownLatch installedLatch = new CountDownLatch(1);
16323        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16324            @Override
16325            public void onUserActionRequired(Intent intent) throws RemoteException {
16326                throw new IllegalStateException();
16327            }
16328
16329            @Override
16330            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16331                    Bundle extras) throws RemoteException {
16332                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16333                        + PackageManager.installStatusToString(returnCode, msg));
16334
16335                installedLatch.countDown();
16336
16337                // Regardless of success or failure of the move operation,
16338                // always unfreeze the package
16339                unfreezePackage(packageName);
16340
16341                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16342                switch (status) {
16343                    case PackageInstaller.STATUS_SUCCESS:
16344                        mMoveCallbacks.notifyStatusChanged(moveId,
16345                                PackageManager.MOVE_SUCCEEDED);
16346                        break;
16347                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16348                        mMoveCallbacks.notifyStatusChanged(moveId,
16349                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16350                        break;
16351                    default:
16352                        mMoveCallbacks.notifyStatusChanged(moveId,
16353                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16354                        break;
16355                }
16356            }
16357        };
16358
16359        final MoveInfo move;
16360        if (moveCompleteApp) {
16361            // Kick off a thread to report progress estimates
16362            new Thread() {
16363                @Override
16364                public void run() {
16365                    while (true) {
16366                        try {
16367                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16368                                break;
16369                            }
16370                        } catch (InterruptedException ignored) {
16371                        }
16372
16373                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16374                        final int progress = 10 + (int) MathUtils.constrain(
16375                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16376                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16377                    }
16378                }
16379            }.start();
16380
16381            final String dataAppName = codeFile.getName();
16382            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16383                    dataAppName, appId, seinfo);
16384        } else {
16385            move = null;
16386        }
16387
16388        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16389
16390        final Message msg = mHandler.obtainMessage(INIT_COPY);
16391        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16392        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16393                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16394        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16395        msg.obj = params;
16396
16397        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16398                System.identityHashCode(msg.obj));
16399        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16400                System.identityHashCode(msg.obj));
16401
16402        mHandler.sendMessage(msg);
16403    }
16404
16405    @Override
16406    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16407        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16408
16409        final int realMoveId = mNextMoveId.getAndIncrement();
16410        final Bundle extras = new Bundle();
16411        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16412        mMoveCallbacks.notifyCreated(realMoveId, extras);
16413
16414        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16415            @Override
16416            public void onCreated(int moveId, Bundle extras) {
16417                // Ignored
16418            }
16419
16420            @Override
16421            public void onStatusChanged(int moveId, int status, long estMillis) {
16422                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16423            }
16424        };
16425
16426        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16427        storage.setPrimaryStorageUuid(volumeUuid, callback);
16428        return realMoveId;
16429    }
16430
16431    @Override
16432    public int getMoveStatus(int moveId) {
16433        mContext.enforceCallingOrSelfPermission(
16434                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16435        return mMoveCallbacks.mLastStatus.get(moveId);
16436    }
16437
16438    @Override
16439    public void registerMoveCallback(IPackageMoveObserver callback) {
16440        mContext.enforceCallingOrSelfPermission(
16441                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16442        mMoveCallbacks.register(callback);
16443    }
16444
16445    @Override
16446    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16447        mContext.enforceCallingOrSelfPermission(
16448                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16449        mMoveCallbacks.unregister(callback);
16450    }
16451
16452    @Override
16453    public boolean setInstallLocation(int loc) {
16454        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16455                null);
16456        if (getInstallLocation() == loc) {
16457            return true;
16458        }
16459        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16460                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16461            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16462                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16463            return true;
16464        }
16465        return false;
16466   }
16467
16468    @Override
16469    public int getInstallLocation() {
16470        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16471                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16472                PackageHelper.APP_INSTALL_AUTO);
16473    }
16474
16475    /** Called by UserManagerService */
16476    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
16477        mDirtyUsers.remove(userHandle);
16478        mSettings.removeUserLPw(userHandle);
16479        mPendingBroadcasts.remove(userHandle);
16480        if (mInstaller != null) {
16481            // Technically, we shouldn't be doing this with the package lock
16482            // held.  However, this is very rare, and there is already so much
16483            // other disk I/O going on, that we'll let it slide for now.
16484            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16485            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16486                final String volumeUuid = vol.getFsUuid();
16487                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16488                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16489            }
16490        }
16491        mUserNeedsBadging.delete(userHandle);
16492        removeUnusedPackagesLILPw(userManager, userHandle);
16493    }
16494
16495    /**
16496     * We're removing userHandle and would like to remove any downloaded packages
16497     * that are no longer in use by any other user.
16498     * @param userHandle the user being removed
16499     */
16500    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16501        final boolean DEBUG_CLEAN_APKS = false;
16502        int [] users = userManager.getUserIdsLPr();
16503        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16504        while (psit.hasNext()) {
16505            PackageSetting ps = psit.next();
16506            if (ps.pkg == null) {
16507                continue;
16508            }
16509            final String packageName = ps.pkg.packageName;
16510            // Skip over if system app
16511            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16512                continue;
16513            }
16514            if (DEBUG_CLEAN_APKS) {
16515                Slog.i(TAG, "Checking package " + packageName);
16516            }
16517            boolean keep = false;
16518            for (int i = 0; i < users.length; i++) {
16519                if (users[i] != userHandle && ps.getInstalled(users[i])) {
16520                    keep = true;
16521                    if (DEBUG_CLEAN_APKS) {
16522                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
16523                                + users[i]);
16524                    }
16525                    break;
16526                }
16527            }
16528            if (!keep) {
16529                if (DEBUG_CLEAN_APKS) {
16530                    Slog.i(TAG, "  Removing package " + packageName);
16531                }
16532                mHandler.post(new Runnable() {
16533                    public void run() {
16534                        deletePackageX(packageName, userHandle, 0);
16535                    } //end run
16536                });
16537            }
16538        }
16539    }
16540
16541    /** Called by UserManagerService */
16542    void createNewUserLILPw(int userHandle) {
16543        if (mInstaller != null) {
16544            mInstaller.createUserConfig(userHandle);
16545            mSettings.createNewUserLILPw(this, mInstaller, userHandle);
16546            applyFactoryDefaultBrowserLPw(userHandle);
16547            primeDomainVerificationsLPw(userHandle);
16548        }
16549    }
16550
16551    void newUserCreated(final int userHandle) {
16552        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
16553    }
16554
16555    @Override
16556    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
16557        mContext.enforceCallingOrSelfPermission(
16558                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
16559                "Only package verification agents can read the verifier device identity");
16560
16561        synchronized (mPackages) {
16562            return mSettings.getVerifierDeviceIdentityLPw();
16563        }
16564    }
16565
16566    @Override
16567    public void setPermissionEnforced(String permission, boolean enforced) {
16568        // TODO: Now that we no longer change GID for storage, this should to away.
16569        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
16570                "setPermissionEnforced");
16571        if (READ_EXTERNAL_STORAGE.equals(permission)) {
16572            synchronized (mPackages) {
16573                if (mSettings.mReadExternalStorageEnforced == null
16574                        || mSettings.mReadExternalStorageEnforced != enforced) {
16575                    mSettings.mReadExternalStorageEnforced = enforced;
16576                    mSettings.writeLPr();
16577                }
16578            }
16579            // kill any non-foreground processes so we restart them and
16580            // grant/revoke the GID.
16581            final IActivityManager am = ActivityManagerNative.getDefault();
16582            if (am != null) {
16583                final long token = Binder.clearCallingIdentity();
16584                try {
16585                    am.killProcessesBelowForeground("setPermissionEnforcement");
16586                } catch (RemoteException e) {
16587                } finally {
16588                    Binder.restoreCallingIdentity(token);
16589                }
16590            }
16591        } else {
16592            throw new IllegalArgumentException("No selective enforcement for " + permission);
16593        }
16594    }
16595
16596    @Override
16597    @Deprecated
16598    public boolean isPermissionEnforced(String permission) {
16599        return true;
16600    }
16601
16602    @Override
16603    public boolean isStorageLow() {
16604        final long token = Binder.clearCallingIdentity();
16605        try {
16606            final DeviceStorageMonitorInternal
16607                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
16608            if (dsm != null) {
16609                return dsm.isMemoryLow();
16610            } else {
16611                return false;
16612            }
16613        } finally {
16614            Binder.restoreCallingIdentity(token);
16615        }
16616    }
16617
16618    @Override
16619    public IPackageInstaller getPackageInstaller() {
16620        return mInstallerService;
16621    }
16622
16623    private boolean userNeedsBadging(int userId) {
16624        int index = mUserNeedsBadging.indexOfKey(userId);
16625        if (index < 0) {
16626            final UserInfo userInfo;
16627            final long token = Binder.clearCallingIdentity();
16628            try {
16629                userInfo = sUserManager.getUserInfo(userId);
16630            } finally {
16631                Binder.restoreCallingIdentity(token);
16632            }
16633            final boolean b;
16634            if (userInfo != null && userInfo.isManagedProfile()) {
16635                b = true;
16636            } else {
16637                b = false;
16638            }
16639            mUserNeedsBadging.put(userId, b);
16640            return b;
16641        }
16642        return mUserNeedsBadging.valueAt(index);
16643    }
16644
16645    @Override
16646    public KeySet getKeySetByAlias(String packageName, String alias) {
16647        if (packageName == null || alias == null) {
16648            return null;
16649        }
16650        synchronized(mPackages) {
16651            final PackageParser.Package pkg = mPackages.get(packageName);
16652            if (pkg == null) {
16653                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16654                throw new IllegalArgumentException("Unknown package: " + packageName);
16655            }
16656            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16657            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
16658        }
16659    }
16660
16661    @Override
16662    public KeySet getSigningKeySet(String packageName) {
16663        if (packageName == null) {
16664            return null;
16665        }
16666        synchronized(mPackages) {
16667            final PackageParser.Package pkg = mPackages.get(packageName);
16668            if (pkg == null) {
16669                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16670                throw new IllegalArgumentException("Unknown package: " + packageName);
16671            }
16672            if (pkg.applicationInfo.uid != Binder.getCallingUid()
16673                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
16674                throw new SecurityException("May not access signing KeySet of other apps.");
16675            }
16676            KeySetManagerService ksms = mSettings.mKeySetManagerService;
16677            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
16678        }
16679    }
16680
16681    @Override
16682    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
16683        if (packageName == null || ks == null) {
16684            return false;
16685        }
16686        synchronized(mPackages) {
16687            final PackageParser.Package pkg = mPackages.get(packageName);
16688            if (pkg == null) {
16689                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16690                throw new IllegalArgumentException("Unknown package: " + packageName);
16691            }
16692            IBinder ksh = ks.getToken();
16693            if (ksh instanceof KeySetHandle) {
16694                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16695                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
16696            }
16697            return false;
16698        }
16699    }
16700
16701    @Override
16702    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
16703        if (packageName == null || ks == null) {
16704            return false;
16705        }
16706        synchronized(mPackages) {
16707            final PackageParser.Package pkg = mPackages.get(packageName);
16708            if (pkg == null) {
16709                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
16710                throw new IllegalArgumentException("Unknown package: " + packageName);
16711            }
16712            IBinder ksh = ks.getToken();
16713            if (ksh instanceof KeySetHandle) {
16714                KeySetManagerService ksms = mSettings.mKeySetManagerService;
16715                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
16716            }
16717            return false;
16718        }
16719    }
16720
16721    public void getUsageStatsIfNoPackageUsageInfo() {
16722        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
16723            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
16724            if (usm == null) {
16725                throw new IllegalStateException("UsageStatsManager must be initialized");
16726            }
16727            long now = System.currentTimeMillis();
16728            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
16729            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
16730                String packageName = entry.getKey();
16731                PackageParser.Package pkg = mPackages.get(packageName);
16732                if (pkg == null) {
16733                    continue;
16734                }
16735                UsageStats usage = entry.getValue();
16736                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
16737                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
16738            }
16739        }
16740    }
16741
16742    /**
16743     * Check and throw if the given before/after packages would be considered a
16744     * downgrade.
16745     */
16746    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
16747            throws PackageManagerException {
16748        if (after.versionCode < before.mVersionCode) {
16749            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16750                    "Update version code " + after.versionCode + " is older than current "
16751                    + before.mVersionCode);
16752        } else if (after.versionCode == before.mVersionCode) {
16753            if (after.baseRevisionCode < before.baseRevisionCode) {
16754                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16755                        "Update base revision code " + after.baseRevisionCode
16756                        + " is older than current " + before.baseRevisionCode);
16757            }
16758
16759            if (!ArrayUtils.isEmpty(after.splitNames)) {
16760                for (int i = 0; i < after.splitNames.length; i++) {
16761                    final String splitName = after.splitNames[i];
16762                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
16763                    if (j != -1) {
16764                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
16765                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
16766                                    "Update split " + splitName + " revision code "
16767                                    + after.splitRevisionCodes[i] + " is older than current "
16768                                    + before.splitRevisionCodes[j]);
16769                        }
16770                    }
16771                }
16772            }
16773        }
16774    }
16775
16776    private static class MoveCallbacks extends Handler {
16777        private static final int MSG_CREATED = 1;
16778        private static final int MSG_STATUS_CHANGED = 2;
16779
16780        private final RemoteCallbackList<IPackageMoveObserver>
16781                mCallbacks = new RemoteCallbackList<>();
16782
16783        private final SparseIntArray mLastStatus = new SparseIntArray();
16784
16785        public MoveCallbacks(Looper looper) {
16786            super(looper);
16787        }
16788
16789        public void register(IPackageMoveObserver callback) {
16790            mCallbacks.register(callback);
16791        }
16792
16793        public void unregister(IPackageMoveObserver callback) {
16794            mCallbacks.unregister(callback);
16795        }
16796
16797        @Override
16798        public void handleMessage(Message msg) {
16799            final SomeArgs args = (SomeArgs) msg.obj;
16800            final int n = mCallbacks.beginBroadcast();
16801            for (int i = 0; i < n; i++) {
16802                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
16803                try {
16804                    invokeCallback(callback, msg.what, args);
16805                } catch (RemoteException ignored) {
16806                }
16807            }
16808            mCallbacks.finishBroadcast();
16809            args.recycle();
16810        }
16811
16812        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
16813                throws RemoteException {
16814            switch (what) {
16815                case MSG_CREATED: {
16816                    callback.onCreated(args.argi1, (Bundle) args.arg2);
16817                    break;
16818                }
16819                case MSG_STATUS_CHANGED: {
16820                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
16821                    break;
16822                }
16823            }
16824        }
16825
16826        private void notifyCreated(int moveId, Bundle extras) {
16827            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
16828
16829            final SomeArgs args = SomeArgs.obtain();
16830            args.argi1 = moveId;
16831            args.arg2 = extras;
16832            obtainMessage(MSG_CREATED, args).sendToTarget();
16833        }
16834
16835        private void notifyStatusChanged(int moveId, int status) {
16836            notifyStatusChanged(moveId, status, -1);
16837        }
16838
16839        private void notifyStatusChanged(int moveId, int status, long estMillis) {
16840            Slog.v(TAG, "Move " + moveId + " status " + status);
16841
16842            final SomeArgs args = SomeArgs.obtain();
16843            args.argi1 = moveId;
16844            args.argi2 = status;
16845            args.arg3 = estMillis;
16846            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
16847
16848            synchronized (mLastStatus) {
16849                mLastStatus.put(moveId, status);
16850            }
16851        }
16852    }
16853
16854    private final class OnPermissionChangeListeners extends Handler {
16855        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
16856
16857        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
16858                new RemoteCallbackList<>();
16859
16860        public OnPermissionChangeListeners(Looper looper) {
16861            super(looper);
16862        }
16863
16864        @Override
16865        public void handleMessage(Message msg) {
16866            switch (msg.what) {
16867                case MSG_ON_PERMISSIONS_CHANGED: {
16868                    final int uid = msg.arg1;
16869                    handleOnPermissionsChanged(uid);
16870                } break;
16871            }
16872        }
16873
16874        public void addListenerLocked(IOnPermissionsChangeListener listener) {
16875            mPermissionListeners.register(listener);
16876
16877        }
16878
16879        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
16880            mPermissionListeners.unregister(listener);
16881        }
16882
16883        public void onPermissionsChanged(int uid) {
16884            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
16885                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
16886            }
16887        }
16888
16889        private void handleOnPermissionsChanged(int uid) {
16890            final int count = mPermissionListeners.beginBroadcast();
16891            try {
16892                for (int i = 0; i < count; i++) {
16893                    IOnPermissionsChangeListener callback = mPermissionListeners
16894                            .getBroadcastItem(i);
16895                    try {
16896                        callback.onPermissionsChanged(uid);
16897                    } catch (RemoteException e) {
16898                        Log.e(TAG, "Permission listener is dead", e);
16899                    }
16900                }
16901            } finally {
16902                mPermissionListeners.finishBroadcast();
16903            }
16904        }
16905    }
16906
16907    private class PackageManagerInternalImpl extends PackageManagerInternal {
16908        @Override
16909        public void setLocationPackagesProvider(PackagesProvider provider) {
16910            synchronized (mPackages) {
16911                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
16912            }
16913        }
16914
16915        @Override
16916        public void setImePackagesProvider(PackagesProvider provider) {
16917            synchronized (mPackages) {
16918                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
16919            }
16920        }
16921
16922        @Override
16923        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
16924            synchronized (mPackages) {
16925                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
16926            }
16927        }
16928
16929        @Override
16930        public void setSmsAppPackagesProvider(PackagesProvider provider) {
16931            synchronized (mPackages) {
16932                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
16933            }
16934        }
16935
16936        @Override
16937        public void setDialerAppPackagesProvider(PackagesProvider provider) {
16938            synchronized (mPackages) {
16939                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
16940            }
16941        }
16942
16943        @Override
16944        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
16945            synchronized (mPackages) {
16946                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
16947            }
16948        }
16949
16950        @Override
16951        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
16952            synchronized (mPackages) {
16953                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
16954            }
16955        }
16956
16957        @Override
16958        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
16959            synchronized (mPackages) {
16960                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
16961                        packageName, userId);
16962            }
16963        }
16964
16965        @Override
16966        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
16967            synchronized (mPackages) {
16968                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
16969                        packageName, userId);
16970            }
16971        }
16972        @Override
16973        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
16974            synchronized (mPackages) {
16975                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
16976                        packageName, userId);
16977            }
16978        }
16979    }
16980
16981    @Override
16982    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
16983        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
16984        synchronized (mPackages) {
16985            final long identity = Binder.clearCallingIdentity();
16986            try {
16987                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
16988                        packageNames, userId);
16989            } finally {
16990                Binder.restoreCallingIdentity(identity);
16991            }
16992        }
16993    }
16994
16995    private static void enforceSystemOrPhoneCaller(String tag) {
16996        int callingUid = Binder.getCallingUid();
16997        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
16998            throw new SecurityException(
16999                    "Cannot call " + tag + " from UID " + callingUid);
17000        }
17001    }
17002}
17003