PackageManagerService.java revision f15150be6538374ebcc15172a59fb551a60c0d13
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_REVIEW_REQUIRED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
34import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
35import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
36import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
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_EPHEMERAL_INVALID;
40import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
41import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
44import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
45import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
46import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
47import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
54import static android.content.pm.PackageManager.INSTALL_INTERNAL;
55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
61import static android.content.pm.PackageManager.MATCH_ALL;
62import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
63import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
64import static android.content.pm.PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
65import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
66import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
67import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
68import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
69import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
70import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
71import static android.content.pm.PackageManager.PERMISSION_DENIED;
72import static android.content.pm.PackageManager.PERMISSION_GRANTED;
73import static android.content.pm.PackageParser.isApkFile;
74import static android.os.Process.PACKAGE_INFO_GID;
75import static android.os.Process.SYSTEM_UID;
76import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
77import static android.system.OsConstants.O_CREAT;
78import static android.system.OsConstants.O_RDWR;
79
80import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
81import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
82import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
83import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
84import static com.android.internal.util.ArrayUtils.appendInt;
85import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
86import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
87import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
88import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
89import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
90import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
91import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
92import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
93import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
94
95import android.Manifest;
96import android.annotation.NonNull;
97import android.annotation.Nullable;
98import android.app.ActivityManager;
99import android.app.ActivityManagerNative;
100import android.app.AppGlobals;
101import android.app.IActivityManager;
102import android.app.admin.IDevicePolicyManager;
103import android.app.backup.IBackupManager;
104import android.content.BroadcastReceiver;
105import android.content.ComponentName;
106import android.content.Context;
107import android.content.IIntentReceiver;
108import android.content.Intent;
109import android.content.IntentFilter;
110import android.content.IntentSender;
111import android.content.IntentSender.SendIntentException;
112import android.content.ServiceConnection;
113import android.content.pm.ActivityInfo;
114import android.content.pm.ApplicationInfo;
115import android.content.pm.AppsQueryHelper;
116import android.content.pm.ComponentInfo;
117import android.content.pm.EphemeralApplicationInfo;
118import android.content.pm.EphemeralResolveInfo;
119import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
120import android.content.pm.FeatureInfo;
121import android.content.pm.IOnPermissionsChangeListener;
122import android.content.pm.IPackageDataObserver;
123import android.content.pm.IPackageDeleteObserver;
124import android.content.pm.IPackageDeleteObserver2;
125import android.content.pm.IPackageInstallObserver2;
126import android.content.pm.IPackageInstaller;
127import android.content.pm.IPackageManager;
128import android.content.pm.IPackageMoveObserver;
129import android.content.pm.IPackageStatsObserver;
130import android.content.pm.InstrumentationInfo;
131import android.content.pm.IntentFilterVerificationInfo;
132import android.content.pm.KeySet;
133import android.content.pm.PackageCleanItem;
134import android.content.pm.PackageInfo;
135import android.content.pm.PackageInfoLite;
136import android.content.pm.PackageInstaller;
137import android.content.pm.PackageManager;
138import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
139import android.content.pm.PackageManagerInternal;
140import android.content.pm.PackageParser;
141import android.content.pm.PackageParser.ActivityIntentInfo;
142import android.content.pm.PackageParser.PackageLite;
143import android.content.pm.PackageParser.PackageParserException;
144import android.content.pm.PackageStats;
145import android.content.pm.PackageUserState;
146import android.content.pm.ParceledListSlice;
147import android.content.pm.PermissionGroupInfo;
148import android.content.pm.PermissionInfo;
149import android.content.pm.ProviderInfo;
150import android.content.pm.ResolveInfo;
151import android.content.pm.ServiceInfo;
152import android.content.pm.Signature;
153import android.content.pm.UserInfo;
154import android.content.pm.VerificationParams;
155import android.content.pm.VerifierDeviceIdentity;
156import android.content.pm.VerifierInfo;
157import android.content.res.Resources;
158import android.graphics.Bitmap;
159import android.hardware.display.DisplayManager;
160import android.net.Uri;
161import android.os.Binder;
162import android.os.Build;
163import android.os.Bundle;
164import android.os.Debug;
165import android.os.Environment;
166import android.os.Environment.UserEnvironment;
167import android.os.FileUtils;
168import android.os.Handler;
169import android.os.IBinder;
170import android.os.Looper;
171import android.os.Message;
172import android.os.Parcel;
173import android.os.ParcelFileDescriptor;
174import android.os.Process;
175import android.os.RemoteCallbackList;
176import android.os.RemoteException;
177import android.os.ResultReceiver;
178import android.os.SELinux;
179import android.os.ServiceManager;
180import android.os.SystemClock;
181import android.os.SystemProperties;
182import android.os.Trace;
183import android.os.UserHandle;
184import android.os.UserManager;
185import android.os.storage.IMountService;
186import android.os.storage.MountServiceInternal;
187import android.os.storage.StorageEventListener;
188import android.os.storage.StorageManager;
189import android.os.storage.VolumeInfo;
190import android.os.storage.VolumeRecord;
191import android.security.KeyStore;
192import android.security.SystemKeyStore;
193import android.system.ErrnoException;
194import android.system.Os;
195import android.system.StructStat;
196import android.text.TextUtils;
197import android.text.format.DateUtils;
198import android.util.ArrayMap;
199import android.util.ArraySet;
200import android.util.AtomicFile;
201import android.util.DisplayMetrics;
202import android.util.EventLog;
203import android.util.ExceptionUtils;
204import android.util.Log;
205import android.util.LogPrinter;
206import android.util.MathUtils;
207import android.util.PrintStreamPrinter;
208import android.util.Slog;
209import android.util.SparseArray;
210import android.util.SparseBooleanArray;
211import android.util.SparseIntArray;
212import android.util.Xml;
213import android.view.Display;
214
215import com.android.internal.R;
216import com.android.internal.annotations.GuardedBy;
217import com.android.internal.app.IMediaContainerService;
218import com.android.internal.app.ResolverActivity;
219import com.android.internal.content.NativeLibraryHelper;
220import com.android.internal.content.PackageHelper;
221import com.android.internal.os.IParcelFileDescriptorFactory;
222import com.android.internal.os.SomeArgs;
223import com.android.internal.os.Zygote;
224import com.android.internal.util.ArrayUtils;
225import com.android.internal.util.FastPrintWriter;
226import com.android.internal.util.FastXmlSerializer;
227import com.android.internal.util.IndentingPrintWriter;
228import com.android.internal.util.Preconditions;
229import com.android.server.EventLogTags;
230import com.android.server.FgThread;
231import com.android.server.IntentResolver;
232import com.android.server.LocalServices;
233import com.android.server.ServiceThread;
234import com.android.server.SystemConfig;
235import com.android.server.Watchdog;
236import com.android.server.pm.PermissionsState.PermissionState;
237import com.android.server.pm.Settings.DatabaseVersion;
238import com.android.server.pm.Settings.VersionInfo;
239import com.android.server.storage.DeviceStorageMonitorInternal;
240
241import dalvik.system.DexFile;
242import dalvik.system.VMRuntime;
243
244import libcore.io.IoUtils;
245import libcore.util.EmptyArray;
246
247import org.xmlpull.v1.XmlPullParser;
248import org.xmlpull.v1.XmlPullParserException;
249import org.xmlpull.v1.XmlSerializer;
250
251import java.io.BufferedInputStream;
252import java.io.BufferedOutputStream;
253import java.io.BufferedReader;
254import java.io.ByteArrayInputStream;
255import java.io.ByteArrayOutputStream;
256import java.io.File;
257import java.io.FileDescriptor;
258import java.io.FileNotFoundException;
259import java.io.FileOutputStream;
260import java.io.FileReader;
261import java.io.FilenameFilter;
262import java.io.IOException;
263import java.io.InputStream;
264import java.io.PrintWriter;
265import java.nio.charset.StandardCharsets;
266import java.security.MessageDigest;
267import java.security.NoSuchAlgorithmException;
268import java.security.PublicKey;
269import java.security.cert.CertificateEncodingException;
270import java.security.cert.CertificateException;
271import java.text.SimpleDateFormat;
272import java.util.ArrayList;
273import java.util.Arrays;
274import java.util.Collection;
275import java.util.Collections;
276import java.util.Comparator;
277import java.util.Date;
278import java.util.Iterator;
279import java.util.List;
280import java.util.Map;
281import java.util.Objects;
282import java.util.Set;
283import java.util.concurrent.CountDownLatch;
284import java.util.concurrent.TimeUnit;
285import java.util.concurrent.atomic.AtomicBoolean;
286import java.util.concurrent.atomic.AtomicInteger;
287import java.util.concurrent.atomic.AtomicLong;
288
289/**
290 * Keep track of all those .apks everywhere.
291 *
292 * This is very central to the platform's security; please run the unit
293 * tests whenever making modifications here:
294 *
295runtest -c android.content.pm.PackageManagerTests frameworks-core
296 *
297 * {@hide}
298 */
299public class PackageManagerService extends IPackageManager.Stub {
300    static final String TAG = "PackageManager";
301    static final boolean DEBUG_SETTINGS = false;
302    static final boolean DEBUG_PREFERRED = false;
303    static final boolean DEBUG_UPGRADE = false;
304    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
305    private static final boolean DEBUG_BACKUP = false;
306    private static final boolean DEBUG_INSTALL = false;
307    private static final boolean DEBUG_REMOVE = false;
308    private static final boolean DEBUG_BROADCASTS = false;
309    private static final boolean DEBUG_SHOW_INFO = false;
310    private static final boolean DEBUG_PACKAGE_INFO = false;
311    private static final boolean DEBUG_INTENT_MATCHING = false;
312    private static final boolean DEBUG_PACKAGE_SCANNING = false;
313    private static final boolean DEBUG_VERIFY = false;
314    private static final boolean DEBUG_DEXOPT = false;
315    private static final boolean DEBUG_ABI_SELECTION = false;
316    private static final boolean DEBUG_EPHEMERAL = false;
317    private static final boolean DEBUG_TRIAGED_MISSING = false;
318
319    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
320
321    private static final int RADIO_UID = Process.PHONE_UID;
322    private static final int LOG_UID = Process.LOG_UID;
323    private static final int NFC_UID = Process.NFC_UID;
324    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
325    private static final int SHELL_UID = Process.SHELL_UID;
326
327    // Cap the size of permission trees that 3rd party apps can define
328    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
329
330    // Suffix used during package installation when copying/moving
331    // package apks to install directory.
332    private static final String INSTALL_PACKAGE_SUFFIX = "-";
333
334    static final int SCAN_NO_DEX = 1<<1;
335    static final int SCAN_FORCE_DEX = 1<<2;
336    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
337    static final int SCAN_NEW_INSTALL = 1<<4;
338    static final int SCAN_NO_PATHS = 1<<5;
339    static final int SCAN_UPDATE_TIME = 1<<6;
340    static final int SCAN_DEFER_DEX = 1<<7;
341    static final int SCAN_BOOTING = 1<<8;
342    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
343    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
344    static final int SCAN_REPLACING = 1<<11;
345    static final int SCAN_REQUIRE_KNOWN = 1<<12;
346    static final int SCAN_MOVE = 1<<13;
347    static final int SCAN_INITIAL = 1<<14;
348
349    static final int REMOVE_CHATTY = 1<<16;
350
351    private static final int[] EMPTY_INT_ARRAY = new int[0];
352
353    /**
354     * Timeout (in milliseconds) after which the watchdog should declare that
355     * our handler thread is wedged.  The usual default for such things is one
356     * minute but we sometimes do very lengthy I/O operations on this thread,
357     * such as installing multi-gigabyte applications, so ours needs to be longer.
358     */
359    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
360
361    /**
362     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
363     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
364     * settings entry if available, otherwise we use the hardcoded default.  If it's been
365     * more than this long since the last fstrim, we force one during the boot sequence.
366     *
367     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
368     * one gets run at the next available charging+idle time.  This final mandatory
369     * no-fstrim check kicks in only of the other scheduling criteria is never met.
370     */
371    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
372
373    /**
374     * Whether verification is enabled by default.
375     */
376    private static final boolean DEFAULT_VERIFY_ENABLE = true;
377
378    /**
379     * The default maximum time to wait for the verification agent to return in
380     * milliseconds.
381     */
382    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
383
384    /**
385     * The default response for package verification timeout.
386     *
387     * This can be either PackageManager.VERIFICATION_ALLOW or
388     * PackageManager.VERIFICATION_REJECT.
389     */
390    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
391
392    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
393
394    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
395            DEFAULT_CONTAINER_PACKAGE,
396            "com.android.defcontainer.DefaultContainerService");
397
398    private static final String KILL_APP_REASON_GIDS_CHANGED =
399            "permission grant or revoke changed gids";
400
401    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
402            "permissions revoked";
403
404    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
405
406    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
407
408    /** Permission grant: not grant the permission. */
409    private static final int GRANT_DENIED = 1;
410
411    /** Permission grant: grant the permission as an install permission. */
412    private static final int GRANT_INSTALL = 2;
413
414    /** Permission grant: grant the permission as a runtime one. */
415    private static final int GRANT_RUNTIME = 3;
416
417    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
418    private static final int GRANT_UPGRADE = 4;
419
420    /** Canonical intent used to identify what counts as a "web browser" app */
421    private static final Intent sBrowserIntent;
422    static {
423        sBrowserIntent = new Intent();
424        sBrowserIntent.setAction(Intent.ACTION_VIEW);
425        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
426        sBrowserIntent.setData(Uri.parse("http:"));
427    }
428
429    final ServiceThread mHandlerThread;
430
431    final PackageHandler mHandler;
432
433    /**
434     * Messages for {@link #mHandler} that need to wait for system ready before
435     * being dispatched.
436     */
437    private ArrayList<Message> mPostSystemReadyMessages;
438
439    final int mSdkVersion = Build.VERSION.SDK_INT;
440
441    final Context mContext;
442    final boolean mFactoryTest;
443    final boolean mOnlyCore;
444    final DisplayMetrics mMetrics;
445    final int mDefParseFlags;
446    final String[] mSeparateProcesses;
447    final boolean mIsUpgrade;
448
449    /** The location for ASEC container files on internal storage. */
450    final String mAsecInternalPath;
451
452    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
453    // LOCK HELD.  Can be called with mInstallLock held.
454    @GuardedBy("mInstallLock")
455    final Installer mInstaller;
456
457    /** Directory where installed third-party apps stored */
458    final File mAppInstallDir;
459    final File mEphemeralInstallDir;
460
461    /**
462     * Directory to which applications installed internally have their
463     * 32 bit native libraries copied.
464     */
465    private File mAppLib32InstallDir;
466
467    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
468    // apps.
469    final File mDrmAppPrivateInstallDir;
470
471    // ----------------------------------------------------------------
472
473    // Lock for state used when installing and doing other long running
474    // operations.  Methods that must be called with this lock held have
475    // the suffix "LI".
476    final Object mInstallLock = new Object();
477
478    // ----------------------------------------------------------------
479
480    // Keys are String (package name), values are Package.  This also serves
481    // as the lock for the global state.  Methods that must be called with
482    // this lock held have the prefix "LP".
483    @GuardedBy("mPackages")
484    final ArrayMap<String, PackageParser.Package> mPackages =
485            new ArrayMap<String, PackageParser.Package>();
486
487    // Tracks available target package names -> overlay package paths.
488    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
489        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
490
491    /**
492     * Tracks new system packages [received in an OTA] that we expect to
493     * find updated user-installed versions. Keys are package name, values
494     * are package location.
495     */
496    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
497
498    /**
499     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
500     */
501    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
502    /**
503     * Whether or not system app permissions should be promoted from install to runtime.
504     */
505    boolean mPromoteSystemApps;
506
507    final Settings mSettings;
508    boolean mRestoredSettings;
509
510    // System configuration read by SystemConfig.
511    final int[] mGlobalGids;
512    final SparseArray<ArraySet<String>> mSystemPermissions;
513    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
514
515    // If mac_permissions.xml was found for seinfo labeling.
516    boolean mFoundPolicyFile;
517
518    // If a recursive restorecon of /data/data/<pkg> is needed.
519    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
520
521    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
522
523    public static final class SharedLibraryEntry {
524        public final String path;
525        public final String apk;
526
527        SharedLibraryEntry(String _path, String _apk) {
528            path = _path;
529            apk = _apk;
530        }
531    }
532
533    // Currently known shared libraries.
534    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
535            new ArrayMap<String, SharedLibraryEntry>();
536
537    // All available activities, for your resolving pleasure.
538    final ActivityIntentResolver mActivities =
539            new ActivityIntentResolver();
540
541    // All available receivers, for your resolving pleasure.
542    final ActivityIntentResolver mReceivers =
543            new ActivityIntentResolver();
544
545    // All available services, for your resolving pleasure.
546    final ServiceIntentResolver mServices = new ServiceIntentResolver();
547
548    // All available providers, for your resolving pleasure.
549    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
550
551    // Mapping from provider base names (first directory in content URI codePath)
552    // to the provider information.
553    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
554            new ArrayMap<String, PackageParser.Provider>();
555
556    // Mapping from instrumentation class names to info about them.
557    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
558            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
559
560    // Mapping from permission names to info about them.
561    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
562            new ArrayMap<String, PackageParser.PermissionGroup>();
563
564    // Packages whose data we have transfered into another package, thus
565    // should no longer exist.
566    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
567
568    // Broadcast actions that are only available to the system.
569    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
570
571    /** List of packages waiting for verification. */
572    final SparseArray<PackageVerificationState> mPendingVerification
573            = new SparseArray<PackageVerificationState>();
574
575    /** Set of packages associated with each app op permission. */
576    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
577
578    final PackageInstallerService mInstallerService;
579
580    private final PackageDexOptimizer mPackageDexOptimizer;
581
582    private AtomicInteger mNextMoveId = new AtomicInteger();
583    private final MoveCallbacks mMoveCallbacks;
584
585    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
586
587    // Cache of users who need badging.
588    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
589
590    /** Token for keys in mPendingVerification. */
591    private int mPendingVerificationToken = 0;
592
593    volatile boolean mSystemReady;
594    volatile boolean mSafeMode;
595    volatile boolean mHasSystemUidErrors;
596
597    ApplicationInfo mAndroidApplication;
598    final ActivityInfo mResolveActivity = new ActivityInfo();
599    final ResolveInfo mResolveInfo = new ResolveInfo();
600    ComponentName mResolveComponentName;
601    PackageParser.Package mPlatformPackage;
602    ComponentName mCustomResolverComponentName;
603
604    boolean mResolverReplaced = false;
605
606    private final @Nullable ComponentName mIntentFilterVerifierComponent;
607    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
608
609    private int mIntentFilterVerificationToken = 0;
610
611    /** Component that knows whether or not an ephemeral application exists */
612    final ComponentName mEphemeralResolverComponent;
613    /** The service connection to the ephemeral resolver */
614    final EphemeralResolverConnection mEphemeralResolverConnection;
615
616    /** Component used to install ephemeral applications */
617    final ComponentName mEphemeralInstallerComponent;
618    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
619    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
620
621    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
622            = new SparseArray<IntentFilterVerificationState>();
623
624    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
625            new DefaultPermissionGrantPolicy(this);
626
627    // List of packages names to keep cached, even if they are uninstalled for all users
628    private List<String> mKeepUninstalledPackages;
629
630    private static class IFVerificationParams {
631        PackageParser.Package pkg;
632        boolean replacing;
633        int userId;
634        int verifierUid;
635
636        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
637                int _userId, int _verifierUid) {
638            pkg = _pkg;
639            replacing = _replacing;
640            userId = _userId;
641            replacing = _replacing;
642            verifierUid = _verifierUid;
643        }
644    }
645
646    private interface IntentFilterVerifier<T extends IntentFilter> {
647        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
648                                               T filter, String packageName);
649        void startVerifications(int userId);
650        void receiveVerificationResponse(int verificationId);
651    }
652
653    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
654        private Context mContext;
655        private ComponentName mIntentFilterVerifierComponent;
656        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
657
658        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
659            mContext = context;
660            mIntentFilterVerifierComponent = verifierComponent;
661        }
662
663        private String getDefaultScheme() {
664            return IntentFilter.SCHEME_HTTPS;
665        }
666
667        @Override
668        public void startVerifications(int userId) {
669            // Launch verifications requests
670            int count = mCurrentIntentFilterVerifications.size();
671            for (int n=0; n<count; n++) {
672                int verificationId = mCurrentIntentFilterVerifications.get(n);
673                final IntentFilterVerificationState ivs =
674                        mIntentFilterVerificationStates.get(verificationId);
675
676                String packageName = ivs.getPackageName();
677
678                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
679                final int filterCount = filters.size();
680                ArraySet<String> domainsSet = new ArraySet<>();
681                for (int m=0; m<filterCount; m++) {
682                    PackageParser.ActivityIntentInfo filter = filters.get(m);
683                    domainsSet.addAll(filter.getHostsList());
684                }
685                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
686                synchronized (mPackages) {
687                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
688                            packageName, domainsList) != null) {
689                        scheduleWriteSettingsLocked();
690                    }
691                }
692                sendVerificationRequest(userId, verificationId, ivs);
693            }
694            mCurrentIntentFilterVerifications.clear();
695        }
696
697        private void sendVerificationRequest(int userId, int verificationId,
698                IntentFilterVerificationState ivs) {
699
700            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
701            verificationIntent.putExtra(
702                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
703                    verificationId);
704            verificationIntent.putExtra(
705                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
706                    getDefaultScheme());
707            verificationIntent.putExtra(
708                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
709                    ivs.getHostsString());
710            verificationIntent.putExtra(
711                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
712                    ivs.getPackageName());
713            verificationIntent.setComponent(mIntentFilterVerifierComponent);
714            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
715
716            UserHandle user = new UserHandle(userId);
717            mContext.sendBroadcastAsUser(verificationIntent, user);
718            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
719                    "Sending IntentFilter verification broadcast");
720        }
721
722        public void receiveVerificationResponse(int verificationId) {
723            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
724
725            final boolean verified = ivs.isVerified();
726
727            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
728            final int count = filters.size();
729            if (DEBUG_DOMAIN_VERIFICATION) {
730                Slog.i(TAG, "Received verification response " + verificationId
731                        + " for " + count + " filters, verified=" + verified);
732            }
733            for (int n=0; n<count; n++) {
734                PackageParser.ActivityIntentInfo filter = filters.get(n);
735                filter.setVerified(verified);
736
737                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
738                        + " verified with result:" + verified + " and hosts:"
739                        + ivs.getHostsString());
740            }
741
742            mIntentFilterVerificationStates.remove(verificationId);
743
744            final String packageName = ivs.getPackageName();
745            IntentFilterVerificationInfo ivi = null;
746
747            synchronized (mPackages) {
748                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
749            }
750            if (ivi == null) {
751                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
752                        + verificationId + " packageName:" + packageName);
753                return;
754            }
755            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
756                    "Updating IntentFilterVerificationInfo for package " + packageName
757                            +" verificationId:" + verificationId);
758
759            synchronized (mPackages) {
760                if (verified) {
761                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
762                } else {
763                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
764                }
765                scheduleWriteSettingsLocked();
766
767                final int userId = ivs.getUserId();
768                if (userId != UserHandle.USER_ALL) {
769                    final int userStatus =
770                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
771
772                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
773                    boolean needUpdate = false;
774
775                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
776                    // already been set by the User thru the Disambiguation dialog
777                    switch (userStatus) {
778                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
779                            if (verified) {
780                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
781                            } else {
782                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
783                            }
784                            needUpdate = true;
785                            break;
786
787                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
788                            if (verified) {
789                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
790                                needUpdate = true;
791                            }
792                            break;
793
794                        default:
795                            // Nothing to do
796                    }
797
798                    if (needUpdate) {
799                        mSettings.updateIntentFilterVerificationStatusLPw(
800                                packageName, updatedStatus, userId);
801                        scheduleWritePackageRestrictionsLocked(userId);
802                    }
803                }
804            }
805        }
806
807        @Override
808        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
809                    ActivityIntentInfo filter, String packageName) {
810            if (!hasValidDomains(filter)) {
811                return false;
812            }
813            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
814            if (ivs == null) {
815                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
816                        packageName);
817            }
818            if (DEBUG_DOMAIN_VERIFICATION) {
819                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
820            }
821            ivs.addFilter(filter);
822            return true;
823        }
824
825        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
826                int userId, int verificationId, String packageName) {
827            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
828                    verifierUid, userId, packageName);
829            ivs.setPendingState();
830            synchronized (mPackages) {
831                mIntentFilterVerificationStates.append(verificationId, ivs);
832                mCurrentIntentFilterVerifications.add(verificationId);
833            }
834            return ivs;
835        }
836    }
837
838    private static boolean hasValidDomains(ActivityIntentInfo filter) {
839        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
840                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
841                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
842    }
843
844    // Set of pending broadcasts for aggregating enable/disable of components.
845    static class PendingPackageBroadcasts {
846        // for each user id, a map of <package name -> components within that package>
847        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
848
849        public PendingPackageBroadcasts() {
850            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
851        }
852
853        public ArrayList<String> get(int userId, String packageName) {
854            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
855            return packages.get(packageName);
856        }
857
858        public void put(int userId, String packageName, ArrayList<String> components) {
859            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
860            packages.put(packageName, components);
861        }
862
863        public void remove(int userId, String packageName) {
864            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
865            if (packages != null) {
866                packages.remove(packageName);
867            }
868        }
869
870        public void remove(int userId) {
871            mUidMap.remove(userId);
872        }
873
874        public int userIdCount() {
875            return mUidMap.size();
876        }
877
878        public int userIdAt(int n) {
879            return mUidMap.keyAt(n);
880        }
881
882        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
883            return mUidMap.get(userId);
884        }
885
886        public int size() {
887            // total number of pending broadcast entries across all userIds
888            int num = 0;
889            for (int i = 0; i< mUidMap.size(); i++) {
890                num += mUidMap.valueAt(i).size();
891            }
892            return num;
893        }
894
895        public void clear() {
896            mUidMap.clear();
897        }
898
899        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
900            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
901            if (map == null) {
902                map = new ArrayMap<String, ArrayList<String>>();
903                mUidMap.put(userId, map);
904            }
905            return map;
906        }
907    }
908    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
909
910    // Service Connection to remote media container service to copy
911    // package uri's from external media onto secure containers
912    // or internal storage.
913    private IMediaContainerService mContainerService = null;
914
915    static final int SEND_PENDING_BROADCAST = 1;
916    static final int MCS_BOUND = 3;
917    static final int END_COPY = 4;
918    static final int INIT_COPY = 5;
919    static final int MCS_UNBIND = 6;
920    static final int START_CLEANING_PACKAGE = 7;
921    static final int FIND_INSTALL_LOC = 8;
922    static final int POST_INSTALL = 9;
923    static final int MCS_RECONNECT = 10;
924    static final int MCS_GIVE_UP = 11;
925    static final int UPDATED_MEDIA_STATUS = 12;
926    static final int WRITE_SETTINGS = 13;
927    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
928    static final int PACKAGE_VERIFIED = 15;
929    static final int CHECK_PENDING_VERIFICATION = 16;
930    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
931    static final int INTENT_FILTER_VERIFIED = 18;
932
933    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
934
935    // Delay time in millisecs
936    static final int BROADCAST_DELAY = 10 * 1000;
937
938    static UserManagerService sUserManager;
939
940    // Stores a list of users whose package restrictions file needs to be updated
941    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
942
943    final private DefaultContainerConnection mDefContainerConn =
944            new DefaultContainerConnection();
945    class DefaultContainerConnection implements ServiceConnection {
946        public void onServiceConnected(ComponentName name, IBinder service) {
947            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
948            IMediaContainerService imcs =
949                IMediaContainerService.Stub.asInterface(service);
950            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
951        }
952
953        public void onServiceDisconnected(ComponentName name) {
954            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
955        }
956    }
957
958    // Recordkeeping of restore-after-install operations that are currently in flight
959    // between the Package Manager and the Backup Manager
960    static class PostInstallData {
961        public InstallArgs args;
962        public PackageInstalledInfo res;
963
964        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
965            args = _a;
966            res = _r;
967        }
968    }
969
970    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
971    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
972
973    // XML tags for backup/restore of various bits of state
974    private static final String TAG_PREFERRED_BACKUP = "pa";
975    private static final String TAG_DEFAULT_APPS = "da";
976    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
977
978    final @Nullable String mRequiredVerifierPackage;
979    final @Nullable String mRequiredInstallerPackage;
980
981    private final PackageUsage mPackageUsage = new PackageUsage();
982
983    private class PackageUsage {
984        private static final int WRITE_INTERVAL
985            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
986
987        private final Object mFileLock = new Object();
988        private final AtomicLong mLastWritten = new AtomicLong(0);
989        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
990
991        private boolean mIsHistoricalPackageUsageAvailable = true;
992
993        boolean isHistoricalPackageUsageAvailable() {
994            return mIsHistoricalPackageUsageAvailable;
995        }
996
997        void write(boolean force) {
998            if (force) {
999                writeInternal();
1000                return;
1001            }
1002            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1003                && !DEBUG_DEXOPT) {
1004                return;
1005            }
1006            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1007                new Thread("PackageUsage_DiskWriter") {
1008                    @Override
1009                    public void run() {
1010                        try {
1011                            writeInternal();
1012                        } finally {
1013                            mBackgroundWriteRunning.set(false);
1014                        }
1015                    }
1016                }.start();
1017            }
1018        }
1019
1020        private void writeInternal() {
1021            synchronized (mPackages) {
1022                synchronized (mFileLock) {
1023                    AtomicFile file = getFile();
1024                    FileOutputStream f = null;
1025                    try {
1026                        f = file.startWrite();
1027                        BufferedOutputStream out = new BufferedOutputStream(f);
1028                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1029                        StringBuilder sb = new StringBuilder();
1030                        for (PackageParser.Package pkg : mPackages.values()) {
1031                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1032                                continue;
1033                            }
1034                            sb.setLength(0);
1035                            sb.append(pkg.packageName);
1036                            sb.append(' ');
1037                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1038                            sb.append('\n');
1039                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1040                        }
1041                        out.flush();
1042                        file.finishWrite(f);
1043                    } catch (IOException e) {
1044                        if (f != null) {
1045                            file.failWrite(f);
1046                        }
1047                        Log.e(TAG, "Failed to write package usage times", e);
1048                    }
1049                }
1050            }
1051            mLastWritten.set(SystemClock.elapsedRealtime());
1052        }
1053
1054        void readLP() {
1055            synchronized (mFileLock) {
1056                AtomicFile file = getFile();
1057                BufferedInputStream in = null;
1058                try {
1059                    in = new BufferedInputStream(file.openRead());
1060                    StringBuffer sb = new StringBuffer();
1061                    while (true) {
1062                        String packageName = readToken(in, sb, ' ');
1063                        if (packageName == null) {
1064                            break;
1065                        }
1066                        String timeInMillisString = readToken(in, sb, '\n');
1067                        if (timeInMillisString == null) {
1068                            throw new IOException("Failed to find last usage time for package "
1069                                                  + packageName);
1070                        }
1071                        PackageParser.Package pkg = mPackages.get(packageName);
1072                        if (pkg == null) {
1073                            continue;
1074                        }
1075                        long timeInMillis;
1076                        try {
1077                            timeInMillis = Long.parseLong(timeInMillisString);
1078                        } catch (NumberFormatException e) {
1079                            throw new IOException("Failed to parse " + timeInMillisString
1080                                                  + " as a long.", e);
1081                        }
1082                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1083                    }
1084                } catch (FileNotFoundException expected) {
1085                    mIsHistoricalPackageUsageAvailable = false;
1086                } catch (IOException e) {
1087                    Log.w(TAG, "Failed to read package usage times", e);
1088                } finally {
1089                    IoUtils.closeQuietly(in);
1090                }
1091            }
1092            mLastWritten.set(SystemClock.elapsedRealtime());
1093        }
1094
1095        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1096                throws IOException {
1097            sb.setLength(0);
1098            while (true) {
1099                int ch = in.read();
1100                if (ch == -1) {
1101                    if (sb.length() == 0) {
1102                        return null;
1103                    }
1104                    throw new IOException("Unexpected EOF");
1105                }
1106                if (ch == endOfToken) {
1107                    return sb.toString();
1108                }
1109                sb.append((char)ch);
1110            }
1111        }
1112
1113        private AtomicFile getFile() {
1114            File dataDir = Environment.getDataDirectory();
1115            File systemDir = new File(dataDir, "system");
1116            File fname = new File(systemDir, "package-usage.list");
1117            return new AtomicFile(fname);
1118        }
1119    }
1120
1121    class PackageHandler extends Handler {
1122        private boolean mBound = false;
1123        final ArrayList<HandlerParams> mPendingInstalls =
1124            new ArrayList<HandlerParams>();
1125
1126        private boolean connectToService() {
1127            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1128                    " DefaultContainerService");
1129            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1130            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1131            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1132                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1133                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1134                mBound = true;
1135                return true;
1136            }
1137            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1138            return false;
1139        }
1140
1141        private void disconnectService() {
1142            mContainerService = null;
1143            mBound = false;
1144            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1145            mContext.unbindService(mDefContainerConn);
1146            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1147        }
1148
1149        PackageHandler(Looper looper) {
1150            super(looper);
1151        }
1152
1153        public void handleMessage(Message msg) {
1154            try {
1155                doHandleMessage(msg);
1156            } finally {
1157                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1158            }
1159        }
1160
1161        void doHandleMessage(Message msg) {
1162            switch (msg.what) {
1163                case INIT_COPY: {
1164                    HandlerParams params = (HandlerParams) msg.obj;
1165                    int idx = mPendingInstalls.size();
1166                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1167                    // If a bind was already initiated we dont really
1168                    // need to do anything. The pending install
1169                    // will be processed later on.
1170                    if (!mBound) {
1171                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1172                                System.identityHashCode(mHandler));
1173                        // If this is the only one pending we might
1174                        // have to bind to the service again.
1175                        if (!connectToService()) {
1176                            Slog.e(TAG, "Failed to bind to media container service");
1177                            params.serviceError();
1178                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1179                                    System.identityHashCode(mHandler));
1180                            if (params.traceMethod != null) {
1181                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1182                                        params.traceCookie);
1183                            }
1184                            return;
1185                        } else {
1186                            // Once we bind to the service, the first
1187                            // pending request will be processed.
1188                            mPendingInstalls.add(idx, params);
1189                        }
1190                    } else {
1191                        mPendingInstalls.add(idx, params);
1192                        // Already bound to the service. Just make
1193                        // sure we trigger off processing the first request.
1194                        if (idx == 0) {
1195                            mHandler.sendEmptyMessage(MCS_BOUND);
1196                        }
1197                    }
1198                    break;
1199                }
1200                case MCS_BOUND: {
1201                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1202                    if (msg.obj != null) {
1203                        mContainerService = (IMediaContainerService) msg.obj;
1204                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1205                                System.identityHashCode(mHandler));
1206                    }
1207                    if (mContainerService == null) {
1208                        if (!mBound) {
1209                            // Something seriously wrong since we are not bound and we are not
1210                            // waiting for connection. Bail out.
1211                            Slog.e(TAG, "Cannot bind to media container service");
1212                            for (HandlerParams params : mPendingInstalls) {
1213                                // Indicate service bind error
1214                                params.serviceError();
1215                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1216                                        System.identityHashCode(params));
1217                                if (params.traceMethod != null) {
1218                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1219                                            params.traceMethod, params.traceCookie);
1220                                }
1221                                return;
1222                            }
1223                            mPendingInstalls.clear();
1224                        } else {
1225                            Slog.w(TAG, "Waiting to connect to media container service");
1226                        }
1227                    } else if (mPendingInstalls.size() > 0) {
1228                        HandlerParams params = mPendingInstalls.get(0);
1229                        if (params != null) {
1230                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1231                                    System.identityHashCode(params));
1232                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1233                            if (params.startCopy()) {
1234                                // We are done...  look for more work or to
1235                                // go idle.
1236                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1237                                        "Checking for more work or unbind...");
1238                                // Delete pending install
1239                                if (mPendingInstalls.size() > 0) {
1240                                    mPendingInstalls.remove(0);
1241                                }
1242                                if (mPendingInstalls.size() == 0) {
1243                                    if (mBound) {
1244                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1245                                                "Posting delayed MCS_UNBIND");
1246                                        removeMessages(MCS_UNBIND);
1247                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1248                                        // Unbind after a little delay, to avoid
1249                                        // continual thrashing.
1250                                        sendMessageDelayed(ubmsg, 10000);
1251                                    }
1252                                } else {
1253                                    // There are more pending requests in queue.
1254                                    // Just post MCS_BOUND message to trigger processing
1255                                    // of next pending install.
1256                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1257                                            "Posting MCS_BOUND for next work");
1258                                    mHandler.sendEmptyMessage(MCS_BOUND);
1259                                }
1260                            }
1261                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1262                        }
1263                    } else {
1264                        // Should never happen ideally.
1265                        Slog.w(TAG, "Empty queue");
1266                    }
1267                    break;
1268                }
1269                case MCS_RECONNECT: {
1270                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1271                    if (mPendingInstalls.size() > 0) {
1272                        if (mBound) {
1273                            disconnectService();
1274                        }
1275                        if (!connectToService()) {
1276                            Slog.e(TAG, "Failed to bind to media container service");
1277                            for (HandlerParams params : mPendingInstalls) {
1278                                // Indicate service bind error
1279                                params.serviceError();
1280                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1281                                        System.identityHashCode(params));
1282                            }
1283                            mPendingInstalls.clear();
1284                        }
1285                    }
1286                    break;
1287                }
1288                case MCS_UNBIND: {
1289                    // If there is no actual work left, then time to unbind.
1290                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1291
1292                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1293                        if (mBound) {
1294                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1295
1296                            disconnectService();
1297                        }
1298                    } else if (mPendingInstalls.size() > 0) {
1299                        // There are more pending requests in queue.
1300                        // Just post MCS_BOUND message to trigger processing
1301                        // of next pending install.
1302                        mHandler.sendEmptyMessage(MCS_BOUND);
1303                    }
1304
1305                    break;
1306                }
1307                case MCS_GIVE_UP: {
1308                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1309                    HandlerParams params = mPendingInstalls.remove(0);
1310                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1311                            System.identityHashCode(params));
1312                    break;
1313                }
1314                case SEND_PENDING_BROADCAST: {
1315                    String packages[];
1316                    ArrayList<String> components[];
1317                    int size = 0;
1318                    int uids[];
1319                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1320                    synchronized (mPackages) {
1321                        if (mPendingBroadcasts == null) {
1322                            return;
1323                        }
1324                        size = mPendingBroadcasts.size();
1325                        if (size <= 0) {
1326                            // Nothing to be done. Just return
1327                            return;
1328                        }
1329                        packages = new String[size];
1330                        components = new ArrayList[size];
1331                        uids = new int[size];
1332                        int i = 0;  // filling out the above arrays
1333
1334                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1335                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1336                            Iterator<Map.Entry<String, ArrayList<String>>> it
1337                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1338                                            .entrySet().iterator();
1339                            while (it.hasNext() && i < size) {
1340                                Map.Entry<String, ArrayList<String>> ent = it.next();
1341                                packages[i] = ent.getKey();
1342                                components[i] = ent.getValue();
1343                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1344                                uids[i] = (ps != null)
1345                                        ? UserHandle.getUid(packageUserId, ps.appId)
1346                                        : -1;
1347                                i++;
1348                            }
1349                        }
1350                        size = i;
1351                        mPendingBroadcasts.clear();
1352                    }
1353                    // Send broadcasts
1354                    for (int i = 0; i < size; i++) {
1355                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1356                    }
1357                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1358                    break;
1359                }
1360                case START_CLEANING_PACKAGE: {
1361                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1362                    final String packageName = (String)msg.obj;
1363                    final int userId = msg.arg1;
1364                    final boolean andCode = msg.arg2 != 0;
1365                    synchronized (mPackages) {
1366                        if (userId == UserHandle.USER_ALL) {
1367                            int[] users = sUserManager.getUserIds();
1368                            for (int user : users) {
1369                                mSettings.addPackageToCleanLPw(
1370                                        new PackageCleanItem(user, packageName, andCode));
1371                            }
1372                        } else {
1373                            mSettings.addPackageToCleanLPw(
1374                                    new PackageCleanItem(userId, packageName, andCode));
1375                        }
1376                    }
1377                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1378                    startCleaningPackages();
1379                } break;
1380                case POST_INSTALL: {
1381                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1382
1383                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1384                    mRunningInstalls.delete(msg.arg1);
1385                    boolean deleteOld = false;
1386
1387                    if (data != null) {
1388                        InstallArgs args = data.args;
1389                        PackageInstalledInfo res = data.res;
1390
1391                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1392                            final String packageName = res.pkg.applicationInfo.packageName;
1393                            res.removedInfo.sendBroadcast(false, true, false);
1394                            Bundle extras = new Bundle(1);
1395                            extras.putInt(Intent.EXTRA_UID, res.uid);
1396
1397                            // Now that we successfully installed the package, grant runtime
1398                            // permissions if requested before broadcasting the install.
1399                            if ((args.installFlags
1400                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
1401                                    && res.pkg.applicationInfo.targetSdkVersion
1402                                            >= Build.VERSION_CODES.M) {
1403                                grantRequestedRuntimePermissions(res.pkg, args.user.getIdentifier(),
1404                                        args.installGrantPermissions);
1405                            }
1406
1407                            synchronized (mPackages) {
1408                                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1409                            }
1410
1411                            // Determine the set of users who are adding this
1412                            // package for the first time vs. those who are seeing
1413                            // an update.
1414                            int[] firstUsers;
1415                            int[] updateUsers = new int[0];
1416                            if (res.origUsers == null || res.origUsers.length == 0) {
1417                                firstUsers = res.newUsers;
1418                            } else {
1419                                firstUsers = new int[0];
1420                                for (int i=0; i<res.newUsers.length; i++) {
1421                                    int user = res.newUsers[i];
1422                                    boolean isNew = true;
1423                                    for (int j=0; j<res.origUsers.length; j++) {
1424                                        if (res.origUsers[j] == user) {
1425                                            isNew = false;
1426                                            break;
1427                                        }
1428                                    }
1429                                    if (isNew) {
1430                                        int[] newFirst = new int[firstUsers.length+1];
1431                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1432                                                firstUsers.length);
1433                                        newFirst[firstUsers.length] = user;
1434                                        firstUsers = newFirst;
1435                                    } else {
1436                                        int[] newUpdate = new int[updateUsers.length+1];
1437                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1438                                                updateUsers.length);
1439                                        newUpdate[updateUsers.length] = user;
1440                                        updateUsers = newUpdate;
1441                                    }
1442                                }
1443                            }
1444                            // don't broadcast for ephemeral installs/updates
1445                            final boolean isEphemeral = isEphemeral(res.pkg);
1446                            if (!isEphemeral) {
1447                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1448                                        extras, 0 /*flags*/, null /*targetPackage*/,
1449                                        null /*finishedReceiver*/, firstUsers);
1450                            }
1451                            final boolean update = res.removedInfo.removedPackage != null;
1452                            if (update) {
1453                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1454                            }
1455                            if (!isEphemeral) {
1456                                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1457                                        extras, 0 /*flags*/, null /*targetPackage*/,
1458                                        null /*finishedReceiver*/, updateUsers);
1459                            }
1460                            if (update) {
1461                                if (!isEphemeral) {
1462                                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1463                                            packageName, extras, 0 /*flags*/,
1464                                            null /*targetPackage*/, null /*finishedReceiver*/,
1465                                            updateUsers);
1466                                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1467                                            null /*package*/, null /*extras*/, 0 /*flags*/,
1468                                            packageName /*targetPackage*/,
1469                                            null /*finishedReceiver*/, updateUsers);
1470                                }
1471
1472                                // treat asec-hosted packages like removable media on upgrade
1473                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1474                                    if (DEBUG_INSTALL) {
1475                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1476                                                + " is ASEC-hosted -> AVAILABLE");
1477                                    }
1478                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1479                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1480                                    pkgList.add(packageName);
1481                                    sendResourcesChangedBroadcast(true, true,
1482                                            pkgList,uidArray, null);
1483                                }
1484                            }
1485                            if (res.removedInfo.args != null) {
1486                                // Remove the replaced package's older resources safely now
1487                                deleteOld = true;
1488                            }
1489
1490                            // If this app is a browser and it's newly-installed for some
1491                            // users, clear any default-browser state in those users
1492                            if (firstUsers.length > 0) {
1493                                // the app's nature doesn't depend on the user, so we can just
1494                                // check its browser nature in any user and generalize.
1495                                if (packageIsBrowser(packageName, firstUsers[0])) {
1496                                    synchronized (mPackages) {
1497                                        for (int userId : firstUsers) {
1498                                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1499                                        }
1500                                    }
1501                                }
1502                            }
1503                            // Log current value of "unknown sources" setting
1504                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1505                                getUnknownSourcesSettings());
1506                        }
1507                        // Force a gc to clear up things
1508                        Runtime.getRuntime().gc();
1509                        // We delete after a gc for applications  on sdcard.
1510                        if (deleteOld) {
1511                            synchronized (mInstallLock) {
1512                                res.removedInfo.args.doPostDeleteLI(true);
1513                            }
1514                        }
1515                        if (args.observer != null) {
1516                            try {
1517                                Bundle extras = extrasForInstallResult(res);
1518                                args.observer.onPackageInstalled(res.name, res.returnCode,
1519                                        res.returnMsg, extras);
1520                            } catch (RemoteException e) {
1521                                Slog.i(TAG, "Observer no longer exists.");
1522                            }
1523                        }
1524                        if (args.traceMethod != null) {
1525                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1526                                    args.traceCookie);
1527                        }
1528                        return;
1529                    } else {
1530                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1531                    }
1532
1533                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1534                } break;
1535                case UPDATED_MEDIA_STATUS: {
1536                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1537                    boolean reportStatus = msg.arg1 == 1;
1538                    boolean doGc = msg.arg2 == 1;
1539                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1540                    if (doGc) {
1541                        // Force a gc to clear up stale containers.
1542                        Runtime.getRuntime().gc();
1543                    }
1544                    if (msg.obj != null) {
1545                        @SuppressWarnings("unchecked")
1546                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1547                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1548                        // Unload containers
1549                        unloadAllContainers(args);
1550                    }
1551                    if (reportStatus) {
1552                        try {
1553                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1554                            PackageHelper.getMountService().finishMediaUpdate();
1555                        } catch (RemoteException e) {
1556                            Log.e(TAG, "MountService not running?");
1557                        }
1558                    }
1559                } break;
1560                case WRITE_SETTINGS: {
1561                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1562                    synchronized (mPackages) {
1563                        removeMessages(WRITE_SETTINGS);
1564                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1565                        mSettings.writeLPr();
1566                        mDirtyUsers.clear();
1567                    }
1568                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1569                } break;
1570                case WRITE_PACKAGE_RESTRICTIONS: {
1571                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1572                    synchronized (mPackages) {
1573                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1574                        for (int userId : mDirtyUsers) {
1575                            mSettings.writePackageRestrictionsLPr(userId);
1576                        }
1577                        mDirtyUsers.clear();
1578                    }
1579                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1580                } break;
1581                case CHECK_PENDING_VERIFICATION: {
1582                    final int verificationId = msg.arg1;
1583                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1584
1585                    if ((state != null) && !state.timeoutExtended()) {
1586                        final InstallArgs args = state.getInstallArgs();
1587                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1588
1589                        Slog.i(TAG, "Verification timed out for " + originUri);
1590                        mPendingVerification.remove(verificationId);
1591
1592                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1593
1594                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1595                            Slog.i(TAG, "Continuing with installation of " + originUri);
1596                            state.setVerifierResponse(Binder.getCallingUid(),
1597                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1598                            broadcastPackageVerified(verificationId, originUri,
1599                                    PackageManager.VERIFICATION_ALLOW,
1600                                    state.getInstallArgs().getUser());
1601                            try {
1602                                ret = args.copyApk(mContainerService, true);
1603                            } catch (RemoteException e) {
1604                                Slog.e(TAG, "Could not contact the ContainerService");
1605                            }
1606                        } else {
1607                            broadcastPackageVerified(verificationId, originUri,
1608                                    PackageManager.VERIFICATION_REJECT,
1609                                    state.getInstallArgs().getUser());
1610                        }
1611
1612                        Trace.asyncTraceEnd(
1613                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1614
1615                        processPendingInstall(args, ret);
1616                        mHandler.sendEmptyMessage(MCS_UNBIND);
1617                    }
1618                    break;
1619                }
1620                case PACKAGE_VERIFIED: {
1621                    final int verificationId = msg.arg1;
1622
1623                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1624                    if (state == null) {
1625                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1626                        break;
1627                    }
1628
1629                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1630
1631                    state.setVerifierResponse(response.callerUid, response.code);
1632
1633                    if (state.isVerificationComplete()) {
1634                        mPendingVerification.remove(verificationId);
1635
1636                        final InstallArgs args = state.getInstallArgs();
1637                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1638
1639                        int ret;
1640                        if (state.isInstallAllowed()) {
1641                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1642                            broadcastPackageVerified(verificationId, originUri,
1643                                    response.code, state.getInstallArgs().getUser());
1644                            try {
1645                                ret = args.copyApk(mContainerService, true);
1646                            } catch (RemoteException e) {
1647                                Slog.e(TAG, "Could not contact the ContainerService");
1648                            }
1649                        } else {
1650                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1651                        }
1652
1653                        Trace.asyncTraceEnd(
1654                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1655
1656                        processPendingInstall(args, ret);
1657                        mHandler.sendEmptyMessage(MCS_UNBIND);
1658                    }
1659
1660                    break;
1661                }
1662                case START_INTENT_FILTER_VERIFICATIONS: {
1663                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1664                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1665                            params.replacing, params.pkg);
1666                    break;
1667                }
1668                case INTENT_FILTER_VERIFIED: {
1669                    final int verificationId = msg.arg1;
1670
1671                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1672                            verificationId);
1673                    if (state == null) {
1674                        Slog.w(TAG, "Invalid IntentFilter verification token "
1675                                + verificationId + " received");
1676                        break;
1677                    }
1678
1679                    final int userId = state.getUserId();
1680
1681                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1682                            "Processing IntentFilter verification with token:"
1683                            + verificationId + " and userId:" + userId);
1684
1685                    final IntentFilterVerificationResponse response =
1686                            (IntentFilterVerificationResponse) msg.obj;
1687
1688                    state.setVerifierResponse(response.callerUid, response.code);
1689
1690                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1691                            "IntentFilter verification with token:" + verificationId
1692                            + " and userId:" + userId
1693                            + " is settings verifier response with response code:"
1694                            + response.code);
1695
1696                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1697                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1698                                + response.getFailedDomainsString());
1699                    }
1700
1701                    if (state.isVerificationComplete()) {
1702                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1703                    } else {
1704                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1705                                "IntentFilter verification with token:" + verificationId
1706                                + " was not said to be complete");
1707                    }
1708
1709                    break;
1710                }
1711            }
1712        }
1713    }
1714
1715    private StorageEventListener mStorageListener = new StorageEventListener() {
1716        @Override
1717        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1718            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1719                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1720                    final String volumeUuid = vol.getFsUuid();
1721
1722                    // Clean up any users or apps that were removed or recreated
1723                    // while this volume was missing
1724                    reconcileUsers(volumeUuid);
1725                    reconcileApps(volumeUuid);
1726
1727                    // Clean up any install sessions that expired or were
1728                    // cancelled while this volume was missing
1729                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1730
1731                    loadPrivatePackages(vol);
1732
1733                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1734                    unloadPrivatePackages(vol);
1735                }
1736            }
1737
1738            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1739                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1740                    updateExternalMediaStatus(true, false);
1741                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1742                    updateExternalMediaStatus(false, false);
1743                }
1744            }
1745        }
1746
1747        @Override
1748        public void onVolumeForgotten(String fsUuid) {
1749            if (TextUtils.isEmpty(fsUuid)) {
1750                Slog.w(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1751                return;
1752            }
1753
1754            // Remove any apps installed on the forgotten volume
1755            synchronized (mPackages) {
1756                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1757                for (PackageSetting ps : packages) {
1758                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1759                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1760                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1761                }
1762
1763                mSettings.onVolumeForgotten(fsUuid);
1764                mSettings.writeLPr();
1765            }
1766        }
1767    };
1768
1769    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId,
1770            String[] grantedPermissions) {
1771        if (userId >= UserHandle.USER_SYSTEM) {
1772            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1773        } else if (userId == UserHandle.USER_ALL) {
1774            final int[] userIds;
1775            synchronized (mPackages) {
1776                userIds = UserManagerService.getInstance().getUserIds();
1777            }
1778            for (int someUserId : userIds) {
1779                grantRequestedRuntimePermissionsForUser(pkg, someUserId, grantedPermissions);
1780            }
1781        }
1782
1783        // We could have touched GID membership, so flush out packages.list
1784        synchronized (mPackages) {
1785            mSettings.writePackageListLPr();
1786        }
1787    }
1788
1789    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1790            String[] grantedPermissions) {
1791        SettingBase sb = (SettingBase) pkg.mExtras;
1792        if (sb == null) {
1793            return;
1794        }
1795
1796        PermissionsState permissionsState = sb.getPermissionsState();
1797
1798        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1799                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1800
1801        synchronized (mPackages) {
1802            for (String permission : pkg.requestedPermissions) {
1803                BasePermission bp = mSettings.mPermissions.get(permission);
1804                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1805                        && (grantedPermissions == null
1806                               || ArrayUtils.contains(grantedPermissions, permission))) {
1807                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1808                    // Installer cannot change immutable permissions.
1809                    if ((flags & immutableFlags) == 0) {
1810                        grantRuntimePermission(pkg.packageName, permission, userId);
1811                    }
1812                }
1813            }
1814        }
1815    }
1816
1817    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1818        Bundle extras = null;
1819        switch (res.returnCode) {
1820            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1821                extras = new Bundle();
1822                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1823                        res.origPermission);
1824                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1825                        res.origPackage);
1826                break;
1827            }
1828            case PackageManager.INSTALL_SUCCEEDED: {
1829                extras = new Bundle();
1830                extras.putBoolean(Intent.EXTRA_REPLACING,
1831                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1832                break;
1833            }
1834        }
1835        return extras;
1836    }
1837
1838    void scheduleWriteSettingsLocked() {
1839        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1840            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1841        }
1842    }
1843
1844    void scheduleWritePackageRestrictionsLocked(int userId) {
1845        if (!sUserManager.exists(userId)) return;
1846        mDirtyUsers.add(userId);
1847        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1848            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1849        }
1850    }
1851
1852    public static PackageManagerService main(Context context, Installer installer,
1853            boolean factoryTest, boolean onlyCore) {
1854        PackageManagerService m = new PackageManagerService(context, installer,
1855                factoryTest, onlyCore);
1856        m.enableSystemUserPackages();
1857        ServiceManager.addService("package", m);
1858        return m;
1859    }
1860
1861    private void enableSystemUserPackages() {
1862        if (!UserManager.isSplitSystemUser()) {
1863            return;
1864        }
1865        // For system user, enable apps based on the following conditions:
1866        // - app is whitelisted or belong to one of these groups:
1867        //   -- system app which has no launcher icons
1868        //   -- system app which has INTERACT_ACROSS_USERS permission
1869        //   -- system IME app
1870        // - app is not in the blacklist
1871        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1872        Set<String> enableApps = new ArraySet<>();
1873        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1874                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1875                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1876        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1877        enableApps.addAll(wlApps);
1878        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1879                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1880        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1881        enableApps.removeAll(blApps);
1882        Log.i(TAG, "Applications installed for system user: " + enableApps);
1883        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1884                UserHandle.SYSTEM);
1885        final int allAppsSize = allAps.size();
1886        synchronized (mPackages) {
1887            for (int i = 0; i < allAppsSize; i++) {
1888                String pName = allAps.get(i);
1889                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1890                // Should not happen, but we shouldn't be failing if it does
1891                if (pkgSetting == null) {
1892                    continue;
1893                }
1894                boolean install = enableApps.contains(pName);
1895                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
1896                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
1897                            + " for system user");
1898                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
1899                }
1900            }
1901        }
1902    }
1903
1904    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1905        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1906                Context.DISPLAY_SERVICE);
1907        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1908    }
1909
1910    public PackageManagerService(Context context, Installer installer,
1911            boolean factoryTest, boolean onlyCore) {
1912        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1913                SystemClock.uptimeMillis());
1914
1915        if (mSdkVersion <= 0) {
1916            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1917        }
1918
1919        mContext = context;
1920        mFactoryTest = factoryTest;
1921        mOnlyCore = onlyCore;
1922        mMetrics = new DisplayMetrics();
1923        mSettings = new Settings(mPackages);
1924        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1925                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1926        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1927                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1928        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1929                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1930        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1931                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1932        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1933                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1934        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1935                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1936
1937        String separateProcesses = SystemProperties.get("debug.separate_processes");
1938        if (separateProcesses != null && separateProcesses.length() > 0) {
1939            if ("*".equals(separateProcesses)) {
1940                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1941                mSeparateProcesses = null;
1942                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1943            } else {
1944                mDefParseFlags = 0;
1945                mSeparateProcesses = separateProcesses.split(",");
1946                Slog.w(TAG, "Running with debug.separate_processes: "
1947                        + separateProcesses);
1948            }
1949        } else {
1950            mDefParseFlags = 0;
1951            mSeparateProcesses = null;
1952        }
1953
1954        mInstaller = installer;
1955        mPackageDexOptimizer = new PackageDexOptimizer(this);
1956        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1957
1958        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
1959                FgThread.get().getLooper());
1960
1961        getDefaultDisplayMetrics(context, mMetrics);
1962
1963        SystemConfig systemConfig = SystemConfig.getInstance();
1964        mGlobalGids = systemConfig.getGlobalGids();
1965        mSystemPermissions = systemConfig.getSystemPermissions();
1966        mAvailableFeatures = systemConfig.getAvailableFeatures();
1967
1968        synchronized (mInstallLock) {
1969        // writer
1970        synchronized (mPackages) {
1971            mHandlerThread = new ServiceThread(TAG,
1972                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1973            mHandlerThread.start();
1974            mHandler = new PackageHandler(mHandlerThread.getLooper());
1975            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1976
1977            File dataDir = Environment.getDataDirectory();
1978            mAppInstallDir = new File(dataDir, "app");
1979            mAppLib32InstallDir = new File(dataDir, "app-lib");
1980            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
1981            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1982            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1983
1984            sUserManager = new UserManagerService(context, this, mPackages);
1985
1986            // Propagate permission configuration in to package manager.
1987            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1988                    = systemConfig.getPermissions();
1989            for (int i=0; i<permConfig.size(); i++) {
1990                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1991                BasePermission bp = mSettings.mPermissions.get(perm.name);
1992                if (bp == null) {
1993                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1994                    mSettings.mPermissions.put(perm.name, bp);
1995                }
1996                if (perm.gids != null) {
1997                    bp.setGids(perm.gids, perm.perUser);
1998                }
1999            }
2000
2001            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2002            for (int i=0; i<libConfig.size(); i++) {
2003                mSharedLibraries.put(libConfig.keyAt(i),
2004                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2005            }
2006
2007            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2008
2009            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2010
2011            String customResolverActivity = Resources.getSystem().getString(
2012                    R.string.config_customResolverActivity);
2013            if (TextUtils.isEmpty(customResolverActivity)) {
2014                customResolverActivity = null;
2015            } else {
2016                mCustomResolverComponentName = ComponentName.unflattenFromString(
2017                        customResolverActivity);
2018            }
2019
2020            long startTime = SystemClock.uptimeMillis();
2021
2022            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2023                    startTime);
2024
2025            // Set flag to monitor and not change apk file paths when
2026            // scanning install directories.
2027            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2028
2029            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2030            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2031
2032            if (bootClassPath == null) {
2033                Slog.w(TAG, "No BOOTCLASSPATH found!");
2034            }
2035
2036            if (systemServerClassPath == null) {
2037                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2038            }
2039
2040            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2041            final String[] dexCodeInstructionSets =
2042                    getDexCodeInstructionSets(
2043                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2044
2045            /**
2046             * Ensure all external libraries have had dexopt run on them.
2047             */
2048            if (mSharedLibraries.size() > 0) {
2049                // NOTE: For now, we're compiling these system "shared libraries"
2050                // (and framework jars) into all available architectures. It's possible
2051                // to compile them only when we come across an app that uses them (there's
2052                // already logic for that in scanPackageLI) but that adds some complexity.
2053                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2054                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2055                        final String lib = libEntry.path;
2056                        if (lib == null) {
2057                            continue;
2058                        }
2059
2060                        try {
2061                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
2062                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2063                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2064                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/);
2065                            }
2066                        } catch (FileNotFoundException e) {
2067                            Slog.w(TAG, "Library not found: " + lib);
2068                        } catch (IOException e) {
2069                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2070                                    + e.getMessage());
2071                        }
2072                    }
2073                }
2074            }
2075
2076            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2077
2078            final VersionInfo ver = mSettings.getInternalVersion();
2079            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2080            // when upgrading from pre-M, promote system app permissions from install to runtime
2081            mPromoteSystemApps =
2082                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2083
2084            // save off the names of pre-existing system packages prior to scanning; we don't
2085            // want to automatically grant runtime permissions for new system apps
2086            if (mPromoteSystemApps) {
2087                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2088                while (pkgSettingIter.hasNext()) {
2089                    PackageSetting ps = pkgSettingIter.next();
2090                    if (isSystemApp(ps)) {
2091                        mExistingSystemPackages.add(ps.name);
2092                    }
2093                }
2094            }
2095
2096            // Collect vendor overlay packages.
2097            // (Do this before scanning any apps.)
2098            // For security and version matching reason, only consider
2099            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2100            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2101            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2102                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2103
2104            // Find base frameworks (resource packages without code).
2105            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2106                    | PackageParser.PARSE_IS_SYSTEM_DIR
2107                    | PackageParser.PARSE_IS_PRIVILEGED,
2108                    scanFlags | SCAN_NO_DEX, 0);
2109
2110            // Collected privileged system packages.
2111            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2112            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2113                    | PackageParser.PARSE_IS_SYSTEM_DIR
2114                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2115
2116            // Collect ordinary system packages.
2117            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2118            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2119                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2120
2121            // Collect all vendor packages.
2122            File vendorAppDir = new File("/vendor/app");
2123            try {
2124                vendorAppDir = vendorAppDir.getCanonicalFile();
2125            } catch (IOException e) {
2126                // failed to look up canonical path, continue with original one
2127            }
2128            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2129                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2130
2131            // Collect all OEM packages.
2132            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2133            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2134                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2135
2136            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
2137            mInstaller.moveFiles();
2138
2139            // Prune any system packages that no longer exist.
2140            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2141            if (!mOnlyCore) {
2142                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2143                while (psit.hasNext()) {
2144                    PackageSetting ps = psit.next();
2145
2146                    /*
2147                     * If this is not a system app, it can't be a
2148                     * disable system app.
2149                     */
2150                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2151                        continue;
2152                    }
2153
2154                    /*
2155                     * If the package is scanned, it's not erased.
2156                     */
2157                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2158                    if (scannedPkg != null) {
2159                        /*
2160                         * If the system app is both scanned and in the
2161                         * disabled packages list, then it must have been
2162                         * added via OTA. Remove it from the currently
2163                         * scanned package so the previously user-installed
2164                         * application can be scanned.
2165                         */
2166                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2167                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2168                                    + ps.name + "; removing system app.  Last known codePath="
2169                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2170                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2171                                    + scannedPkg.mVersionCode);
2172                            removePackageLI(ps, true);
2173                            mExpectingBetter.put(ps.name, ps.codePath);
2174                        }
2175
2176                        continue;
2177                    }
2178
2179                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2180                        psit.remove();
2181                        logCriticalInfo(Log.WARN, "System package " + ps.name
2182                                + " no longer exists; wiping its data");
2183                        removeDataDirsLI(null, ps.name);
2184                    } else {
2185                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2186                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2187                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2188                        }
2189                    }
2190                }
2191            }
2192
2193            //look for any incomplete package installations
2194            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2195            //clean up list
2196            for(int i = 0; i < deletePkgsList.size(); i++) {
2197                //clean up here
2198                cleanupInstallFailedPackage(deletePkgsList.get(i));
2199            }
2200            //delete tmp files
2201            deleteTempPackageFiles();
2202
2203            // Remove any shared userIDs that have no associated packages
2204            mSettings.pruneSharedUsersLPw();
2205
2206            if (!mOnlyCore) {
2207                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2208                        SystemClock.uptimeMillis());
2209                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2210
2211                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2212                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2213
2214                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2215                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2216
2217                /**
2218                 * Remove disable package settings for any updated system
2219                 * apps that were removed via an OTA. If they're not a
2220                 * previously-updated app, remove them completely.
2221                 * Otherwise, just revoke their system-level permissions.
2222                 */
2223                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2224                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2225                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2226
2227                    String msg;
2228                    if (deletedPkg == null) {
2229                        msg = "Updated system package " + deletedAppName
2230                                + " no longer exists; wiping its data";
2231                        removeDataDirsLI(null, deletedAppName);
2232                    } else {
2233                        msg = "Updated system app + " + deletedAppName
2234                                + " no longer present; removing system privileges for "
2235                                + deletedAppName;
2236
2237                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2238
2239                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2240                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2241                    }
2242                    logCriticalInfo(Log.WARN, msg);
2243                }
2244
2245                /**
2246                 * Make sure all system apps that we expected to appear on
2247                 * the userdata partition actually showed up. If they never
2248                 * appeared, crawl back and revive the system version.
2249                 */
2250                for (int i = 0; i < mExpectingBetter.size(); i++) {
2251                    final String packageName = mExpectingBetter.keyAt(i);
2252                    if (!mPackages.containsKey(packageName)) {
2253                        final File scanFile = mExpectingBetter.valueAt(i);
2254
2255                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2256                                + " but never showed up; reverting to system");
2257
2258                        final int reparseFlags;
2259                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2260                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2261                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2262                                    | PackageParser.PARSE_IS_PRIVILEGED;
2263                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2264                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2265                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2266                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2267                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2268                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2269                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2270                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2271                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2272                        } else {
2273                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2274                            continue;
2275                        }
2276
2277                        mSettings.enableSystemPackageLPw(packageName);
2278
2279                        try {
2280                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2281                        } catch (PackageManagerException e) {
2282                            Slog.e(TAG, "Failed to parse original system package: "
2283                                    + e.getMessage());
2284                        }
2285                    }
2286                }
2287            }
2288            mExpectingBetter.clear();
2289
2290            // Now that we know all of the shared libraries, update all clients to have
2291            // the correct library paths.
2292            updateAllSharedLibrariesLPw();
2293
2294            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2295                // NOTE: We ignore potential failures here during a system scan (like
2296                // the rest of the commands above) because there's precious little we
2297                // can do about it. A settings error is reported, though.
2298                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
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, StorageManager.UUID_PRIVATE_INTERNAL, 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            if (!mOnlyCore) {
2367                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2368                mRequiredInstallerPackage = getRequiredInstallerLPr();
2369                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2370                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2371                        mIntentFilterVerifierComponent);
2372            } else {
2373                mRequiredVerifierPackage = null;
2374                mRequiredInstallerPackage = null;
2375                mIntentFilterVerifierComponent = null;
2376                mIntentFilterVerifier = null;
2377            }
2378
2379            mInstallerService = new PackageInstallerService(context, this);
2380
2381            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2382            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2383            // both the installer and resolver must be present to enable ephemeral
2384            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2385                if (DEBUG_EPHEMERAL) {
2386                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2387                            + " installer:" + ephemeralInstallerComponent);
2388                }
2389                mEphemeralResolverComponent = ephemeralResolverComponent;
2390                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2391                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2392                mEphemeralResolverConnection =
2393                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2394            } else {
2395                if (DEBUG_EPHEMERAL) {
2396                    final String missingComponent =
2397                            (ephemeralResolverComponent == null)
2398                            ? (ephemeralInstallerComponent == null)
2399                                    ? "resolver and installer"
2400                                    : "resolver"
2401                            : "installer";
2402                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2403                }
2404                mEphemeralResolverComponent = null;
2405                mEphemeralInstallerComponent = null;
2406                mEphemeralResolverConnection = null;
2407            }
2408
2409            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2410        } // synchronized (mPackages)
2411        } // synchronized (mInstallLock)
2412
2413        // Now after opening every single application zip, make sure they
2414        // are all flushed.  Not really needed, but keeps things nice and
2415        // tidy.
2416        Runtime.getRuntime().gc();
2417
2418        // The initial scanning above does many calls into installd while
2419        // holding the mPackages lock, but we're mostly interested in yelling
2420        // once we have a booted system.
2421        mInstaller.setWarnIfHeld(mPackages);
2422
2423        // Expose private service for system components to use.
2424        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2425    }
2426
2427    @Override
2428    public boolean isFirstBoot() {
2429        return !mRestoredSettings;
2430    }
2431
2432    @Override
2433    public boolean isOnlyCoreApps() {
2434        return mOnlyCore;
2435    }
2436
2437    @Override
2438    public boolean isUpgrade() {
2439        return mIsUpgrade;
2440    }
2441
2442    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2443        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2444
2445        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2446                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2447        if (matches.size() == 1) {
2448            return matches.get(0).getComponentInfo().packageName;
2449        } else {
2450            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2451            return null;
2452        }
2453    }
2454
2455    private @NonNull String getRequiredInstallerLPr() {
2456        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2457        intent.addCategory(Intent.CATEGORY_DEFAULT);
2458        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2459
2460        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2461                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2462        if (matches.size() == 1) {
2463            return matches.get(0).getComponentInfo().packageName;
2464        } else {
2465            throw new RuntimeException("There must be exactly one installer; found " + matches);
2466        }
2467    }
2468
2469    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2470        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2471
2472        final List<ResolveInfo> matches = queryIntentReceivers(intent, PACKAGE_MIME_TYPE,
2473                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2474        ResolveInfo best = null;
2475        final int N = matches.size();
2476        for (int i = 0; i < N; i++) {
2477            final ResolveInfo cur = matches.get(i);
2478            final String packageName = cur.getComponentInfo().packageName;
2479            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2480                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2481                continue;
2482            }
2483
2484            if (best == null || cur.priority > best.priority) {
2485                best = cur;
2486            }
2487        }
2488
2489        if (best != null) {
2490            return best.getComponentInfo().getComponentName();
2491        } else {
2492            throw new RuntimeException("There must be at least one intent filter verifier");
2493        }
2494    }
2495
2496    private @Nullable ComponentName getEphemeralResolverLPr() {
2497        final String[] packageArray =
2498                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2499        if (packageArray.length == 0) {
2500            if (DEBUG_EPHEMERAL) {
2501                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2502            }
2503            return null;
2504        }
2505
2506        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2507        final List<ResolveInfo> resolvers = queryIntentServices(resolverIntent, null,
2508                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2509
2510        final int N = resolvers.size();
2511        if (N == 0) {
2512            if (DEBUG_EPHEMERAL) {
2513                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2514            }
2515            return null;
2516        }
2517
2518        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2519        for (int i = 0; i < N; i++) {
2520            final ResolveInfo info = resolvers.get(i);
2521
2522            if (info.serviceInfo == null) {
2523                continue;
2524            }
2525
2526            final String packageName = info.serviceInfo.packageName;
2527            if (!possiblePackages.contains(packageName)) {
2528                if (DEBUG_EPHEMERAL) {
2529                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2530                            + " pkg: " + packageName + ", info:" + info);
2531                }
2532                continue;
2533            }
2534
2535            if (DEBUG_EPHEMERAL) {
2536                Slog.v(TAG, "Ephemeral resolver found;"
2537                        + " pkg: " + packageName + ", info:" + info);
2538            }
2539            return new ComponentName(packageName, info.serviceInfo.name);
2540        }
2541        if (DEBUG_EPHEMERAL) {
2542            Slog.v(TAG, "Ephemeral resolver NOT found");
2543        }
2544        return null;
2545    }
2546
2547    private @Nullable ComponentName getEphemeralInstallerLPr() {
2548        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2549        intent.addCategory(Intent.CATEGORY_DEFAULT);
2550        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2551
2552        final List<ResolveInfo> matches = queryIntentActivities(intent, PACKAGE_MIME_TYPE,
2553                MATCH_SYSTEM_ONLY | MATCH_ENCRYPTION_AWARE_AND_UNAWARE, UserHandle.USER_SYSTEM);
2554        if (matches.size() == 0) {
2555            return null;
2556        } else if (matches.size() == 1) {
2557            return matches.get(0).getComponentInfo().getComponentName();
2558        } else {
2559            throw new RuntimeException(
2560                    "There must be at most one ephemeral installer; found " + matches);
2561        }
2562    }
2563
2564    private void primeDomainVerificationsLPw(int userId) {
2565        if (DEBUG_DOMAIN_VERIFICATION) {
2566            Slog.d(TAG, "Priming domain verifications in user " + userId);
2567        }
2568
2569        SystemConfig systemConfig = SystemConfig.getInstance();
2570        ArraySet<String> packages = systemConfig.getLinkedApps();
2571        ArraySet<String> domains = new ArraySet<String>();
2572
2573        for (String packageName : packages) {
2574            PackageParser.Package pkg = mPackages.get(packageName);
2575            if (pkg != null) {
2576                if (!pkg.isSystemApp()) {
2577                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2578                    continue;
2579                }
2580
2581                domains.clear();
2582                for (PackageParser.Activity a : pkg.activities) {
2583                    for (ActivityIntentInfo filter : a.intents) {
2584                        if (hasValidDomains(filter)) {
2585                            domains.addAll(filter.getHostsList());
2586                        }
2587                    }
2588                }
2589
2590                if (domains.size() > 0) {
2591                    if (DEBUG_DOMAIN_VERIFICATION) {
2592                        Slog.v(TAG, "      + " + packageName);
2593                    }
2594                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2595                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2596                    // and then 'always' in the per-user state actually used for intent resolution.
2597                    final IntentFilterVerificationInfo ivi;
2598                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2599                            new ArrayList<String>(domains));
2600                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2601                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2602                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2603                } else {
2604                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2605                            + "' does not handle web links");
2606                }
2607            } else {
2608                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2609            }
2610        }
2611
2612        scheduleWritePackageRestrictionsLocked(userId);
2613        scheduleWriteSettingsLocked();
2614    }
2615
2616    private void applyFactoryDefaultBrowserLPw(int userId) {
2617        // The default browser app's package name is stored in a string resource,
2618        // with a product-specific overlay used for vendor customization.
2619        String browserPkg = mContext.getResources().getString(
2620                com.android.internal.R.string.default_browser);
2621        if (!TextUtils.isEmpty(browserPkg)) {
2622            // non-empty string => required to be a known package
2623            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2624            if (ps == null) {
2625                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2626                browserPkg = null;
2627            } else {
2628                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2629            }
2630        }
2631
2632        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2633        // default.  If there's more than one, just leave everything alone.
2634        if (browserPkg == null) {
2635            calculateDefaultBrowserLPw(userId);
2636        }
2637    }
2638
2639    private void calculateDefaultBrowserLPw(int userId) {
2640        List<String> allBrowsers = resolveAllBrowserApps(userId);
2641        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2642        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2643    }
2644
2645    private List<String> resolveAllBrowserApps(int userId) {
2646        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2647        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2648                PackageManager.MATCH_ALL, userId);
2649
2650        final int count = list.size();
2651        List<String> result = new ArrayList<String>(count);
2652        for (int i=0; i<count; i++) {
2653            ResolveInfo info = list.get(i);
2654            if (info.activityInfo == null
2655                    || !info.handleAllWebDataURI
2656                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2657                    || result.contains(info.activityInfo.packageName)) {
2658                continue;
2659            }
2660            result.add(info.activityInfo.packageName);
2661        }
2662
2663        return result;
2664    }
2665
2666    private boolean packageIsBrowser(String packageName, int userId) {
2667        List<ResolveInfo> list = queryIntentActivities(sBrowserIntent, null,
2668                PackageManager.MATCH_ALL, userId);
2669        final int N = list.size();
2670        for (int i = 0; i < N; i++) {
2671            ResolveInfo info = list.get(i);
2672            if (packageName.equals(info.activityInfo.packageName)) {
2673                return true;
2674            }
2675        }
2676        return false;
2677    }
2678
2679    private void checkDefaultBrowser() {
2680        final int myUserId = UserHandle.myUserId();
2681        final String packageName = getDefaultBrowserPackageName(myUserId);
2682        if (packageName != null) {
2683            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2684            if (info == null) {
2685                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2686                synchronized (mPackages) {
2687                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2688                }
2689            }
2690        }
2691    }
2692
2693    @Override
2694    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2695            throws RemoteException {
2696        try {
2697            return super.onTransact(code, data, reply, flags);
2698        } catch (RuntimeException e) {
2699            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2700                Slog.wtf(TAG, "Package Manager Crash", e);
2701            }
2702            throw e;
2703        }
2704    }
2705
2706    void cleanupInstallFailedPackage(PackageSetting ps) {
2707        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2708
2709        removeDataDirsLI(ps.volumeUuid, ps.name);
2710        if (ps.codePath != null) {
2711            if (ps.codePath.isDirectory()) {
2712                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2713            } else {
2714                ps.codePath.delete();
2715            }
2716        }
2717        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2718            if (ps.resourcePath.isDirectory()) {
2719                FileUtils.deleteContents(ps.resourcePath);
2720            }
2721            ps.resourcePath.delete();
2722        }
2723        mSettings.removePackageLPw(ps.name);
2724    }
2725
2726    static int[] appendInts(int[] cur, int[] add) {
2727        if (add == null) return cur;
2728        if (cur == null) return add;
2729        final int N = add.length;
2730        for (int i=0; i<N; i++) {
2731            cur = appendInt(cur, add[i]);
2732        }
2733        return cur;
2734    }
2735
2736    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2737        if (!sUserManager.exists(userId)) return null;
2738        final PackageSetting ps = (PackageSetting) p.mExtras;
2739        if (ps == null) {
2740            return null;
2741        }
2742
2743        final PermissionsState permissionsState = ps.getPermissionsState();
2744
2745        final int[] gids = permissionsState.computeGids(userId);
2746        final Set<String> permissions = permissionsState.getPermissions(userId);
2747        final PackageUserState state = ps.readUserState(userId);
2748
2749        return PackageParser.generatePackageInfo(p, gids, flags,
2750                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2751    }
2752
2753    @Override
2754    public void checkPackageStartable(String packageName, int userId) {
2755        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2756
2757        synchronized (mPackages) {
2758            final PackageSetting ps = mSettings.mPackages.get(packageName);
2759            if (ps == null) {
2760                throw new SecurityException("Package " + packageName + " was not found!");
2761            }
2762
2763            if (ps.frozen) {
2764                throw new SecurityException("Package " + packageName + " is currently frozen!");
2765            }
2766
2767            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isEncryptionAware()
2768                    || ps.pkg.applicationInfo.isPartiallyEncryptionAware())) {
2769                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2770            }
2771        }
2772    }
2773
2774    @Override
2775    public boolean isPackageAvailable(String packageName, int userId) {
2776        if (!sUserManager.exists(userId)) return false;
2777        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2778        synchronized (mPackages) {
2779            PackageParser.Package p = mPackages.get(packageName);
2780            if (p != null) {
2781                final PackageSetting ps = (PackageSetting) p.mExtras;
2782                if (ps != null) {
2783                    final PackageUserState state = ps.readUserState(userId);
2784                    if (state != null) {
2785                        return PackageParser.isAvailable(state);
2786                    }
2787                }
2788            }
2789        }
2790        return false;
2791    }
2792
2793    @Override
2794    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2795        if (!sUserManager.exists(userId)) return null;
2796        flags = updateFlagsForPackage(flags, userId, packageName);
2797        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2798        // reader
2799        synchronized (mPackages) {
2800            PackageParser.Package p = mPackages.get(packageName);
2801            if (DEBUG_PACKAGE_INFO)
2802                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2803            if (p != null) {
2804                return generatePackageInfo(p, flags, userId);
2805            }
2806            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2807                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2808            }
2809        }
2810        return null;
2811    }
2812
2813    @Override
2814    public String[] currentToCanonicalPackageNames(String[] names) {
2815        String[] out = new String[names.length];
2816        // reader
2817        synchronized (mPackages) {
2818            for (int i=names.length-1; i>=0; i--) {
2819                PackageSetting ps = mSettings.mPackages.get(names[i]);
2820                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2821            }
2822        }
2823        return out;
2824    }
2825
2826    @Override
2827    public String[] canonicalToCurrentPackageNames(String[] names) {
2828        String[] out = new String[names.length];
2829        // reader
2830        synchronized (mPackages) {
2831            for (int i=names.length-1; i>=0; i--) {
2832                String cur = mSettings.mRenamedPackages.get(names[i]);
2833                out[i] = cur != null ? cur : names[i];
2834            }
2835        }
2836        return out;
2837    }
2838
2839    @Override
2840    public int getPackageUid(String packageName, int flags, int userId) {
2841        if (!sUserManager.exists(userId)) return -1;
2842        flags = updateFlagsForPackage(flags, userId, packageName);
2843        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2844
2845        // reader
2846        synchronized (mPackages) {
2847            final PackageParser.Package p = mPackages.get(packageName);
2848            if (p != null && p.isMatch(flags)) {
2849                return UserHandle.getUid(userId, p.applicationInfo.uid);
2850            }
2851            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2852                final PackageSetting ps = mSettings.mPackages.get(packageName);
2853                if (ps != null && ps.isMatch(flags)) {
2854                    return UserHandle.getUid(userId, ps.appId);
2855                }
2856            }
2857        }
2858
2859        return -1;
2860    }
2861
2862    @Override
2863    public int[] getPackageGids(String packageName, int flags, int userId) {
2864        if (!sUserManager.exists(userId)) return null;
2865        flags = updateFlagsForPackage(flags, userId, packageName);
2866        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2867                "getPackageGids");
2868
2869        // reader
2870        synchronized (mPackages) {
2871            final PackageParser.Package p = mPackages.get(packageName);
2872            if (p != null && p.isMatch(flags)) {
2873                PackageSetting ps = (PackageSetting) p.mExtras;
2874                return ps.getPermissionsState().computeGids(userId);
2875            }
2876            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2877                final PackageSetting ps = mSettings.mPackages.get(packageName);
2878                if (ps != null && ps.isMatch(flags)) {
2879                    return ps.getPermissionsState().computeGids(userId);
2880                }
2881            }
2882        }
2883
2884        return null;
2885    }
2886
2887    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
2888        if (bp.perm != null) {
2889            return PackageParser.generatePermissionInfo(bp.perm, flags);
2890        }
2891        PermissionInfo pi = new PermissionInfo();
2892        pi.name = bp.name;
2893        pi.packageName = bp.sourcePackage;
2894        pi.nonLocalizedLabel = bp.name;
2895        pi.protectionLevel = bp.protectionLevel;
2896        return pi;
2897    }
2898
2899    @Override
2900    public PermissionInfo getPermissionInfo(String name, int flags) {
2901        // reader
2902        synchronized (mPackages) {
2903            final BasePermission p = mSettings.mPermissions.get(name);
2904            if (p != null) {
2905                return generatePermissionInfo(p, flags);
2906            }
2907            return null;
2908        }
2909    }
2910
2911    @Override
2912    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2913        // reader
2914        synchronized (mPackages) {
2915            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2916            for (BasePermission p : mSettings.mPermissions.values()) {
2917                if (group == null) {
2918                    if (p.perm == null || p.perm.info.group == null) {
2919                        out.add(generatePermissionInfo(p, flags));
2920                    }
2921                } else {
2922                    if (p.perm != null && group.equals(p.perm.info.group)) {
2923                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2924                    }
2925                }
2926            }
2927
2928            if (out.size() > 0) {
2929                return out;
2930            }
2931            return mPermissionGroups.containsKey(group) ? out : null;
2932        }
2933    }
2934
2935    @Override
2936    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2937        // reader
2938        synchronized (mPackages) {
2939            return PackageParser.generatePermissionGroupInfo(
2940                    mPermissionGroups.get(name), flags);
2941        }
2942    }
2943
2944    @Override
2945    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2946        // reader
2947        synchronized (mPackages) {
2948            final int N = mPermissionGroups.size();
2949            ArrayList<PermissionGroupInfo> out
2950                    = new ArrayList<PermissionGroupInfo>(N);
2951            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2952                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2953            }
2954            return out;
2955        }
2956    }
2957
2958    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2959            int userId) {
2960        if (!sUserManager.exists(userId)) return null;
2961        PackageSetting ps = mSettings.mPackages.get(packageName);
2962        if (ps != null) {
2963            if (ps.pkg == null) {
2964                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2965                        flags, userId);
2966                if (pInfo != null) {
2967                    return pInfo.applicationInfo;
2968                }
2969                return null;
2970            }
2971            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2972                    ps.readUserState(userId), userId);
2973        }
2974        return null;
2975    }
2976
2977    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2978            int userId) {
2979        if (!sUserManager.exists(userId)) return null;
2980        PackageSetting ps = mSettings.mPackages.get(packageName);
2981        if (ps != null) {
2982            PackageParser.Package pkg = ps.pkg;
2983            if (pkg == null) {
2984                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
2985                    return null;
2986                }
2987                // Only data remains, so we aren't worried about code paths
2988                pkg = new PackageParser.Package(packageName);
2989                pkg.applicationInfo.packageName = packageName;
2990                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2991                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2992                pkg.applicationInfo.uid = ps.appId;
2993                pkg.applicationInfo.initForUser(userId);
2994                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2995                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2996            }
2997            return generatePackageInfo(pkg, flags, userId);
2998        }
2999        return null;
3000    }
3001
3002    @Override
3003    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3004        if (!sUserManager.exists(userId)) return null;
3005        flags = updateFlagsForApplication(flags, userId, packageName);
3006        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
3007        // writer
3008        synchronized (mPackages) {
3009            PackageParser.Package p = mPackages.get(packageName);
3010            if (DEBUG_PACKAGE_INFO) Log.v(
3011                    TAG, "getApplicationInfo " + packageName
3012                    + ": " + p);
3013            if (p != null) {
3014                PackageSetting ps = mSettings.mPackages.get(packageName);
3015                if (ps == null) return null;
3016                // Note: isEnabledLP() does not apply here - always return info
3017                return PackageParser.generateApplicationInfo(
3018                        p, flags, ps.readUserState(userId), userId);
3019            }
3020            if ("android".equals(packageName)||"system".equals(packageName)) {
3021                return mAndroidApplication;
3022            }
3023            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3024                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3025            }
3026        }
3027        return null;
3028    }
3029
3030    @Override
3031    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3032            final IPackageDataObserver observer) {
3033        mContext.enforceCallingOrSelfPermission(
3034                android.Manifest.permission.CLEAR_APP_CACHE, null);
3035        // Queue up an async operation since clearing cache may take a little while.
3036        mHandler.post(new Runnable() {
3037            public void run() {
3038                mHandler.removeCallbacks(this);
3039                int retCode = -1;
3040                synchronized (mInstallLock) {
3041                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3042                    if (retCode < 0) {
3043                        Slog.w(TAG, "Couldn't clear application caches");
3044                    }
3045                }
3046                if (observer != null) {
3047                    try {
3048                        observer.onRemoveCompleted(null, (retCode >= 0));
3049                    } catch (RemoteException e) {
3050                        Slog.w(TAG, "RemoveException when invoking call back");
3051                    }
3052                }
3053            }
3054        });
3055    }
3056
3057    @Override
3058    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3059            final IntentSender pi) {
3060        mContext.enforceCallingOrSelfPermission(
3061                android.Manifest.permission.CLEAR_APP_CACHE, null);
3062        // Queue up an async operation since clearing cache may take a little while.
3063        mHandler.post(new Runnable() {
3064            public void run() {
3065                mHandler.removeCallbacks(this);
3066                int retCode = -1;
3067                synchronized (mInstallLock) {
3068                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
3069                    if (retCode < 0) {
3070                        Slog.w(TAG, "Couldn't clear application caches");
3071                    }
3072                }
3073                if(pi != null) {
3074                    try {
3075                        // Callback via pending intent
3076                        int code = (retCode >= 0) ? 1 : 0;
3077                        pi.sendIntent(null, code, null,
3078                                null, null);
3079                    } catch (SendIntentException e1) {
3080                        Slog.i(TAG, "Failed to send pending intent");
3081                    }
3082                }
3083            }
3084        });
3085    }
3086
3087    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3088        synchronized (mInstallLock) {
3089            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
3090                throw new IOException("Failed to free enough space");
3091            }
3092        }
3093    }
3094
3095    /**
3096     * Return if the user key is currently unlocked.
3097     */
3098    private boolean isUserKeyUnlocked(int userId) {
3099        if (StorageManager.isFileBasedEncryptionEnabled()) {
3100            final IMountService mount = IMountService.Stub
3101                    .asInterface(ServiceManager.getService("mount"));
3102            if (mount == null) {
3103                Slog.w(TAG, "Early during boot, assuming locked");
3104                return false;
3105            }
3106            final long token = Binder.clearCallingIdentity();
3107            try {
3108                return mount.isUserKeyUnlocked(userId);
3109            } catch (RemoteException e) {
3110                throw e.rethrowAsRuntimeException();
3111            } finally {
3112                Binder.restoreCallingIdentity(token);
3113            }
3114        } else {
3115            return true;
3116        }
3117    }
3118
3119    /**
3120     * Update given flags based on encryption status of current user.
3121     */
3122    private int updateFlagsForEncryption(int flags, int userId) {
3123        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3124                | PackageManager.MATCH_ENCRYPTION_AWARE)) != 0) {
3125            // Caller expressed an explicit opinion about what encryption
3126            // aware/unaware components they want to see, so fall through and
3127            // give them what they want
3128        } else {
3129            // Caller expressed no opinion, so match based on user state
3130            if (isUserKeyUnlocked(userId)) {
3131                flags |= PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE;
3132            } else {
3133                flags |= PackageManager.MATCH_ENCRYPTION_AWARE;
3134            }
3135        }
3136        return flags;
3137    }
3138
3139    /**
3140     * Update given flags when being used to request {@link PackageInfo}.
3141     */
3142    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3143        boolean triaged = true;
3144        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3145                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3146            // Caller is asking for component details, so they'd better be
3147            // asking for specific encryption matching behavior, or be triaged
3148            if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3149                    | PackageManager.MATCH_ENCRYPTION_AWARE
3150                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3151                triaged = false;
3152            }
3153        }
3154        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3155                | PackageManager.MATCH_SYSTEM_ONLY
3156                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3157            triaged = false;
3158        }
3159        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3160            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3161                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3162        }
3163        return updateFlagsForEncryption(flags, userId);
3164    }
3165
3166    /**
3167     * Update given flags when being used to request {@link ApplicationInfo}.
3168     */
3169    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3170        return updateFlagsForPackage(flags, userId, cookie);
3171    }
3172
3173    /**
3174     * Update given flags when being used to request {@link ComponentInfo}.
3175     */
3176    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3177        if (cookie instanceof Intent) {
3178            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3179                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3180            }
3181        }
3182
3183        boolean triaged = true;
3184        // Caller is asking for component details, so they'd better be
3185        // asking for specific encryption matching behavior, or be triaged
3186        if ((flags & (PackageManager.MATCH_ENCRYPTION_UNAWARE
3187                | PackageManager.MATCH_ENCRYPTION_AWARE
3188                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3189            triaged = false;
3190        }
3191        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3192            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3193                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3194        }
3195        return updateFlagsForEncryption(flags, userId);
3196    }
3197
3198    /**
3199     * Update given flags when being used to request {@link ResolveInfo}.
3200     */
3201    private int updateFlagsForResolve(int flags, int userId, Object cookie) {
3202        return updateFlagsForComponent(flags, userId, cookie);
3203    }
3204
3205    @Override
3206    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3207        if (!sUserManager.exists(userId)) return null;
3208        flags = updateFlagsForComponent(flags, userId, component);
3209        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
3210        synchronized (mPackages) {
3211            PackageParser.Activity a = mActivities.mActivities.get(component);
3212
3213            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3214            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3215                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3216                if (ps == null) return null;
3217                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3218                        userId);
3219            }
3220            if (mResolveComponentName.equals(component)) {
3221                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3222                        new PackageUserState(), userId);
3223            }
3224        }
3225        return null;
3226    }
3227
3228    @Override
3229    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3230            String resolvedType) {
3231        synchronized (mPackages) {
3232            if (component.equals(mResolveComponentName)) {
3233                // The resolver supports EVERYTHING!
3234                return true;
3235            }
3236            PackageParser.Activity a = mActivities.mActivities.get(component);
3237            if (a == null) {
3238                return false;
3239            }
3240            for (int i=0; i<a.intents.size(); i++) {
3241                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3242                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3243                    return true;
3244                }
3245            }
3246            return false;
3247        }
3248    }
3249
3250    @Override
3251    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3252        if (!sUserManager.exists(userId)) return null;
3253        flags = updateFlagsForComponent(flags, userId, component);
3254        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
3255        synchronized (mPackages) {
3256            PackageParser.Activity a = mReceivers.mActivities.get(component);
3257            if (DEBUG_PACKAGE_INFO) Log.v(
3258                TAG, "getReceiverInfo " + component + ": " + a);
3259            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3260                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3261                if (ps == null) return null;
3262                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3263                        userId);
3264            }
3265        }
3266        return null;
3267    }
3268
3269    @Override
3270    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3271        if (!sUserManager.exists(userId)) return null;
3272        flags = updateFlagsForComponent(flags, userId, component);
3273        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
3274        synchronized (mPackages) {
3275            PackageParser.Service s = mServices.mServices.get(component);
3276            if (DEBUG_PACKAGE_INFO) Log.v(
3277                TAG, "getServiceInfo " + component + ": " + s);
3278            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3279                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3280                if (ps == null) return null;
3281                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3282                        userId);
3283            }
3284        }
3285        return null;
3286    }
3287
3288    @Override
3289    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3290        if (!sUserManager.exists(userId)) return null;
3291        flags = updateFlagsForComponent(flags, userId, component);
3292        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
3293        synchronized (mPackages) {
3294            PackageParser.Provider p = mProviders.mProviders.get(component);
3295            if (DEBUG_PACKAGE_INFO) Log.v(
3296                TAG, "getProviderInfo " + component + ": " + p);
3297            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3298                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3299                if (ps == null) return null;
3300                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3301                        userId);
3302            }
3303        }
3304        return null;
3305    }
3306
3307    @Override
3308    public String[] getSystemSharedLibraryNames() {
3309        Set<String> libSet;
3310        synchronized (mPackages) {
3311            libSet = mSharedLibraries.keySet();
3312            int size = libSet.size();
3313            if (size > 0) {
3314                String[] libs = new String[size];
3315                libSet.toArray(libs);
3316                return libs;
3317            }
3318        }
3319        return null;
3320    }
3321
3322    /**
3323     * @hide
3324     */
3325    PackageParser.Package findSharedNonSystemLibrary(String libName) {
3326        synchronized (mPackages) {
3327            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
3328            if (lib != null && lib.apk != null) {
3329                return mPackages.get(lib.apk);
3330            }
3331        }
3332        return null;
3333    }
3334
3335    @Override
3336    public FeatureInfo[] getSystemAvailableFeatures() {
3337        Collection<FeatureInfo> featSet;
3338        synchronized (mPackages) {
3339            featSet = mAvailableFeatures.values();
3340            int size = featSet.size();
3341            if (size > 0) {
3342                FeatureInfo[] features = new FeatureInfo[size+1];
3343                featSet.toArray(features);
3344                FeatureInfo fi = new FeatureInfo();
3345                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3346                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
3347                features[size] = fi;
3348                return features;
3349            }
3350        }
3351        return null;
3352    }
3353
3354    @Override
3355    public boolean hasSystemFeature(String name) {
3356        synchronized (mPackages) {
3357            return mAvailableFeatures.containsKey(name);
3358        }
3359    }
3360
3361    @Override
3362    public int checkPermission(String permName, String pkgName, int userId) {
3363        if (!sUserManager.exists(userId)) {
3364            return PackageManager.PERMISSION_DENIED;
3365        }
3366
3367        synchronized (mPackages) {
3368            final PackageParser.Package p = mPackages.get(pkgName);
3369            if (p != null && p.mExtras != null) {
3370                final PackageSetting ps = (PackageSetting) p.mExtras;
3371                final PermissionsState permissionsState = ps.getPermissionsState();
3372                if (permissionsState.hasPermission(permName, userId)) {
3373                    return PackageManager.PERMISSION_GRANTED;
3374                }
3375                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3376                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3377                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3378                    return PackageManager.PERMISSION_GRANTED;
3379                }
3380            }
3381        }
3382
3383        return PackageManager.PERMISSION_DENIED;
3384    }
3385
3386    @Override
3387    public int checkUidPermission(String permName, int uid) {
3388        final int userId = UserHandle.getUserId(uid);
3389
3390        if (!sUserManager.exists(userId)) {
3391            return PackageManager.PERMISSION_DENIED;
3392        }
3393
3394        synchronized (mPackages) {
3395            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3396            if (obj != null) {
3397                final SettingBase ps = (SettingBase) obj;
3398                final PermissionsState permissionsState = ps.getPermissionsState();
3399                if (permissionsState.hasPermission(permName, userId)) {
3400                    return PackageManager.PERMISSION_GRANTED;
3401                }
3402                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3403                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3404                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3405                    return PackageManager.PERMISSION_GRANTED;
3406                }
3407            } else {
3408                ArraySet<String> perms = mSystemPermissions.get(uid);
3409                if (perms != null) {
3410                    if (perms.contains(permName)) {
3411                        return PackageManager.PERMISSION_GRANTED;
3412                    }
3413                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3414                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3415                        return PackageManager.PERMISSION_GRANTED;
3416                    }
3417                }
3418            }
3419        }
3420
3421        return PackageManager.PERMISSION_DENIED;
3422    }
3423
3424    @Override
3425    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3426        if (UserHandle.getCallingUserId() != userId) {
3427            mContext.enforceCallingPermission(
3428                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3429                    "isPermissionRevokedByPolicy for user " + userId);
3430        }
3431
3432        if (checkPermission(permission, packageName, userId)
3433                == PackageManager.PERMISSION_GRANTED) {
3434            return false;
3435        }
3436
3437        final long identity = Binder.clearCallingIdentity();
3438        try {
3439            final int flags = getPermissionFlags(permission, packageName, userId);
3440            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3441        } finally {
3442            Binder.restoreCallingIdentity(identity);
3443        }
3444    }
3445
3446    @Override
3447    public String getPermissionControllerPackageName() {
3448        synchronized (mPackages) {
3449            return mRequiredInstallerPackage;
3450        }
3451    }
3452
3453    /**
3454     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3455     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3456     * @param checkShell TODO(yamasani):
3457     * @param message the message to log on security exception
3458     */
3459    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3460            boolean checkShell, String message) {
3461        if (userId < 0) {
3462            throw new IllegalArgumentException("Invalid userId " + userId);
3463        }
3464        if (checkShell) {
3465            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3466        }
3467        if (userId == UserHandle.getUserId(callingUid)) return;
3468        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3469            if (requireFullPermission) {
3470                mContext.enforceCallingOrSelfPermission(
3471                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3472            } else {
3473                try {
3474                    mContext.enforceCallingOrSelfPermission(
3475                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3476                } catch (SecurityException se) {
3477                    mContext.enforceCallingOrSelfPermission(
3478                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3479                }
3480            }
3481        }
3482    }
3483
3484    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3485        if (callingUid == Process.SHELL_UID) {
3486            if (userHandle >= 0
3487                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3488                throw new SecurityException("Shell does not have permission to access user "
3489                        + userHandle);
3490            } else if (userHandle < 0) {
3491                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3492                        + Debug.getCallers(3));
3493            }
3494        }
3495    }
3496
3497    private BasePermission findPermissionTreeLP(String permName) {
3498        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3499            if (permName.startsWith(bp.name) &&
3500                    permName.length() > bp.name.length() &&
3501                    permName.charAt(bp.name.length()) == '.') {
3502                return bp;
3503            }
3504        }
3505        return null;
3506    }
3507
3508    private BasePermission checkPermissionTreeLP(String permName) {
3509        if (permName != null) {
3510            BasePermission bp = findPermissionTreeLP(permName);
3511            if (bp != null) {
3512                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3513                    return bp;
3514                }
3515                throw new SecurityException("Calling uid "
3516                        + Binder.getCallingUid()
3517                        + " is not allowed to add to permission tree "
3518                        + bp.name + " owned by uid " + bp.uid);
3519            }
3520        }
3521        throw new SecurityException("No permission tree found for " + permName);
3522    }
3523
3524    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3525        if (s1 == null) {
3526            return s2 == null;
3527        }
3528        if (s2 == null) {
3529            return false;
3530        }
3531        if (s1.getClass() != s2.getClass()) {
3532            return false;
3533        }
3534        return s1.equals(s2);
3535    }
3536
3537    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3538        if (pi1.icon != pi2.icon) return false;
3539        if (pi1.logo != pi2.logo) return false;
3540        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3541        if (!compareStrings(pi1.name, pi2.name)) return false;
3542        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3543        // We'll take care of setting this one.
3544        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3545        // These are not currently stored in settings.
3546        //if (!compareStrings(pi1.group, pi2.group)) return false;
3547        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3548        //if (pi1.labelRes != pi2.labelRes) return false;
3549        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3550        return true;
3551    }
3552
3553    int permissionInfoFootprint(PermissionInfo info) {
3554        int size = info.name.length();
3555        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3556        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3557        return size;
3558    }
3559
3560    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3561        int size = 0;
3562        for (BasePermission perm : mSettings.mPermissions.values()) {
3563            if (perm.uid == tree.uid) {
3564                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3565            }
3566        }
3567        return size;
3568    }
3569
3570    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3571        // We calculate the max size of permissions defined by this uid and throw
3572        // if that plus the size of 'info' would exceed our stated maximum.
3573        if (tree.uid != Process.SYSTEM_UID) {
3574            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3575            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3576                throw new SecurityException("Permission tree size cap exceeded");
3577            }
3578        }
3579    }
3580
3581    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3582        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3583            throw new SecurityException("Label must be specified in permission");
3584        }
3585        BasePermission tree = checkPermissionTreeLP(info.name);
3586        BasePermission bp = mSettings.mPermissions.get(info.name);
3587        boolean added = bp == null;
3588        boolean changed = true;
3589        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3590        if (added) {
3591            enforcePermissionCapLocked(info, tree);
3592            bp = new BasePermission(info.name, tree.sourcePackage,
3593                    BasePermission.TYPE_DYNAMIC);
3594        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3595            throw new SecurityException(
3596                    "Not allowed to modify non-dynamic permission "
3597                    + info.name);
3598        } else {
3599            if (bp.protectionLevel == fixedLevel
3600                    && bp.perm.owner.equals(tree.perm.owner)
3601                    && bp.uid == tree.uid
3602                    && comparePermissionInfos(bp.perm.info, info)) {
3603                changed = false;
3604            }
3605        }
3606        bp.protectionLevel = fixedLevel;
3607        info = new PermissionInfo(info);
3608        info.protectionLevel = fixedLevel;
3609        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3610        bp.perm.info.packageName = tree.perm.info.packageName;
3611        bp.uid = tree.uid;
3612        if (added) {
3613            mSettings.mPermissions.put(info.name, bp);
3614        }
3615        if (changed) {
3616            if (!async) {
3617                mSettings.writeLPr();
3618            } else {
3619                scheduleWriteSettingsLocked();
3620            }
3621        }
3622        return added;
3623    }
3624
3625    @Override
3626    public boolean addPermission(PermissionInfo info) {
3627        synchronized (mPackages) {
3628            return addPermissionLocked(info, false);
3629        }
3630    }
3631
3632    @Override
3633    public boolean addPermissionAsync(PermissionInfo info) {
3634        synchronized (mPackages) {
3635            return addPermissionLocked(info, true);
3636        }
3637    }
3638
3639    @Override
3640    public void removePermission(String name) {
3641        synchronized (mPackages) {
3642            checkPermissionTreeLP(name);
3643            BasePermission bp = mSettings.mPermissions.get(name);
3644            if (bp != null) {
3645                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3646                    throw new SecurityException(
3647                            "Not allowed to modify non-dynamic permission "
3648                            + name);
3649                }
3650                mSettings.mPermissions.remove(name);
3651                mSettings.writeLPr();
3652            }
3653        }
3654    }
3655
3656    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3657            BasePermission bp) {
3658        int index = pkg.requestedPermissions.indexOf(bp.name);
3659        if (index == -1) {
3660            throw new SecurityException("Package " + pkg.packageName
3661                    + " has not requested permission " + bp.name);
3662        }
3663        if (!bp.isRuntime() && !bp.isDevelopment()) {
3664            throw new SecurityException("Permission " + bp.name
3665                    + " is not a changeable permission type");
3666        }
3667    }
3668
3669    @Override
3670    public void grantRuntimePermission(String packageName, String name, final int userId) {
3671        if (!sUserManager.exists(userId)) {
3672            Log.e(TAG, "No such user:" + userId);
3673            return;
3674        }
3675
3676        mContext.enforceCallingOrSelfPermission(
3677                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3678                "grantRuntimePermission");
3679
3680        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3681                "grantRuntimePermission");
3682
3683        final int uid;
3684        final SettingBase sb;
3685
3686        synchronized (mPackages) {
3687            final PackageParser.Package pkg = mPackages.get(packageName);
3688            if (pkg == null) {
3689                throw new IllegalArgumentException("Unknown package: " + packageName);
3690            }
3691
3692            final BasePermission bp = mSettings.mPermissions.get(name);
3693            if (bp == null) {
3694                throw new IllegalArgumentException("Unknown permission: " + name);
3695            }
3696
3697            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3698
3699            // If a permission review is required for legacy apps we represent
3700            // their permissions as always granted runtime ones since we need
3701            // to keep the review required permission flag per user while an
3702            // install permission's state is shared across all users.
3703            if (Build.PERMISSIONS_REVIEW_REQUIRED
3704                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3705                    && bp.isRuntime()) {
3706                return;
3707            }
3708
3709            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3710            sb = (SettingBase) pkg.mExtras;
3711            if (sb == null) {
3712                throw new IllegalArgumentException("Unknown package: " + packageName);
3713            }
3714
3715            final PermissionsState permissionsState = sb.getPermissionsState();
3716
3717            final int flags = permissionsState.getPermissionFlags(name, userId);
3718            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3719                throw new SecurityException("Cannot grant system fixed permission "
3720                        + name + " for package " + packageName);
3721            }
3722
3723            if (bp.isDevelopment()) {
3724                // Development permissions must be handled specially, since they are not
3725                // normal runtime permissions.  For now they apply to all users.
3726                if (permissionsState.grantInstallPermission(bp) !=
3727                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3728                    scheduleWriteSettingsLocked();
3729                }
3730                return;
3731            }
3732
3733            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3734                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3735                return;
3736            }
3737
3738            final int result = permissionsState.grantRuntimePermission(bp, userId);
3739            switch (result) {
3740                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3741                    return;
3742                }
3743
3744                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3745                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3746                    mHandler.post(new Runnable() {
3747                        @Override
3748                        public void run() {
3749                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3750                        }
3751                    });
3752                }
3753                break;
3754            }
3755
3756            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3757
3758            // Not critical if that is lost - app has to request again.
3759            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3760        }
3761
3762        // Only need to do this if user is initialized. Otherwise it's a new user
3763        // and there are no processes running as the user yet and there's no need
3764        // to make an expensive call to remount processes for the changed permissions.
3765        if (READ_EXTERNAL_STORAGE.equals(name)
3766                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3767            final long token = Binder.clearCallingIdentity();
3768            try {
3769                if (sUserManager.isInitialized(userId)) {
3770                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3771                            MountServiceInternal.class);
3772                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3773                }
3774            } finally {
3775                Binder.restoreCallingIdentity(token);
3776            }
3777        }
3778    }
3779
3780    @Override
3781    public void revokeRuntimePermission(String packageName, String name, int userId) {
3782        if (!sUserManager.exists(userId)) {
3783            Log.e(TAG, "No such user:" + userId);
3784            return;
3785        }
3786
3787        mContext.enforceCallingOrSelfPermission(
3788                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3789                "revokeRuntimePermission");
3790
3791        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3792                "revokeRuntimePermission");
3793
3794        final int appId;
3795
3796        synchronized (mPackages) {
3797            final PackageParser.Package pkg = mPackages.get(packageName);
3798            if (pkg == null) {
3799                throw new IllegalArgumentException("Unknown package: " + packageName);
3800            }
3801
3802            final BasePermission bp = mSettings.mPermissions.get(name);
3803            if (bp == null) {
3804                throw new IllegalArgumentException("Unknown permission: " + name);
3805            }
3806
3807            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3808
3809            // If a permission review is required for legacy apps we represent
3810            // their permissions as always granted runtime ones since we need
3811            // to keep the review required permission flag per user while an
3812            // install permission's state is shared across all users.
3813            if (Build.PERMISSIONS_REVIEW_REQUIRED
3814                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3815                    && bp.isRuntime()) {
3816                return;
3817            }
3818
3819            SettingBase sb = (SettingBase) pkg.mExtras;
3820            if (sb == null) {
3821                throw new IllegalArgumentException("Unknown package: " + packageName);
3822            }
3823
3824            final PermissionsState permissionsState = sb.getPermissionsState();
3825
3826            final int flags = permissionsState.getPermissionFlags(name, userId);
3827            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3828                throw new SecurityException("Cannot revoke system fixed permission "
3829                        + name + " for package " + packageName);
3830            }
3831
3832            if (bp.isDevelopment()) {
3833                // Development permissions must be handled specially, since they are not
3834                // normal runtime permissions.  For now they apply to all users.
3835                if (permissionsState.revokeInstallPermission(bp) !=
3836                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3837                    scheduleWriteSettingsLocked();
3838                }
3839                return;
3840            }
3841
3842            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3843                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3844                return;
3845            }
3846
3847            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3848
3849            // Critical, after this call app should never have the permission.
3850            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3851
3852            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3853        }
3854
3855        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3856    }
3857
3858    @Override
3859    public void resetRuntimePermissions() {
3860        mContext.enforceCallingOrSelfPermission(
3861                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3862                "revokeRuntimePermission");
3863
3864        int callingUid = Binder.getCallingUid();
3865        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3866            mContext.enforceCallingOrSelfPermission(
3867                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3868                    "resetRuntimePermissions");
3869        }
3870
3871        synchronized (mPackages) {
3872            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
3873            for (int userId : UserManagerService.getInstance().getUserIds()) {
3874                final int packageCount = mPackages.size();
3875                for (int i = 0; i < packageCount; i++) {
3876                    PackageParser.Package pkg = mPackages.valueAt(i);
3877                    if (!(pkg.mExtras instanceof PackageSetting)) {
3878                        continue;
3879                    }
3880                    PackageSetting ps = (PackageSetting) pkg.mExtras;
3881                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
3882                }
3883            }
3884        }
3885    }
3886
3887    @Override
3888    public int getPermissionFlags(String name, String packageName, int userId) {
3889        if (!sUserManager.exists(userId)) {
3890            return 0;
3891        }
3892
3893        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
3894
3895        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3896                "getPermissionFlags");
3897
3898        synchronized (mPackages) {
3899            final PackageParser.Package pkg = mPackages.get(packageName);
3900            if (pkg == null) {
3901                throw new IllegalArgumentException("Unknown package: " + packageName);
3902            }
3903
3904            final BasePermission bp = mSettings.mPermissions.get(name);
3905            if (bp == null) {
3906                throw new IllegalArgumentException("Unknown permission: " + name);
3907            }
3908
3909            SettingBase sb = (SettingBase) pkg.mExtras;
3910            if (sb == null) {
3911                throw new IllegalArgumentException("Unknown package: " + packageName);
3912            }
3913
3914            PermissionsState permissionsState = sb.getPermissionsState();
3915            return permissionsState.getPermissionFlags(name, userId);
3916        }
3917    }
3918
3919    @Override
3920    public void updatePermissionFlags(String name, String packageName, int flagMask,
3921            int flagValues, int userId) {
3922        if (!sUserManager.exists(userId)) {
3923            return;
3924        }
3925
3926        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
3927
3928        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3929                "updatePermissionFlags");
3930
3931        // Only the system can change these flags and nothing else.
3932        if (getCallingUid() != Process.SYSTEM_UID) {
3933            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3934            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3935            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3936            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
3937            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
3938        }
3939
3940        synchronized (mPackages) {
3941            final PackageParser.Package pkg = mPackages.get(packageName);
3942            if (pkg == null) {
3943                throw new IllegalArgumentException("Unknown package: " + packageName);
3944            }
3945
3946            final BasePermission bp = mSettings.mPermissions.get(name);
3947            if (bp == null) {
3948                throw new IllegalArgumentException("Unknown permission: " + name);
3949            }
3950
3951            SettingBase sb = (SettingBase) pkg.mExtras;
3952            if (sb == null) {
3953                throw new IllegalArgumentException("Unknown package: " + packageName);
3954            }
3955
3956            PermissionsState permissionsState = sb.getPermissionsState();
3957
3958            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
3959
3960            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3961                // Install and runtime permissions are stored in different places,
3962                // so figure out what permission changed and persist the change.
3963                if (permissionsState.getInstallPermissionState(name) != null) {
3964                    scheduleWriteSettingsLocked();
3965                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
3966                        || hadState) {
3967                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3968                }
3969            }
3970        }
3971    }
3972
3973    /**
3974     * Update the permission flags for all packages and runtime permissions of a user in order
3975     * to allow device or profile owner to remove POLICY_FIXED.
3976     */
3977    @Override
3978    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
3979        if (!sUserManager.exists(userId)) {
3980            return;
3981        }
3982
3983        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
3984
3985        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3986                "updatePermissionFlagsForAllApps");
3987
3988        // Only the system can change system fixed flags.
3989        if (getCallingUid() != Process.SYSTEM_UID) {
3990            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3991            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
3992        }
3993
3994        synchronized (mPackages) {
3995            boolean changed = false;
3996            final int packageCount = mPackages.size();
3997            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
3998                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
3999                SettingBase sb = (SettingBase) pkg.mExtras;
4000                if (sb == null) {
4001                    continue;
4002                }
4003                PermissionsState permissionsState = sb.getPermissionsState();
4004                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4005                        userId, flagMask, flagValues);
4006            }
4007            if (changed) {
4008                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4009            }
4010        }
4011    }
4012
4013    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4014        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4015                != PackageManager.PERMISSION_GRANTED
4016            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4017                != PackageManager.PERMISSION_GRANTED) {
4018            throw new SecurityException(message + " requires "
4019                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4020                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4021        }
4022    }
4023
4024    @Override
4025    public boolean shouldShowRequestPermissionRationale(String permissionName,
4026            String packageName, int userId) {
4027        if (UserHandle.getCallingUserId() != userId) {
4028            mContext.enforceCallingPermission(
4029                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4030                    "canShowRequestPermissionRationale for user " + userId);
4031        }
4032
4033        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4034        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4035            return false;
4036        }
4037
4038        if (checkPermission(permissionName, packageName, userId)
4039                == PackageManager.PERMISSION_GRANTED) {
4040            return false;
4041        }
4042
4043        final int flags;
4044
4045        final long identity = Binder.clearCallingIdentity();
4046        try {
4047            flags = getPermissionFlags(permissionName,
4048                    packageName, userId);
4049        } finally {
4050            Binder.restoreCallingIdentity(identity);
4051        }
4052
4053        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4054                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4055                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4056
4057        if ((flags & fixedFlags) != 0) {
4058            return false;
4059        }
4060
4061        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4062    }
4063
4064    @Override
4065    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4066        mContext.enforceCallingOrSelfPermission(
4067                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4068                "addOnPermissionsChangeListener");
4069
4070        synchronized (mPackages) {
4071            mOnPermissionChangeListeners.addListenerLocked(listener);
4072        }
4073    }
4074
4075    @Override
4076    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4077        synchronized (mPackages) {
4078            mOnPermissionChangeListeners.removeListenerLocked(listener);
4079        }
4080    }
4081
4082    @Override
4083    public boolean isProtectedBroadcast(String actionName) {
4084        synchronized (mPackages) {
4085            if (mProtectedBroadcasts.contains(actionName)) {
4086                return true;
4087            } else if (actionName != null) {
4088                // TODO: remove these terrible hacks
4089                if (actionName.startsWith("android.net.netmon.lingerExpired")
4090                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")) {
4091                    return true;
4092                }
4093            }
4094        }
4095        return false;
4096    }
4097
4098    @Override
4099    public int checkSignatures(String pkg1, String pkg2) {
4100        synchronized (mPackages) {
4101            final PackageParser.Package p1 = mPackages.get(pkg1);
4102            final PackageParser.Package p2 = mPackages.get(pkg2);
4103            if (p1 == null || p1.mExtras == null
4104                    || p2 == null || p2.mExtras == null) {
4105                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4106            }
4107            return compareSignatures(p1.mSignatures, p2.mSignatures);
4108        }
4109    }
4110
4111    @Override
4112    public int checkUidSignatures(int uid1, int uid2) {
4113        // Map to base uids.
4114        uid1 = UserHandle.getAppId(uid1);
4115        uid2 = UserHandle.getAppId(uid2);
4116        // reader
4117        synchronized (mPackages) {
4118            Signature[] s1;
4119            Signature[] s2;
4120            Object obj = mSettings.getUserIdLPr(uid1);
4121            if (obj != null) {
4122                if (obj instanceof SharedUserSetting) {
4123                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4124                } else if (obj instanceof PackageSetting) {
4125                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4126                } else {
4127                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4128                }
4129            } else {
4130                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4131            }
4132            obj = mSettings.getUserIdLPr(uid2);
4133            if (obj != null) {
4134                if (obj instanceof SharedUserSetting) {
4135                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4136                } else if (obj instanceof PackageSetting) {
4137                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4138                } else {
4139                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4140                }
4141            } else {
4142                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4143            }
4144            return compareSignatures(s1, s2);
4145        }
4146    }
4147
4148    private void killUid(int appId, int userId, String reason) {
4149        final long identity = Binder.clearCallingIdentity();
4150        try {
4151            IActivityManager am = ActivityManagerNative.getDefault();
4152            if (am != null) {
4153                try {
4154                    am.killUid(appId, userId, reason);
4155                } catch (RemoteException e) {
4156                    /* ignore - same process */
4157                }
4158            }
4159        } finally {
4160            Binder.restoreCallingIdentity(identity);
4161        }
4162    }
4163
4164    /**
4165     * Compares two sets of signatures. Returns:
4166     * <br />
4167     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4168     * <br />
4169     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4170     * <br />
4171     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4172     * <br />
4173     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4174     * <br />
4175     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4176     */
4177    static int compareSignatures(Signature[] s1, Signature[] s2) {
4178        if (s1 == null) {
4179            return s2 == null
4180                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4181                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4182        }
4183
4184        if (s2 == null) {
4185            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4186        }
4187
4188        if (s1.length != s2.length) {
4189            return PackageManager.SIGNATURE_NO_MATCH;
4190        }
4191
4192        // Since both signature sets are of size 1, we can compare without HashSets.
4193        if (s1.length == 1) {
4194            return s1[0].equals(s2[0]) ?
4195                    PackageManager.SIGNATURE_MATCH :
4196                    PackageManager.SIGNATURE_NO_MATCH;
4197        }
4198
4199        ArraySet<Signature> set1 = new ArraySet<Signature>();
4200        for (Signature sig : s1) {
4201            set1.add(sig);
4202        }
4203        ArraySet<Signature> set2 = new ArraySet<Signature>();
4204        for (Signature sig : s2) {
4205            set2.add(sig);
4206        }
4207        // Make sure s2 contains all signatures in s1.
4208        if (set1.equals(set2)) {
4209            return PackageManager.SIGNATURE_MATCH;
4210        }
4211        return PackageManager.SIGNATURE_NO_MATCH;
4212    }
4213
4214    /**
4215     * If the database version for this type of package (internal storage or
4216     * external storage) is less than the version where package signatures
4217     * were updated, return true.
4218     */
4219    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4220        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4221        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4222    }
4223
4224    /**
4225     * Used for backward compatibility to make sure any packages with
4226     * certificate chains get upgraded to the new style. {@code existingSigs}
4227     * will be in the old format (since they were stored on disk from before the
4228     * system upgrade) and {@code scannedSigs} will be in the newer format.
4229     */
4230    private int compareSignaturesCompat(PackageSignatures existingSigs,
4231            PackageParser.Package scannedPkg) {
4232        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4233            return PackageManager.SIGNATURE_NO_MATCH;
4234        }
4235
4236        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4237        for (Signature sig : existingSigs.mSignatures) {
4238            existingSet.add(sig);
4239        }
4240        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4241        for (Signature sig : scannedPkg.mSignatures) {
4242            try {
4243                Signature[] chainSignatures = sig.getChainSignatures();
4244                for (Signature chainSig : chainSignatures) {
4245                    scannedCompatSet.add(chainSig);
4246                }
4247            } catch (CertificateEncodingException e) {
4248                scannedCompatSet.add(sig);
4249            }
4250        }
4251        /*
4252         * Make sure the expanded scanned set contains all signatures in the
4253         * existing one.
4254         */
4255        if (scannedCompatSet.equals(existingSet)) {
4256            // Migrate the old signatures to the new scheme.
4257            existingSigs.assignSignatures(scannedPkg.mSignatures);
4258            // The new KeySets will be re-added later in the scanning process.
4259            synchronized (mPackages) {
4260                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4261            }
4262            return PackageManager.SIGNATURE_MATCH;
4263        }
4264        return PackageManager.SIGNATURE_NO_MATCH;
4265    }
4266
4267    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4268        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4269        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4270    }
4271
4272    private int compareSignaturesRecover(PackageSignatures existingSigs,
4273            PackageParser.Package scannedPkg) {
4274        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4275            return PackageManager.SIGNATURE_NO_MATCH;
4276        }
4277
4278        String msg = null;
4279        try {
4280            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4281                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4282                        + scannedPkg.packageName);
4283                return PackageManager.SIGNATURE_MATCH;
4284            }
4285        } catch (CertificateException e) {
4286            msg = e.getMessage();
4287        }
4288
4289        logCriticalInfo(Log.INFO,
4290                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4291        return PackageManager.SIGNATURE_NO_MATCH;
4292    }
4293
4294    @Override
4295    public String[] getPackagesForUid(int uid) {
4296        uid = UserHandle.getAppId(uid);
4297        // reader
4298        synchronized (mPackages) {
4299            Object obj = mSettings.getUserIdLPr(uid);
4300            if (obj instanceof SharedUserSetting) {
4301                final SharedUserSetting sus = (SharedUserSetting) obj;
4302                final int N = sus.packages.size();
4303                final String[] res = new String[N];
4304                final Iterator<PackageSetting> it = sus.packages.iterator();
4305                int i = 0;
4306                while (it.hasNext()) {
4307                    res[i++] = it.next().name;
4308                }
4309                return res;
4310            } else if (obj instanceof PackageSetting) {
4311                final PackageSetting ps = (PackageSetting) obj;
4312                return new String[] { ps.name };
4313            }
4314        }
4315        return null;
4316    }
4317
4318    @Override
4319    public String getNameForUid(int uid) {
4320        // reader
4321        synchronized (mPackages) {
4322            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4323            if (obj instanceof SharedUserSetting) {
4324                final SharedUserSetting sus = (SharedUserSetting) obj;
4325                return sus.name + ":" + sus.userId;
4326            } else if (obj instanceof PackageSetting) {
4327                final PackageSetting ps = (PackageSetting) obj;
4328                return ps.name;
4329            }
4330        }
4331        return null;
4332    }
4333
4334    @Override
4335    public int getUidForSharedUser(String sharedUserName) {
4336        if(sharedUserName == null) {
4337            return -1;
4338        }
4339        // reader
4340        synchronized (mPackages) {
4341            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4342            if (suid == null) {
4343                return -1;
4344            }
4345            return suid.userId;
4346        }
4347    }
4348
4349    @Override
4350    public int getFlagsForUid(int uid) {
4351        synchronized (mPackages) {
4352            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4353            if (obj instanceof SharedUserSetting) {
4354                final SharedUserSetting sus = (SharedUserSetting) obj;
4355                return sus.pkgFlags;
4356            } else if (obj instanceof PackageSetting) {
4357                final PackageSetting ps = (PackageSetting) obj;
4358                return ps.pkgFlags;
4359            }
4360        }
4361        return 0;
4362    }
4363
4364    @Override
4365    public int getPrivateFlagsForUid(int uid) {
4366        synchronized (mPackages) {
4367            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4368            if (obj instanceof SharedUserSetting) {
4369                final SharedUserSetting sus = (SharedUserSetting) obj;
4370                return sus.pkgPrivateFlags;
4371            } else if (obj instanceof PackageSetting) {
4372                final PackageSetting ps = (PackageSetting) obj;
4373                return ps.pkgPrivateFlags;
4374            }
4375        }
4376        return 0;
4377    }
4378
4379    @Override
4380    public boolean isUidPrivileged(int uid) {
4381        uid = UserHandle.getAppId(uid);
4382        // reader
4383        synchronized (mPackages) {
4384            Object obj = mSettings.getUserIdLPr(uid);
4385            if (obj instanceof SharedUserSetting) {
4386                final SharedUserSetting sus = (SharedUserSetting) obj;
4387                final Iterator<PackageSetting> it = sus.packages.iterator();
4388                while (it.hasNext()) {
4389                    if (it.next().isPrivileged()) {
4390                        return true;
4391                    }
4392                }
4393            } else if (obj instanceof PackageSetting) {
4394                final PackageSetting ps = (PackageSetting) obj;
4395                return ps.isPrivileged();
4396            }
4397        }
4398        return false;
4399    }
4400
4401    @Override
4402    public String[] getAppOpPermissionPackages(String permissionName) {
4403        synchronized (mPackages) {
4404            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4405            if (pkgs == null) {
4406                return null;
4407            }
4408            return pkgs.toArray(new String[pkgs.size()]);
4409        }
4410    }
4411
4412    @Override
4413    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4414            int flags, int userId) {
4415        if (!sUserManager.exists(userId)) return null;
4416        flags = updateFlagsForResolve(flags, userId, intent);
4417        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
4418        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4419        final ResolveInfo bestChoice =
4420                chooseBestActivity(intent, resolvedType, flags, query, userId);
4421
4422        if (isEphemeralAllowed(intent, query, userId)) {
4423            final EphemeralResolveInfo ai =
4424                    getEphemeralResolveInfo(intent, resolvedType, userId);
4425            if (ai != null) {
4426                if (DEBUG_EPHEMERAL) {
4427                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4428                }
4429                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4430                bestChoice.ephemeralResolveInfo = ai;
4431            }
4432        }
4433        return bestChoice;
4434    }
4435
4436    @Override
4437    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4438            IntentFilter filter, int match, ComponentName activity) {
4439        final int userId = UserHandle.getCallingUserId();
4440        if (DEBUG_PREFERRED) {
4441            Log.v(TAG, "setLastChosenActivity intent=" + intent
4442                + " resolvedType=" + resolvedType
4443                + " flags=" + flags
4444                + " filter=" + filter
4445                + " match=" + match
4446                + " activity=" + activity);
4447            filter.dump(new PrintStreamPrinter(System.out), "    ");
4448        }
4449        intent.setComponent(null);
4450        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4451        // Find any earlier preferred or last chosen entries and nuke them
4452        findPreferredActivity(intent, resolvedType,
4453                flags, query, 0, false, true, false, userId);
4454        // Add the new activity as the last chosen for this filter
4455        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4456                "Setting last chosen");
4457    }
4458
4459    @Override
4460    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4461        final int userId = UserHandle.getCallingUserId();
4462        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4463        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
4464        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4465                false, false, false, userId);
4466    }
4467
4468
4469    private boolean isEphemeralAllowed(
4470            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4471        // Short circuit and return early if possible.
4472        final int callingUser = UserHandle.getCallingUserId();
4473        if (callingUser != UserHandle.USER_SYSTEM) {
4474            return false;
4475        }
4476        if (mEphemeralResolverConnection == null) {
4477            return false;
4478        }
4479        if (intent.getComponent() != null) {
4480            return false;
4481        }
4482        if (intent.getPackage() != null) {
4483            return false;
4484        }
4485        final boolean isWebUri = hasWebURI(intent);
4486        if (!isWebUri) {
4487            return false;
4488        }
4489        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4490        synchronized (mPackages) {
4491            final int count = resolvedActivites.size();
4492            for (int n = 0; n < count; n++) {
4493                ResolveInfo info = resolvedActivites.get(n);
4494                String packageName = info.activityInfo.packageName;
4495                PackageSetting ps = mSettings.mPackages.get(packageName);
4496                if (ps != null) {
4497                    // Try to get the status from User settings first
4498                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4499                    int status = (int) (packedStatus >> 32);
4500                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4501                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4502                        if (DEBUG_EPHEMERAL) {
4503                            Slog.v(TAG, "DENY ephemeral apps;"
4504                                + " pkg: " + packageName + ", status: " + status);
4505                        }
4506                        return false;
4507                    }
4508                }
4509            }
4510        }
4511        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4512        return true;
4513    }
4514
4515    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4516            int userId) {
4517        MessageDigest digest = null;
4518        try {
4519            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4520        } catch (NoSuchAlgorithmException e) {
4521            // If we can't create a digest, ignore ephemeral apps.
4522            return null;
4523        }
4524
4525        final byte[] hostBytes = intent.getData().getHost().getBytes();
4526        final byte[] digestBytes = digest.digest(hostBytes);
4527        int shaPrefix =
4528                digestBytes[0] << 24
4529                | digestBytes[1] << 16
4530                | digestBytes[2] << 8
4531                | digestBytes[3] << 0;
4532        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4533                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4534        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4535            // No hash prefix match; there are no ephemeral apps for this domain.
4536            return null;
4537        }
4538        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4539            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4540            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4541                continue;
4542            }
4543            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4544            // No filters; this should never happen.
4545            if (filters.isEmpty()) {
4546                continue;
4547            }
4548            // We have a domain match; resolve the filters to see if anything matches.
4549            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4550            for (int j = filters.size() - 1; j >= 0; --j) {
4551                final EphemeralResolveIntentInfo intentInfo =
4552                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4553                ephemeralResolver.addFilter(intentInfo);
4554            }
4555            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4556                    intent, resolvedType, false /*defaultOnly*/, userId);
4557            if (!matchedResolveInfoList.isEmpty()) {
4558                return matchedResolveInfoList.get(0);
4559            }
4560        }
4561        // Hash or filter mis-match; no ephemeral apps for this domain.
4562        return null;
4563    }
4564
4565    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4566            int flags, List<ResolveInfo> query, int userId) {
4567        if (query != null) {
4568            final int N = query.size();
4569            if (N == 1) {
4570                return query.get(0);
4571            } else if (N > 1) {
4572                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4573                // If there is more than one activity with the same priority,
4574                // then let the user decide between them.
4575                ResolveInfo r0 = query.get(0);
4576                ResolveInfo r1 = query.get(1);
4577                if (DEBUG_INTENT_MATCHING || debug) {
4578                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4579                            + r1.activityInfo.name + "=" + r1.priority);
4580                }
4581                // If the first activity has a higher priority, or a different
4582                // default, then it is always desirable to pick it.
4583                if (r0.priority != r1.priority
4584                        || r0.preferredOrder != r1.preferredOrder
4585                        || r0.isDefault != r1.isDefault) {
4586                    return query.get(0);
4587                }
4588                // If we have saved a preference for a preferred activity for
4589                // this Intent, use that.
4590                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4591                        flags, query, r0.priority, true, false, debug, userId);
4592                if (ri != null) {
4593                    return ri;
4594                }
4595                ri = new ResolveInfo(mResolveInfo);
4596                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4597                ri.activityInfo.applicationInfo = new ApplicationInfo(
4598                        ri.activityInfo.applicationInfo);
4599                if (userId != 0) {
4600                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4601                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4602                }
4603                // Make sure that the resolver is displayable in car mode
4604                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4605                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4606                return ri;
4607            }
4608        }
4609        return null;
4610    }
4611
4612    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4613            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4614        final int N = query.size();
4615        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4616                .get(userId);
4617        // Get the list of persistent preferred activities that handle the intent
4618        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4619        List<PersistentPreferredActivity> pprefs = ppir != null
4620                ? ppir.queryIntent(intent, resolvedType,
4621                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4622                : null;
4623        if (pprefs != null && pprefs.size() > 0) {
4624            final int M = pprefs.size();
4625            for (int i=0; i<M; i++) {
4626                final PersistentPreferredActivity ppa = pprefs.get(i);
4627                if (DEBUG_PREFERRED || debug) {
4628                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4629                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4630                            + "\n  component=" + ppa.mComponent);
4631                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4632                }
4633                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4634                        flags | MATCH_DISABLED_COMPONENTS, userId);
4635                if (DEBUG_PREFERRED || debug) {
4636                    Slog.v(TAG, "Found persistent preferred activity:");
4637                    if (ai != null) {
4638                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4639                    } else {
4640                        Slog.v(TAG, "  null");
4641                    }
4642                }
4643                if (ai == null) {
4644                    // This previously registered persistent preferred activity
4645                    // component is no longer known. Ignore it and do NOT remove it.
4646                    continue;
4647                }
4648                for (int j=0; j<N; j++) {
4649                    final ResolveInfo ri = query.get(j);
4650                    if (!ri.activityInfo.applicationInfo.packageName
4651                            .equals(ai.applicationInfo.packageName)) {
4652                        continue;
4653                    }
4654                    if (!ri.activityInfo.name.equals(ai.name)) {
4655                        continue;
4656                    }
4657                    //  Found a persistent preference that can handle the intent.
4658                    if (DEBUG_PREFERRED || debug) {
4659                        Slog.v(TAG, "Returning persistent preferred activity: " +
4660                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4661                    }
4662                    return ri;
4663                }
4664            }
4665        }
4666        return null;
4667    }
4668
4669    // TODO: handle preferred activities missing while user has amnesia
4670    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4671            List<ResolveInfo> query, int priority, boolean always,
4672            boolean removeMatches, boolean debug, int userId) {
4673        if (!sUserManager.exists(userId)) return null;
4674        flags = updateFlagsForResolve(flags, userId, intent);
4675        // writer
4676        synchronized (mPackages) {
4677            if (intent.getSelector() != null) {
4678                intent = intent.getSelector();
4679            }
4680            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4681
4682            // Try to find a matching persistent preferred activity.
4683            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4684                    debug, userId);
4685
4686            // If a persistent preferred activity matched, use it.
4687            if (pri != null) {
4688                return pri;
4689            }
4690
4691            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4692            // Get the list of preferred activities that handle the intent
4693            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4694            List<PreferredActivity> prefs = pir != null
4695                    ? pir.queryIntent(intent, resolvedType,
4696                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4697                    : null;
4698            if (prefs != null && prefs.size() > 0) {
4699                boolean changed = false;
4700                try {
4701                    // First figure out how good the original match set is.
4702                    // We will only allow preferred activities that came
4703                    // from the same match quality.
4704                    int match = 0;
4705
4706                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4707
4708                    final int N = query.size();
4709                    for (int j=0; j<N; j++) {
4710                        final ResolveInfo ri = query.get(j);
4711                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4712                                + ": 0x" + Integer.toHexString(match));
4713                        if (ri.match > match) {
4714                            match = ri.match;
4715                        }
4716                    }
4717
4718                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4719                            + Integer.toHexString(match));
4720
4721                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4722                    final int M = prefs.size();
4723                    for (int i=0; i<M; i++) {
4724                        final PreferredActivity pa = prefs.get(i);
4725                        if (DEBUG_PREFERRED || debug) {
4726                            Slog.v(TAG, "Checking PreferredActivity ds="
4727                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4728                                    + "\n  component=" + pa.mPref.mComponent);
4729                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4730                        }
4731                        if (pa.mPref.mMatch != match) {
4732                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4733                                    + Integer.toHexString(pa.mPref.mMatch));
4734                            continue;
4735                        }
4736                        // If it's not an "always" type preferred activity and that's what we're
4737                        // looking for, skip it.
4738                        if (always && !pa.mPref.mAlways) {
4739                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4740                            continue;
4741                        }
4742                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4743                                flags | MATCH_DISABLED_COMPONENTS, userId);
4744                        if (DEBUG_PREFERRED || debug) {
4745                            Slog.v(TAG, "Found preferred activity:");
4746                            if (ai != null) {
4747                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4748                            } else {
4749                                Slog.v(TAG, "  null");
4750                            }
4751                        }
4752                        if (ai == null) {
4753                            // This previously registered preferred activity
4754                            // component is no longer known.  Most likely an update
4755                            // to the app was installed and in the new version this
4756                            // component no longer exists.  Clean it up by removing
4757                            // it from the preferred activities list, and skip it.
4758                            Slog.w(TAG, "Removing dangling preferred activity: "
4759                                    + pa.mPref.mComponent);
4760                            pir.removeFilter(pa);
4761                            changed = true;
4762                            continue;
4763                        }
4764                        for (int j=0; j<N; j++) {
4765                            final ResolveInfo ri = query.get(j);
4766                            if (!ri.activityInfo.applicationInfo.packageName
4767                                    .equals(ai.applicationInfo.packageName)) {
4768                                continue;
4769                            }
4770                            if (!ri.activityInfo.name.equals(ai.name)) {
4771                                continue;
4772                            }
4773
4774                            if (removeMatches) {
4775                                pir.removeFilter(pa);
4776                                changed = true;
4777                                if (DEBUG_PREFERRED) {
4778                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4779                                }
4780                                break;
4781                            }
4782
4783                            // Okay we found a previously set preferred or last chosen app.
4784                            // If the result set is different from when this
4785                            // was created, we need to clear it and re-ask the
4786                            // user their preference, if we're looking for an "always" type entry.
4787                            if (always && !pa.mPref.sameSet(query)) {
4788                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4789                                        + intent + " type " + resolvedType);
4790                                if (DEBUG_PREFERRED) {
4791                                    Slog.v(TAG, "Removing preferred activity since set changed "
4792                                            + pa.mPref.mComponent);
4793                                }
4794                                pir.removeFilter(pa);
4795                                // Re-add the filter as a "last chosen" entry (!always)
4796                                PreferredActivity lastChosen = new PreferredActivity(
4797                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4798                                pir.addFilter(lastChosen);
4799                                changed = true;
4800                                return null;
4801                            }
4802
4803                            // Yay! Either the set matched or we're looking for the last chosen
4804                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4805                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4806                            return ri;
4807                        }
4808                    }
4809                } finally {
4810                    if (changed) {
4811                        if (DEBUG_PREFERRED) {
4812                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4813                        }
4814                        scheduleWritePackageRestrictionsLocked(userId);
4815                    }
4816                }
4817            }
4818        }
4819        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4820        return null;
4821    }
4822
4823    /*
4824     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4825     */
4826    @Override
4827    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4828            int targetUserId) {
4829        mContext.enforceCallingOrSelfPermission(
4830                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
4831        List<CrossProfileIntentFilter> matches =
4832                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
4833        if (matches != null) {
4834            int size = matches.size();
4835            for (int i = 0; i < size; i++) {
4836                if (matches.get(i).getTargetUserId() == targetUserId) return true;
4837            }
4838        }
4839        if (hasWebURI(intent)) {
4840            // cross-profile app linking works only towards the parent.
4841            final UserInfo parent = getProfileParent(sourceUserId);
4842            synchronized(mPackages) {
4843                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
4844                        intent, resolvedType, 0, sourceUserId, parent.id);
4845                return xpDomainInfo != null;
4846            }
4847        }
4848        return false;
4849    }
4850
4851    private UserInfo getProfileParent(int userId) {
4852        final long identity = Binder.clearCallingIdentity();
4853        try {
4854            return sUserManager.getProfileParent(userId);
4855        } finally {
4856            Binder.restoreCallingIdentity(identity);
4857        }
4858    }
4859
4860    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4861            String resolvedType, int userId) {
4862        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4863        if (resolver != null) {
4864            return resolver.queryIntent(intent, resolvedType, false, userId);
4865        }
4866        return null;
4867    }
4868
4869    @Override
4870    public List<ResolveInfo> queryIntentActivities(Intent intent,
4871            String resolvedType, int flags, int userId) {
4872        if (!sUserManager.exists(userId)) return Collections.emptyList();
4873        flags = updateFlagsForResolve(flags, userId, intent);
4874        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4875        ComponentName comp = intent.getComponent();
4876        if (comp == null) {
4877            if (intent.getSelector() != null) {
4878                intent = intent.getSelector();
4879                comp = intent.getComponent();
4880            }
4881        }
4882
4883        if (comp != null) {
4884            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4885            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4886            if (ai != null) {
4887                final ResolveInfo ri = new ResolveInfo();
4888                ri.activityInfo = ai;
4889                list.add(ri);
4890            }
4891            return list;
4892        }
4893
4894        // reader
4895        synchronized (mPackages) {
4896            final String pkgName = intent.getPackage();
4897            if (pkgName == null) {
4898                List<CrossProfileIntentFilter> matchingFilters =
4899                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4900                // Check for results that need to skip the current profile.
4901                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4902                        resolvedType, flags, userId);
4903                if (xpResolveInfo != null) {
4904                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4905                    result.add(xpResolveInfo);
4906                    return filterIfNotSystemUser(result, userId);
4907                }
4908
4909                // Check for results in the current profile.
4910                List<ResolveInfo> result = mActivities.queryIntent(
4911                        intent, resolvedType, flags, userId);
4912                result = filterIfNotSystemUser(result, userId);
4913
4914                // Check for cross profile results.
4915                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
4916                xpResolveInfo = queryCrossProfileIntents(
4917                        matchingFilters, intent, resolvedType, flags, userId,
4918                        hasNonNegativePriorityResult);
4919                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
4920                    boolean isVisibleToUser = filterIfNotSystemUser(
4921                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
4922                    if (isVisibleToUser) {
4923                        result.add(xpResolveInfo);
4924                        Collections.sort(result, mResolvePrioritySorter);
4925                    }
4926                }
4927                if (hasWebURI(intent)) {
4928                    CrossProfileDomainInfo xpDomainInfo = null;
4929                    final UserInfo parent = getProfileParent(userId);
4930                    if (parent != null) {
4931                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
4932                                flags, userId, parent.id);
4933                    }
4934                    if (xpDomainInfo != null) {
4935                        if (xpResolveInfo != null) {
4936                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
4937                            // in the result.
4938                            result.remove(xpResolveInfo);
4939                        }
4940                        if (result.size() == 0) {
4941                            result.add(xpDomainInfo.resolveInfo);
4942                            return result;
4943                        }
4944                    } else if (result.size() <= 1) {
4945                        return result;
4946                    }
4947                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
4948                            xpDomainInfo, userId);
4949                    Collections.sort(result, mResolvePrioritySorter);
4950                }
4951                return result;
4952            }
4953            final PackageParser.Package pkg = mPackages.get(pkgName);
4954            if (pkg != null) {
4955                return filterIfNotSystemUser(
4956                        mActivities.queryIntentForPackage(
4957                                intent, resolvedType, flags, pkg.activities, userId),
4958                        userId);
4959            }
4960            return new ArrayList<ResolveInfo>();
4961        }
4962    }
4963
4964    private static class CrossProfileDomainInfo {
4965        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
4966        ResolveInfo resolveInfo;
4967        /* Best domain verification status of the activities found in the other profile */
4968        int bestDomainVerificationStatus;
4969    }
4970
4971    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
4972            String resolvedType, int flags, int sourceUserId, int parentUserId) {
4973        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
4974                sourceUserId)) {
4975            return null;
4976        }
4977        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4978                resolvedType, flags, parentUserId);
4979
4980        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
4981            return null;
4982        }
4983        CrossProfileDomainInfo result = null;
4984        int size = resultTargetUser.size();
4985        for (int i = 0; i < size; i++) {
4986            ResolveInfo riTargetUser = resultTargetUser.get(i);
4987            // Intent filter verification is only for filters that specify a host. So don't return
4988            // those that handle all web uris.
4989            if (riTargetUser.handleAllWebDataURI) {
4990                continue;
4991            }
4992            String packageName = riTargetUser.activityInfo.packageName;
4993            PackageSetting ps = mSettings.mPackages.get(packageName);
4994            if (ps == null) {
4995                continue;
4996            }
4997            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
4998            int status = (int)(verificationState >> 32);
4999            if (result == null) {
5000                result = new CrossProfileDomainInfo();
5001                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5002                        sourceUserId, parentUserId);
5003                result.bestDomainVerificationStatus = status;
5004            } else {
5005                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5006                        result.bestDomainVerificationStatus);
5007            }
5008        }
5009        // Don't consider matches with status NEVER across profiles.
5010        if (result != null && result.bestDomainVerificationStatus
5011                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5012            return null;
5013        }
5014        return result;
5015    }
5016
5017    /**
5018     * Verification statuses are ordered from the worse to the best, except for
5019     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5020     */
5021    private int bestDomainVerificationStatus(int status1, int status2) {
5022        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5023            return status2;
5024        }
5025        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5026            return status1;
5027        }
5028        return (int) MathUtils.max(status1, status2);
5029    }
5030
5031    private boolean isUserEnabled(int userId) {
5032        long callingId = Binder.clearCallingIdentity();
5033        try {
5034            UserInfo userInfo = sUserManager.getUserInfo(userId);
5035            return userInfo != null && userInfo.isEnabled();
5036        } finally {
5037            Binder.restoreCallingIdentity(callingId);
5038        }
5039    }
5040
5041    /**
5042     * Filter out activities with systemUserOnly flag set, when current user is not System.
5043     *
5044     * @return filtered list
5045     */
5046    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5047        if (userId == UserHandle.USER_SYSTEM) {
5048            return resolveInfos;
5049        }
5050        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5051            ResolveInfo info = resolveInfos.get(i);
5052            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5053                resolveInfos.remove(i);
5054            }
5055        }
5056        return resolveInfos;
5057    }
5058
5059    /**
5060     * @param resolveInfos list of resolve infos in descending priority order
5061     * @return if the list contains a resolve info with non-negative priority
5062     */
5063    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5064        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5065    }
5066
5067    private static boolean hasWebURI(Intent intent) {
5068        if (intent.getData() == null) {
5069            return false;
5070        }
5071        final String scheme = intent.getScheme();
5072        if (TextUtils.isEmpty(scheme)) {
5073            return false;
5074        }
5075        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5076    }
5077
5078    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5079            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5080            int userId) {
5081        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5082
5083        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5084            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5085                    candidates.size());
5086        }
5087
5088        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5089        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5090        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5091        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5092        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5093        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5094
5095        synchronized (mPackages) {
5096            final int count = candidates.size();
5097            // First, try to use linked apps. Partition the candidates into four lists:
5098            // one for the final results, one for the "do not use ever", one for "undefined status"
5099            // and finally one for "browser app type".
5100            for (int n=0; n<count; n++) {
5101                ResolveInfo info = candidates.get(n);
5102                String packageName = info.activityInfo.packageName;
5103                PackageSetting ps = mSettings.mPackages.get(packageName);
5104                if (ps != null) {
5105                    // Add to the special match all list (Browser use case)
5106                    if (info.handleAllWebDataURI) {
5107                        matchAllList.add(info);
5108                        continue;
5109                    }
5110                    // Try to get the status from User settings first
5111                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5112                    int status = (int)(packedStatus >> 32);
5113                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5114                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5115                        if (DEBUG_DOMAIN_VERIFICATION) {
5116                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5117                                    + " : linkgen=" + linkGeneration);
5118                        }
5119                        // Use link-enabled generation as preferredOrder, i.e.
5120                        // prefer newly-enabled over earlier-enabled.
5121                        info.preferredOrder = linkGeneration;
5122                        alwaysList.add(info);
5123                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5124                        if (DEBUG_DOMAIN_VERIFICATION) {
5125                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5126                        }
5127                        neverList.add(info);
5128                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5129                        if (DEBUG_DOMAIN_VERIFICATION) {
5130                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5131                        }
5132                        alwaysAskList.add(info);
5133                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5134                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5135                        if (DEBUG_DOMAIN_VERIFICATION) {
5136                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5137                        }
5138                        undefinedList.add(info);
5139                    }
5140                }
5141            }
5142
5143            // We'll want to include browser possibilities in a few cases
5144            boolean includeBrowser = false;
5145
5146            // First try to add the "always" resolution(s) for the current user, if any
5147            if (alwaysList.size() > 0) {
5148                result.addAll(alwaysList);
5149            } else {
5150                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5151                result.addAll(undefinedList);
5152                // Maybe add one for the other profile.
5153                if (xpDomainInfo != null && (
5154                        xpDomainInfo.bestDomainVerificationStatus
5155                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5156                    result.add(xpDomainInfo.resolveInfo);
5157                }
5158                includeBrowser = true;
5159            }
5160
5161            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5162            // If there were 'always' entries their preferred order has been set, so we also
5163            // back that off to make the alternatives equivalent
5164            if (alwaysAskList.size() > 0) {
5165                for (ResolveInfo i : result) {
5166                    i.preferredOrder = 0;
5167                }
5168                result.addAll(alwaysAskList);
5169                includeBrowser = true;
5170            }
5171
5172            if (includeBrowser) {
5173                // Also add browsers (all of them or only the default one)
5174                if (DEBUG_DOMAIN_VERIFICATION) {
5175                    Slog.v(TAG, "   ...including browsers in candidate set");
5176                }
5177                if ((matchFlags & MATCH_ALL) != 0) {
5178                    result.addAll(matchAllList);
5179                } else {
5180                    // Browser/generic handling case.  If there's a default browser, go straight
5181                    // to that (but only if there is no other higher-priority match).
5182                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5183                    int maxMatchPrio = 0;
5184                    ResolveInfo defaultBrowserMatch = null;
5185                    final int numCandidates = matchAllList.size();
5186                    for (int n = 0; n < numCandidates; n++) {
5187                        ResolveInfo info = matchAllList.get(n);
5188                        // track the highest overall match priority...
5189                        if (info.priority > maxMatchPrio) {
5190                            maxMatchPrio = info.priority;
5191                        }
5192                        // ...and the highest-priority default browser match
5193                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5194                            if (defaultBrowserMatch == null
5195                                    || (defaultBrowserMatch.priority < info.priority)) {
5196                                if (debug) {
5197                                    Slog.v(TAG, "Considering default browser match " + info);
5198                                }
5199                                defaultBrowserMatch = info;
5200                            }
5201                        }
5202                    }
5203                    if (defaultBrowserMatch != null
5204                            && defaultBrowserMatch.priority >= maxMatchPrio
5205                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5206                    {
5207                        if (debug) {
5208                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5209                        }
5210                        result.add(defaultBrowserMatch);
5211                    } else {
5212                        result.addAll(matchAllList);
5213                    }
5214                }
5215
5216                // If there is nothing selected, add all candidates and remove the ones that the user
5217                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5218                if (result.size() == 0) {
5219                    result.addAll(candidates);
5220                    result.removeAll(neverList);
5221                }
5222            }
5223        }
5224        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5225            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5226                    result.size());
5227            for (ResolveInfo info : result) {
5228                Slog.v(TAG, "  + " + info.activityInfo);
5229            }
5230        }
5231        return result;
5232    }
5233
5234    // Returns a packed value as a long:
5235    //
5236    // high 'int'-sized word: link status: undefined/ask/never/always.
5237    // low 'int'-sized word: relative priority among 'always' results.
5238    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5239        long result = ps.getDomainVerificationStatusForUser(userId);
5240        // if none available, get the master status
5241        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5242            if (ps.getIntentFilterVerificationInfo() != null) {
5243                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5244            }
5245        }
5246        return result;
5247    }
5248
5249    private ResolveInfo querySkipCurrentProfileIntents(
5250            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5251            int flags, int sourceUserId) {
5252        if (matchingFilters != null) {
5253            int size = matchingFilters.size();
5254            for (int i = 0; i < size; i ++) {
5255                CrossProfileIntentFilter filter = matchingFilters.get(i);
5256                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5257                    // Checking if there are activities in the target user that can handle the
5258                    // intent.
5259                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5260                            resolvedType, flags, sourceUserId);
5261                    if (resolveInfo != null) {
5262                        return resolveInfo;
5263                    }
5264                }
5265            }
5266        }
5267        return null;
5268    }
5269
5270    // Return matching ResolveInfo in target user if any.
5271    private ResolveInfo queryCrossProfileIntents(
5272            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5273            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5274        if (matchingFilters != null) {
5275            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5276            // match the same intent. For performance reasons, it is better not to
5277            // run queryIntent twice for the same userId
5278            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5279            int size = matchingFilters.size();
5280            for (int i = 0; i < size; i++) {
5281                CrossProfileIntentFilter filter = matchingFilters.get(i);
5282                int targetUserId = filter.getTargetUserId();
5283                boolean skipCurrentProfile =
5284                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5285                boolean skipCurrentProfileIfNoMatchFound =
5286                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5287                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5288                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5289                    // Checking if there are activities in the target user that can handle the
5290                    // intent.
5291                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5292                            resolvedType, flags, sourceUserId);
5293                    if (resolveInfo != null) return resolveInfo;
5294                    alreadyTriedUserIds.put(targetUserId, true);
5295                }
5296            }
5297        }
5298        return null;
5299    }
5300
5301    /**
5302     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5303     * will forward the intent to the filter's target user.
5304     * Otherwise, returns null.
5305     */
5306    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5307            String resolvedType, int flags, int sourceUserId) {
5308        int targetUserId = filter.getTargetUserId();
5309        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5310                resolvedType, flags, targetUserId);
5311        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5312            // If all the matches in the target profile are suspended, return null.
5313            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5314                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5315                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5316                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5317                            targetUserId);
5318                }
5319            }
5320        }
5321        return null;
5322    }
5323
5324    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5325            int sourceUserId, int targetUserId) {
5326        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5327        long ident = Binder.clearCallingIdentity();
5328        boolean targetIsProfile;
5329        try {
5330            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5331        } finally {
5332            Binder.restoreCallingIdentity(ident);
5333        }
5334        String className;
5335        if (targetIsProfile) {
5336            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5337        } else {
5338            className = FORWARD_INTENT_TO_PARENT;
5339        }
5340        ComponentName forwardingActivityComponentName = new ComponentName(
5341                mAndroidApplication.packageName, className);
5342        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5343                sourceUserId);
5344        if (!targetIsProfile) {
5345            forwardingActivityInfo.showUserIcon = targetUserId;
5346            forwardingResolveInfo.noResourceId = true;
5347        }
5348        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5349        forwardingResolveInfo.priority = 0;
5350        forwardingResolveInfo.preferredOrder = 0;
5351        forwardingResolveInfo.match = 0;
5352        forwardingResolveInfo.isDefault = true;
5353        forwardingResolveInfo.filter = filter;
5354        forwardingResolveInfo.targetUserId = targetUserId;
5355        return forwardingResolveInfo;
5356    }
5357
5358    @Override
5359    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5360            Intent[] specifics, String[] specificTypes, Intent intent,
5361            String resolvedType, int flags, int userId) {
5362        if (!sUserManager.exists(userId)) return Collections.emptyList();
5363        flags = updateFlagsForResolve(flags, userId, intent);
5364        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
5365                false, "query intent activity options");
5366        final String resultsAction = intent.getAction();
5367
5368        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
5369                | PackageManager.GET_RESOLVED_FILTER, userId);
5370
5371        if (DEBUG_INTENT_MATCHING) {
5372            Log.v(TAG, "Query " + intent + ": " + results);
5373        }
5374
5375        int specificsPos = 0;
5376        int N;
5377
5378        // todo: note that the algorithm used here is O(N^2).  This
5379        // isn't a problem in our current environment, but if we start running
5380        // into situations where we have more than 5 or 10 matches then this
5381        // should probably be changed to something smarter...
5382
5383        // First we go through and resolve each of the specific items
5384        // that were supplied, taking care of removing any corresponding
5385        // duplicate items in the generic resolve list.
5386        if (specifics != null) {
5387            for (int i=0; i<specifics.length; i++) {
5388                final Intent sintent = specifics[i];
5389                if (sintent == null) {
5390                    continue;
5391                }
5392
5393                if (DEBUG_INTENT_MATCHING) {
5394                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5395                }
5396
5397                String action = sintent.getAction();
5398                if (resultsAction != null && resultsAction.equals(action)) {
5399                    // If this action was explicitly requested, then don't
5400                    // remove things that have it.
5401                    action = null;
5402                }
5403
5404                ResolveInfo ri = null;
5405                ActivityInfo ai = null;
5406
5407                ComponentName comp = sintent.getComponent();
5408                if (comp == null) {
5409                    ri = resolveIntent(
5410                        sintent,
5411                        specificTypes != null ? specificTypes[i] : null,
5412                            flags, userId);
5413                    if (ri == null) {
5414                        continue;
5415                    }
5416                    if (ri == mResolveInfo) {
5417                        // ACK!  Must do something better with this.
5418                    }
5419                    ai = ri.activityInfo;
5420                    comp = new ComponentName(ai.applicationInfo.packageName,
5421                            ai.name);
5422                } else {
5423                    ai = getActivityInfo(comp, flags, userId);
5424                    if (ai == null) {
5425                        continue;
5426                    }
5427                }
5428
5429                // Look for any generic query activities that are duplicates
5430                // of this specific one, and remove them from the results.
5431                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5432                N = results.size();
5433                int j;
5434                for (j=specificsPos; j<N; j++) {
5435                    ResolveInfo sri = results.get(j);
5436                    if ((sri.activityInfo.name.equals(comp.getClassName())
5437                            && sri.activityInfo.applicationInfo.packageName.equals(
5438                                    comp.getPackageName()))
5439                        || (action != null && sri.filter.matchAction(action))) {
5440                        results.remove(j);
5441                        if (DEBUG_INTENT_MATCHING) Log.v(
5442                            TAG, "Removing duplicate item from " + j
5443                            + " due to specific " + specificsPos);
5444                        if (ri == null) {
5445                            ri = sri;
5446                        }
5447                        j--;
5448                        N--;
5449                    }
5450                }
5451
5452                // Add this specific item to its proper place.
5453                if (ri == null) {
5454                    ri = new ResolveInfo();
5455                    ri.activityInfo = ai;
5456                }
5457                results.add(specificsPos, ri);
5458                ri.specificIndex = i;
5459                specificsPos++;
5460            }
5461        }
5462
5463        // Now we go through the remaining generic results and remove any
5464        // duplicate actions that are found here.
5465        N = results.size();
5466        for (int i=specificsPos; i<N-1; i++) {
5467            final ResolveInfo rii = results.get(i);
5468            if (rii.filter == null) {
5469                continue;
5470            }
5471
5472            // Iterate over all of the actions of this result's intent
5473            // filter...  typically this should be just one.
5474            final Iterator<String> it = rii.filter.actionsIterator();
5475            if (it == null) {
5476                continue;
5477            }
5478            while (it.hasNext()) {
5479                final String action = it.next();
5480                if (resultsAction != null && resultsAction.equals(action)) {
5481                    // If this action was explicitly requested, then don't
5482                    // remove things that have it.
5483                    continue;
5484                }
5485                for (int j=i+1; j<N; j++) {
5486                    final ResolveInfo rij = results.get(j);
5487                    if (rij.filter != null && rij.filter.hasAction(action)) {
5488                        results.remove(j);
5489                        if (DEBUG_INTENT_MATCHING) Log.v(
5490                            TAG, "Removing duplicate item from " + j
5491                            + " due to action " + action + " at " + i);
5492                        j--;
5493                        N--;
5494                    }
5495                }
5496            }
5497
5498            // If the caller didn't request filter information, drop it now
5499            // so we don't have to marshall/unmarshall it.
5500            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5501                rii.filter = null;
5502            }
5503        }
5504
5505        // Filter out the caller activity if so requested.
5506        if (caller != null) {
5507            N = results.size();
5508            for (int i=0; i<N; i++) {
5509                ActivityInfo ainfo = results.get(i).activityInfo;
5510                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5511                        && caller.getClassName().equals(ainfo.name)) {
5512                    results.remove(i);
5513                    break;
5514                }
5515            }
5516        }
5517
5518        // If the caller didn't request filter information,
5519        // drop them now so we don't have to
5520        // marshall/unmarshall it.
5521        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5522            N = results.size();
5523            for (int i=0; i<N; i++) {
5524                results.get(i).filter = null;
5525            }
5526        }
5527
5528        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5529        return results;
5530    }
5531
5532    @Override
5533    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
5534            int userId) {
5535        if (!sUserManager.exists(userId)) return Collections.emptyList();
5536        flags = updateFlagsForResolve(flags, userId, intent);
5537        ComponentName comp = intent.getComponent();
5538        if (comp == null) {
5539            if (intent.getSelector() != null) {
5540                intent = intent.getSelector();
5541                comp = intent.getComponent();
5542            }
5543        }
5544        if (comp != null) {
5545            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5546            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5547            if (ai != null) {
5548                ResolveInfo ri = new ResolveInfo();
5549                ri.activityInfo = ai;
5550                list.add(ri);
5551            }
5552            return list;
5553        }
5554
5555        // reader
5556        synchronized (mPackages) {
5557            String pkgName = intent.getPackage();
5558            if (pkgName == null) {
5559                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5560            }
5561            final PackageParser.Package pkg = mPackages.get(pkgName);
5562            if (pkg != null) {
5563                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5564                        userId);
5565            }
5566            return null;
5567        }
5568    }
5569
5570    @Override
5571    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5572        if (!sUserManager.exists(userId)) return null;
5573        flags = updateFlagsForResolve(flags, userId, intent);
5574        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
5575        if (query != null) {
5576            if (query.size() >= 1) {
5577                // If there is more than one service with the same priority,
5578                // just arbitrarily pick the first one.
5579                return query.get(0);
5580            }
5581        }
5582        return null;
5583    }
5584
5585    @Override
5586    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
5587            int userId) {
5588        if (!sUserManager.exists(userId)) return Collections.emptyList();
5589        flags = updateFlagsForResolve(flags, userId, intent);
5590        ComponentName comp = intent.getComponent();
5591        if (comp == null) {
5592            if (intent.getSelector() != null) {
5593                intent = intent.getSelector();
5594                comp = intent.getComponent();
5595            }
5596        }
5597        if (comp != null) {
5598            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5599            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5600            if (si != null) {
5601                final ResolveInfo ri = new ResolveInfo();
5602                ri.serviceInfo = si;
5603                list.add(ri);
5604            }
5605            return list;
5606        }
5607
5608        // reader
5609        synchronized (mPackages) {
5610            String pkgName = intent.getPackage();
5611            if (pkgName == null) {
5612                return mServices.queryIntent(intent, resolvedType, flags, userId);
5613            }
5614            final PackageParser.Package pkg = mPackages.get(pkgName);
5615            if (pkg != null) {
5616                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5617                        userId);
5618            }
5619            return null;
5620        }
5621    }
5622
5623    @Override
5624    public List<ResolveInfo> queryIntentContentProviders(
5625            Intent intent, String resolvedType, int flags, int userId) {
5626        if (!sUserManager.exists(userId)) return Collections.emptyList();
5627        flags = updateFlagsForResolve(flags, userId, intent);
5628        ComponentName comp = intent.getComponent();
5629        if (comp == null) {
5630            if (intent.getSelector() != null) {
5631                intent = intent.getSelector();
5632                comp = intent.getComponent();
5633            }
5634        }
5635        if (comp != null) {
5636            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5637            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5638            if (pi != null) {
5639                final ResolveInfo ri = new ResolveInfo();
5640                ri.providerInfo = pi;
5641                list.add(ri);
5642            }
5643            return list;
5644        }
5645
5646        // reader
5647        synchronized (mPackages) {
5648            String pkgName = intent.getPackage();
5649            if (pkgName == null) {
5650                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5651            }
5652            final PackageParser.Package pkg = mPackages.get(pkgName);
5653            if (pkg != null) {
5654                return mProviders.queryIntentForPackage(
5655                        intent, resolvedType, flags, pkg.providers, userId);
5656            }
5657            return null;
5658        }
5659    }
5660
5661    @Override
5662    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5663        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5664        flags = updateFlagsForPackage(flags, userId, null);
5665        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5666        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
5667
5668        // writer
5669        synchronized (mPackages) {
5670            ArrayList<PackageInfo> list;
5671            if (listUninstalled) {
5672                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5673                for (PackageSetting ps : mSettings.mPackages.values()) {
5674                    PackageInfo pi;
5675                    if (ps.pkg != null) {
5676                        pi = generatePackageInfo(ps.pkg, flags, userId);
5677                    } else {
5678                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5679                    }
5680                    if (pi != null) {
5681                        list.add(pi);
5682                    }
5683                }
5684            } else {
5685                list = new ArrayList<PackageInfo>(mPackages.size());
5686                for (PackageParser.Package p : mPackages.values()) {
5687                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5688                    if (pi != null) {
5689                        list.add(pi);
5690                    }
5691                }
5692            }
5693
5694            return new ParceledListSlice<PackageInfo>(list);
5695        }
5696    }
5697
5698    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5699            String[] permissions, boolean[] tmp, int flags, int userId) {
5700        int numMatch = 0;
5701        final PermissionsState permissionsState = ps.getPermissionsState();
5702        for (int i=0; i<permissions.length; i++) {
5703            final String permission = permissions[i];
5704            if (permissionsState.hasPermission(permission, userId)) {
5705                tmp[i] = true;
5706                numMatch++;
5707            } else {
5708                tmp[i] = false;
5709            }
5710        }
5711        if (numMatch == 0) {
5712            return;
5713        }
5714        PackageInfo pi;
5715        if (ps.pkg != null) {
5716            pi = generatePackageInfo(ps.pkg, flags, userId);
5717        } else {
5718            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5719        }
5720        // The above might return null in cases of uninstalled apps or install-state
5721        // skew across users/profiles.
5722        if (pi != null) {
5723            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5724                if (numMatch == permissions.length) {
5725                    pi.requestedPermissions = permissions;
5726                } else {
5727                    pi.requestedPermissions = new String[numMatch];
5728                    numMatch = 0;
5729                    for (int i=0; i<permissions.length; i++) {
5730                        if (tmp[i]) {
5731                            pi.requestedPermissions[numMatch] = permissions[i];
5732                            numMatch++;
5733                        }
5734                    }
5735                }
5736            }
5737            list.add(pi);
5738        }
5739    }
5740
5741    @Override
5742    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5743            String[] permissions, int flags, int userId) {
5744        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5745        flags = updateFlagsForPackage(flags, userId, permissions);
5746        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5747
5748        // writer
5749        synchronized (mPackages) {
5750            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5751            boolean[] tmpBools = new boolean[permissions.length];
5752            if (listUninstalled) {
5753                for (PackageSetting ps : mSettings.mPackages.values()) {
5754                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5755                }
5756            } else {
5757                for (PackageParser.Package pkg : mPackages.values()) {
5758                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5759                    if (ps != null) {
5760                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5761                                userId);
5762                    }
5763                }
5764            }
5765
5766            return new ParceledListSlice<PackageInfo>(list);
5767        }
5768    }
5769
5770    @Override
5771    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5772        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5773        flags = updateFlagsForApplication(flags, userId, null);
5774        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5775
5776        // writer
5777        synchronized (mPackages) {
5778            ArrayList<ApplicationInfo> list;
5779            if (listUninstalled) {
5780                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5781                for (PackageSetting ps : mSettings.mPackages.values()) {
5782                    ApplicationInfo ai;
5783                    if (ps.pkg != null) {
5784                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5785                                ps.readUserState(userId), userId);
5786                    } else {
5787                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5788                    }
5789                    if (ai != null) {
5790                        list.add(ai);
5791                    }
5792                }
5793            } else {
5794                list = new ArrayList<ApplicationInfo>(mPackages.size());
5795                for (PackageParser.Package p : mPackages.values()) {
5796                    if (p.mExtras != null) {
5797                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5798                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
5799                        if (ai != null) {
5800                            list.add(ai);
5801                        }
5802                    }
5803                }
5804            }
5805
5806            return new ParceledListSlice<ApplicationInfo>(list);
5807        }
5808    }
5809
5810    @Override
5811    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
5812        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5813                "getEphemeralApplications");
5814        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5815                "getEphemeralApplications");
5816        synchronized (mPackages) {
5817            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
5818                    .getEphemeralApplicationsLPw(userId);
5819            if (ephemeralApps != null) {
5820                return new ParceledListSlice<>(ephemeralApps);
5821            }
5822        }
5823        return null;
5824    }
5825
5826    @Override
5827    public boolean isEphemeralApplication(String packageName, int userId) {
5828        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5829                "isEphemeral");
5830        if (!isCallerSameApp(packageName)) {
5831            return false;
5832        }
5833        synchronized (mPackages) {
5834            PackageParser.Package pkg = mPackages.get(packageName);
5835            if (pkg != null) {
5836                return pkg.applicationInfo.isEphemeralApp();
5837            }
5838        }
5839        return false;
5840    }
5841
5842    @Override
5843    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
5844        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5845                "getCookie");
5846        if (!isCallerSameApp(packageName)) {
5847            return null;
5848        }
5849        synchronized (mPackages) {
5850            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
5851                    packageName, userId);
5852        }
5853    }
5854
5855    @Override
5856    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
5857        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5858                "setCookie");
5859        if (!isCallerSameApp(packageName)) {
5860            return false;
5861        }
5862        synchronized (mPackages) {
5863            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
5864                    packageName, cookie, userId);
5865        }
5866    }
5867
5868    @Override
5869    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
5870        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
5871                "getEphemeralApplicationIcon");
5872        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
5873                "getEphemeralApplicationIcon");
5874        synchronized (mPackages) {
5875            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
5876                    packageName, userId);
5877        }
5878    }
5879
5880    private boolean isCallerSameApp(String packageName) {
5881        PackageParser.Package pkg = mPackages.get(packageName);
5882        return pkg != null
5883                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
5884    }
5885
5886    public List<ApplicationInfo> getPersistentApplications(int flags) {
5887        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
5888
5889        // reader
5890        synchronized (mPackages) {
5891            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
5892            final int userId = UserHandle.getCallingUserId();
5893            while (i.hasNext()) {
5894                final PackageParser.Package p = i.next();
5895                if (p.applicationInfo != null
5896                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
5897                        && (!mSafeMode || isSystemApp(p))) {
5898                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
5899                    if (ps != null) {
5900                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
5901                                ps.readUserState(userId), userId);
5902                        if (ai != null) {
5903                            finalList.add(ai);
5904                        }
5905                    }
5906                }
5907            }
5908        }
5909
5910        return finalList;
5911    }
5912
5913    @Override
5914    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
5915        if (!sUserManager.exists(userId)) return null;
5916        flags = updateFlagsForComponent(flags, userId, name);
5917        // reader
5918        synchronized (mPackages) {
5919            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
5920            PackageSetting ps = provider != null
5921                    ? mSettings.mPackages.get(provider.owner.packageName)
5922                    : null;
5923            return ps != null
5924                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
5925                    && (!mSafeMode || (provider.info.applicationInfo.flags
5926                            &ApplicationInfo.FLAG_SYSTEM) != 0)
5927                    ? PackageParser.generateProviderInfo(provider, flags,
5928                            ps.readUserState(userId), userId)
5929                    : null;
5930        }
5931    }
5932
5933    /**
5934     * @deprecated
5935     */
5936    @Deprecated
5937    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
5938        // reader
5939        synchronized (mPackages) {
5940            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
5941                    .entrySet().iterator();
5942            final int userId = UserHandle.getCallingUserId();
5943            while (i.hasNext()) {
5944                Map.Entry<String, PackageParser.Provider> entry = i.next();
5945                PackageParser.Provider p = entry.getValue();
5946                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5947
5948                if (ps != null && p.syncable
5949                        && (!mSafeMode || (p.info.applicationInfo.flags
5950                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
5951                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
5952                            ps.readUserState(userId), userId);
5953                    if (info != null) {
5954                        outNames.add(entry.getKey());
5955                        outInfo.add(info);
5956                    }
5957                }
5958            }
5959        }
5960    }
5961
5962    @Override
5963    public ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
5964            int uid, int flags) {
5965        final int userId = processName != null ? UserHandle.getUserId(uid)
5966                : UserHandle.getCallingUserId();
5967        if (!sUserManager.exists(userId)) return null;
5968        flags = updateFlagsForComponent(flags, userId, processName);
5969
5970        ArrayList<ProviderInfo> finalList = null;
5971        // reader
5972        synchronized (mPackages) {
5973            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
5974            while (i.hasNext()) {
5975                final PackageParser.Provider p = i.next();
5976                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
5977                if (ps != null && p.info.authority != null
5978                        && (processName == null
5979                                || (p.info.processName.equals(processName)
5980                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
5981                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)
5982                        && (!mSafeMode
5983                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
5984                    if (finalList == null) {
5985                        finalList = new ArrayList<ProviderInfo>(3);
5986                    }
5987                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
5988                            ps.readUserState(userId), userId);
5989                    if (info != null) {
5990                        finalList.add(info);
5991                    }
5992                }
5993            }
5994        }
5995
5996        if (finalList != null) {
5997            Collections.sort(finalList, mProviderInitOrderSorter);
5998            return new ParceledListSlice<ProviderInfo>(finalList);
5999        }
6000
6001        return null;
6002    }
6003
6004    @Override
6005    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6006        // reader
6007        synchronized (mPackages) {
6008            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6009            return PackageParser.generateInstrumentationInfo(i, flags);
6010        }
6011    }
6012
6013    @Override
6014    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
6015            int flags) {
6016        ArrayList<InstrumentationInfo> finalList =
6017            new ArrayList<InstrumentationInfo>();
6018
6019        // reader
6020        synchronized (mPackages) {
6021            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6022            while (i.hasNext()) {
6023                final PackageParser.Instrumentation p = i.next();
6024                if (targetPackage == null
6025                        || targetPackage.equals(p.info.targetPackage)) {
6026                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6027                            flags);
6028                    if (ii != null) {
6029                        finalList.add(ii);
6030                    }
6031                }
6032            }
6033        }
6034
6035        return finalList;
6036    }
6037
6038    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6039        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6040        if (overlays == null) {
6041            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6042            return;
6043        }
6044        for (PackageParser.Package opkg : overlays.values()) {
6045            // Not much to do if idmap fails: we already logged the error
6046            // and we certainly don't want to abort installation of pkg simply
6047            // because an overlay didn't fit properly. For these reasons,
6048            // ignore the return value of createIdmapForPackagePairLI.
6049            createIdmapForPackagePairLI(pkg, opkg);
6050        }
6051    }
6052
6053    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6054            PackageParser.Package opkg) {
6055        if (!opkg.mTrustedOverlay) {
6056            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6057                    opkg.baseCodePath + ": overlay not trusted");
6058            return false;
6059        }
6060        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6061        if (overlaySet == null) {
6062            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6063                    opkg.baseCodePath + " but target package has no known overlays");
6064            return false;
6065        }
6066        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6067        // TODO: generate idmap for split APKs
6068        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
6069            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6070                    + opkg.baseCodePath);
6071            return false;
6072        }
6073        PackageParser.Package[] overlayArray =
6074            overlaySet.values().toArray(new PackageParser.Package[0]);
6075        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6076            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6077                return p1.mOverlayPriority - p2.mOverlayPriority;
6078            }
6079        };
6080        Arrays.sort(overlayArray, cmp);
6081
6082        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6083        int i = 0;
6084        for (PackageParser.Package p : overlayArray) {
6085            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6086        }
6087        return true;
6088    }
6089
6090    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6091        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6092        try {
6093            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6094        } finally {
6095            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6096        }
6097    }
6098
6099    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6100        final File[] files = dir.listFiles();
6101        if (ArrayUtils.isEmpty(files)) {
6102            Log.d(TAG, "No files in app dir " + dir);
6103            return;
6104        }
6105
6106        if (DEBUG_PACKAGE_SCANNING) {
6107            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6108                    + " flags=0x" + Integer.toHexString(parseFlags));
6109        }
6110
6111        for (File file : files) {
6112            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6113                    && !PackageInstallerService.isStageName(file.getName());
6114            if (!isPackage) {
6115                // Ignore entries which are not packages
6116                continue;
6117            }
6118            try {
6119                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6120                        scanFlags, currentTime, null);
6121            } catch (PackageManagerException e) {
6122                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6123
6124                // Delete invalid userdata apps
6125                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6126                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6127                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6128                    if (file.isDirectory()) {
6129                        mInstaller.rmPackageDir(file.getAbsolutePath());
6130                    } else {
6131                        file.delete();
6132                    }
6133                }
6134            }
6135        }
6136    }
6137
6138    private static File getSettingsProblemFile() {
6139        File dataDir = Environment.getDataDirectory();
6140        File systemDir = new File(dataDir, "system");
6141        File fname = new File(systemDir, "uiderrors.txt");
6142        return fname;
6143    }
6144
6145    static void reportSettingsProblem(int priority, String msg) {
6146        logCriticalInfo(priority, msg);
6147    }
6148
6149    static void logCriticalInfo(int priority, String msg) {
6150        Slog.println(priority, TAG, msg);
6151        EventLogTags.writePmCriticalInfo(msg);
6152        try {
6153            File fname = getSettingsProblemFile();
6154            FileOutputStream out = new FileOutputStream(fname, true);
6155            PrintWriter pw = new FastPrintWriter(out);
6156            SimpleDateFormat formatter = new SimpleDateFormat();
6157            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6158            pw.println(dateString + ": " + msg);
6159            pw.close();
6160            FileUtils.setPermissions(
6161                    fname.toString(),
6162                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6163                    -1, -1);
6164        } catch (java.io.IOException e) {
6165        }
6166    }
6167
6168    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
6169            PackageParser.Package pkg, File srcFile, int parseFlags)
6170            throws PackageManagerException {
6171        if (ps != null
6172                && ps.codePath.equals(srcFile)
6173                && ps.timeStamp == srcFile.lastModified()
6174                && !isCompatSignatureUpdateNeeded(pkg)
6175                && !isRecoverSignatureUpdateNeeded(pkg)) {
6176            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6177            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6178            ArraySet<PublicKey> signingKs;
6179            synchronized (mPackages) {
6180                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6181            }
6182            if (ps.signatures.mSignatures != null
6183                    && ps.signatures.mSignatures.length != 0
6184                    && signingKs != null) {
6185                // Optimization: reuse the existing cached certificates
6186                // if the package appears to be unchanged.
6187                pkg.mSignatures = ps.signatures.mSignatures;
6188                pkg.mSigningKeys = signingKs;
6189                return;
6190            }
6191
6192            Slog.w(TAG, "PackageSetting for " + ps.name
6193                    + " is missing signatures.  Collecting certs again to recover them.");
6194        } else {
6195            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6196        }
6197
6198        try {
6199            pp.collectCertificates(pkg, parseFlags);
6200        } catch (PackageParserException e) {
6201            throw PackageManagerException.from(e);
6202        }
6203    }
6204
6205    /**
6206     *  Traces a package scan.
6207     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6208     */
6209    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6210            long currentTime, UserHandle user) throws PackageManagerException {
6211        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6212        try {
6213            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6214        } finally {
6215            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6216        }
6217    }
6218
6219    /**
6220     *  Scans a package and returns the newly parsed package.
6221     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6222     */
6223    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6224            long currentTime, UserHandle user) throws PackageManagerException {
6225        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6226        parseFlags |= mDefParseFlags;
6227        PackageParser pp = new PackageParser();
6228        pp.setSeparateProcesses(mSeparateProcesses);
6229        pp.setOnlyCoreApps(mOnlyCore);
6230        pp.setDisplayMetrics(mMetrics);
6231
6232        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6233            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6234        }
6235
6236        final PackageParser.Package pkg;
6237        try {
6238            pkg = pp.parsePackage(scanFile, parseFlags);
6239        } catch (PackageParserException e) {
6240            throw PackageManagerException.from(e);
6241        }
6242
6243        PackageSetting ps = null;
6244        PackageSetting updatedPkg;
6245        // reader
6246        synchronized (mPackages) {
6247            // Look to see if we already know about this package.
6248            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6249            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6250                // This package has been renamed to its original name.  Let's
6251                // use that.
6252                ps = mSettings.peekPackageLPr(oldName);
6253            }
6254            // If there was no original package, see one for the real package name.
6255            if (ps == null) {
6256                ps = mSettings.peekPackageLPr(pkg.packageName);
6257            }
6258            // Check to see if this package could be hiding/updating a system
6259            // package.  Must look for it either under the original or real
6260            // package name depending on our state.
6261            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6262            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6263        }
6264        boolean updatedPkgBetter = false;
6265        // First check if this is a system package that may involve an update
6266        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6267            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6268            // it needs to drop FLAG_PRIVILEGED.
6269            if (locationIsPrivileged(scanFile)) {
6270                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6271            } else {
6272                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6273            }
6274
6275            if (ps != null && !ps.codePath.equals(scanFile)) {
6276                // The path has changed from what was last scanned...  check the
6277                // version of the new path against what we have stored to determine
6278                // what to do.
6279                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6280                if (pkg.mVersionCode <= ps.versionCode) {
6281                    // The system package has been updated and the code path does not match
6282                    // Ignore entry. Skip it.
6283                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6284                            + " ignored: updated version " + ps.versionCode
6285                            + " better than this " + pkg.mVersionCode);
6286                    if (!updatedPkg.codePath.equals(scanFile)) {
6287                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6288                                + ps.name + " changing from " + updatedPkg.codePathString
6289                                + " to " + scanFile);
6290                        updatedPkg.codePath = scanFile;
6291                        updatedPkg.codePathString = scanFile.toString();
6292                        updatedPkg.resourcePath = scanFile;
6293                        updatedPkg.resourcePathString = scanFile.toString();
6294                    }
6295                    updatedPkg.pkg = pkg;
6296                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6297                            "Package " + ps.name + " at " + scanFile
6298                                    + " ignored: updated version " + ps.versionCode
6299                                    + " better than this " + pkg.mVersionCode);
6300                } else {
6301                    // The current app on the system partition is better than
6302                    // what we have updated to on the data partition; switch
6303                    // back to the system partition version.
6304                    // At this point, its safely assumed that package installation for
6305                    // apps in system partition will go through. If not there won't be a working
6306                    // version of the app
6307                    // writer
6308                    synchronized (mPackages) {
6309                        // Just remove the loaded entries from package lists.
6310                        mPackages.remove(ps.name);
6311                    }
6312
6313                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6314                            + " reverting from " + ps.codePathString
6315                            + ": new version " + pkg.mVersionCode
6316                            + " better than installed " + ps.versionCode);
6317
6318                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6319                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6320                    synchronized (mInstallLock) {
6321                        args.cleanUpResourcesLI();
6322                    }
6323                    synchronized (mPackages) {
6324                        mSettings.enableSystemPackageLPw(ps.name);
6325                    }
6326                    updatedPkgBetter = true;
6327                }
6328            }
6329        }
6330
6331        if (updatedPkg != null) {
6332            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6333            // initially
6334            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6335
6336            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6337            // flag set initially
6338            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6339                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6340            }
6341        }
6342
6343        // Verify certificates against what was last scanned
6344        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
6345
6346        /*
6347         * A new system app appeared, but we already had a non-system one of the
6348         * same name installed earlier.
6349         */
6350        boolean shouldHideSystemApp = false;
6351        if (updatedPkg == null && ps != null
6352                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6353            /*
6354             * Check to make sure the signatures match first. If they don't,
6355             * wipe the installed application and its data.
6356             */
6357            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6358                    != PackageManager.SIGNATURE_MATCH) {
6359                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6360                        + " signatures don't match existing userdata copy; removing");
6361                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
6362                ps = null;
6363            } else {
6364                /*
6365                 * If the newly-added system app is an older version than the
6366                 * already installed version, hide it. It will be scanned later
6367                 * and re-added like an update.
6368                 */
6369                if (pkg.mVersionCode <= ps.versionCode) {
6370                    shouldHideSystemApp = true;
6371                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6372                            + " but new version " + pkg.mVersionCode + " better than installed "
6373                            + ps.versionCode + "; hiding system");
6374                } else {
6375                    /*
6376                     * The newly found system app is a newer version that the
6377                     * one previously installed. Simply remove the
6378                     * already-installed application and replace it with our own
6379                     * while keeping the application data.
6380                     */
6381                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6382                            + " reverting from " + ps.codePathString + ": new version "
6383                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6384                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6385                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6386                    synchronized (mInstallLock) {
6387                        args.cleanUpResourcesLI();
6388                    }
6389                }
6390            }
6391        }
6392
6393        // The apk is forward locked (not public) if its code and resources
6394        // are kept in different files. (except for app in either system or
6395        // vendor path).
6396        // TODO grab this value from PackageSettings
6397        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6398            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6399                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6400            }
6401        }
6402
6403        // TODO: extend to support forward-locked splits
6404        String resourcePath = null;
6405        String baseResourcePath = null;
6406        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6407            if (ps != null && ps.resourcePathString != null) {
6408                resourcePath = ps.resourcePathString;
6409                baseResourcePath = ps.resourcePathString;
6410            } else {
6411                // Should not happen at all. Just log an error.
6412                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6413            }
6414        } else {
6415            resourcePath = pkg.codePath;
6416            baseResourcePath = pkg.baseCodePath;
6417        }
6418
6419        // Set application objects path explicitly.
6420        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
6421        pkg.applicationInfo.setCodePath(pkg.codePath);
6422        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
6423        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
6424        pkg.applicationInfo.setResourcePath(resourcePath);
6425        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
6426        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
6427
6428        // Note that we invoke the following method only if we are about to unpack an application
6429        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6430                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6431
6432        /*
6433         * If the system app should be overridden by a previously installed
6434         * data, hide the system app now and let the /data/app scan pick it up
6435         * again.
6436         */
6437        if (shouldHideSystemApp) {
6438            synchronized (mPackages) {
6439                mSettings.disableSystemPackageLPw(pkg.packageName);
6440            }
6441        }
6442
6443        return scannedPkg;
6444    }
6445
6446    private static String fixProcessName(String defProcessName,
6447            String processName, int uid) {
6448        if (processName == null) {
6449            return defProcessName;
6450        }
6451        return processName;
6452    }
6453
6454    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6455            throws PackageManagerException {
6456        if (pkgSetting.signatures.mSignatures != null) {
6457            // Already existing package. Make sure signatures match
6458            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6459                    == PackageManager.SIGNATURE_MATCH;
6460            if (!match) {
6461                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6462                        == PackageManager.SIGNATURE_MATCH;
6463            }
6464            if (!match) {
6465                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6466                        == PackageManager.SIGNATURE_MATCH;
6467            }
6468            if (!match) {
6469                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6470                        + pkg.packageName + " signatures do not match the "
6471                        + "previously installed version; ignoring!");
6472            }
6473        }
6474
6475        // Check for shared user signatures
6476        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6477            // Already existing package. Make sure signatures match
6478            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6479                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6480            if (!match) {
6481                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6482                        == PackageManager.SIGNATURE_MATCH;
6483            }
6484            if (!match) {
6485                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6486                        == PackageManager.SIGNATURE_MATCH;
6487            }
6488            if (!match) {
6489                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6490                        "Package " + pkg.packageName
6491                        + " has no signatures that match those in shared user "
6492                        + pkgSetting.sharedUser.name + "; ignoring!");
6493            }
6494        }
6495    }
6496
6497    /**
6498     * Enforces that only the system UID or root's UID can call a method exposed
6499     * via Binder.
6500     *
6501     * @param message used as message if SecurityException is thrown
6502     * @throws SecurityException if the caller is not system or root
6503     */
6504    private static final void enforceSystemOrRoot(String message) {
6505        final int uid = Binder.getCallingUid();
6506        if (uid != Process.SYSTEM_UID && uid != 0) {
6507            throw new SecurityException(message);
6508        }
6509    }
6510
6511    @Override
6512    public void performFstrimIfNeeded() {
6513        enforceSystemOrRoot("Only the system can request fstrim");
6514
6515        // Before everything else, see whether we need to fstrim.
6516        try {
6517            IMountService ms = PackageHelper.getMountService();
6518            if (ms != null) {
6519                final boolean isUpgrade = isUpgrade();
6520                boolean doTrim = isUpgrade;
6521                if (doTrim) {
6522                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6523                } else {
6524                    final long interval = android.provider.Settings.Global.getLong(
6525                            mContext.getContentResolver(),
6526                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6527                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6528                    if (interval > 0) {
6529                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6530                        if (timeSinceLast > interval) {
6531                            doTrim = true;
6532                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6533                                    + "; running immediately");
6534                        }
6535                    }
6536                }
6537                if (doTrim) {
6538                    if (!isFirstBoot()) {
6539                        try {
6540                            ActivityManagerNative.getDefault().showBootMessage(
6541                                    mContext.getResources().getString(
6542                                            R.string.android_upgrading_fstrim), true);
6543                        } catch (RemoteException e) {
6544                        }
6545                    }
6546                    ms.runMaintenance();
6547                }
6548            } else {
6549                Slog.e(TAG, "Mount service unavailable!");
6550            }
6551        } catch (RemoteException e) {
6552            // Can't happen; MountService is local
6553        }
6554    }
6555
6556    private ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
6557        List<ResolveInfo> ris = null;
6558        try {
6559            ris = AppGlobals.getPackageManager().queryIntentReceivers(
6560                    intent, null, 0, userId);
6561        } catch (RemoteException e) {
6562        }
6563        ArraySet<String> pkgNames = new ArraySet<String>();
6564        if (ris != null) {
6565            for (ResolveInfo ri : ris) {
6566                pkgNames.add(ri.activityInfo.packageName);
6567            }
6568        }
6569        return pkgNames;
6570    }
6571
6572    @Override
6573    public void notifyPackageUse(String packageName) {
6574        synchronized (mPackages) {
6575            PackageParser.Package p = mPackages.get(packageName);
6576            if (p == null) {
6577                return;
6578            }
6579            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6580        }
6581    }
6582
6583    @Override
6584    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6585        return performDexOptTraced(packageName, instructionSet);
6586    }
6587
6588    public boolean performDexOpt(String packageName, String instructionSet) {
6589        return performDexOptTraced(packageName, instructionSet);
6590    }
6591
6592    private boolean performDexOptTraced(String packageName, String instructionSet) {
6593        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6594        try {
6595            return performDexOptInternal(packageName, instructionSet);
6596        } finally {
6597            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6598        }
6599    }
6600
6601    private boolean performDexOptInternal(String packageName, String instructionSet) {
6602        PackageParser.Package p;
6603        final String targetInstructionSet;
6604        synchronized (mPackages) {
6605            p = mPackages.get(packageName);
6606            if (p == null) {
6607                return false;
6608            }
6609            mPackageUsage.write(false);
6610
6611            targetInstructionSet = instructionSet != null ? instructionSet :
6612                    getPrimaryInstructionSet(p.applicationInfo);
6613            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
6614                return false;
6615            }
6616        }
6617        long callingId = Binder.clearCallingIdentity();
6618        try {
6619            synchronized (mInstallLock) {
6620                final String[] instructionSets = new String[] { targetInstructionSet };
6621                int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
6622                        true /* inclDependencies */);
6623                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6624            }
6625        } finally {
6626            Binder.restoreCallingIdentity(callingId);
6627        }
6628    }
6629
6630    public ArraySet<String> getPackagesThatNeedDexOpt() {
6631        ArraySet<String> pkgs = null;
6632        synchronized (mPackages) {
6633            for (PackageParser.Package p : mPackages.values()) {
6634                if (DEBUG_DEXOPT) {
6635                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
6636                }
6637                if (!p.mDexOptPerformed.isEmpty()) {
6638                    continue;
6639                }
6640                if (pkgs == null) {
6641                    pkgs = new ArraySet<String>();
6642                }
6643                pkgs.add(p.packageName);
6644            }
6645        }
6646        return pkgs;
6647    }
6648
6649    public void shutdown() {
6650        mPackageUsage.write(true);
6651    }
6652
6653    @Override
6654    public void forceDexOpt(String packageName) {
6655        enforceSystemOrRoot("forceDexOpt");
6656
6657        PackageParser.Package pkg;
6658        synchronized (mPackages) {
6659            pkg = mPackages.get(packageName);
6660            if (pkg == null) {
6661                throw new IllegalArgumentException("Unknown package: " + packageName);
6662            }
6663        }
6664
6665        synchronized (mInstallLock) {
6666            final String[] instructionSets = new String[] {
6667                    getPrimaryInstructionSet(pkg.applicationInfo) };
6668
6669            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6670
6671            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
6672                    true /* inclDependencies */);
6673
6674            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6675            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
6676                throw new IllegalStateException("Failed to dexopt: " + res);
6677            }
6678        }
6679    }
6680
6681    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
6682        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6683            Slog.w(TAG, "Unable to update from " + oldPkg.name
6684                    + " to " + newPkg.packageName
6685                    + ": old package not in system partition");
6686            return false;
6687        } else if (mPackages.get(oldPkg.name) != null) {
6688            Slog.w(TAG, "Unable to update from " + oldPkg.name
6689                    + " to " + newPkg.packageName
6690                    + ": old package still exists");
6691            return false;
6692        }
6693        return true;
6694    }
6695
6696    private void createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo)
6697            throws PackageManagerException {
6698        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
6699        if (res != 0) {
6700            throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6701                    "Failed to install " + packageName + ": " + res);
6702        }
6703
6704        final int[] users = sUserManager.getUserIds();
6705        for (int user : users) {
6706            if (user != 0) {
6707                res = mInstaller.createUserData(volumeUuid, packageName,
6708                        UserHandle.getUid(user, uid), user, seinfo);
6709                if (res != 0) {
6710                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6711                            "Failed to createUserData " + packageName + ": " + res);
6712                }
6713            }
6714        }
6715    }
6716
6717    private int removeDataDirsLI(String volumeUuid, String packageName) {
6718        int[] users = sUserManager.getUserIds();
6719        int res = 0;
6720        for (int user : users) {
6721            int resInner = mInstaller.remove(volumeUuid, packageName, user);
6722            if (resInner < 0) {
6723                res = resInner;
6724            }
6725        }
6726
6727        return res;
6728    }
6729
6730    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
6731        int[] users = sUserManager.getUserIds();
6732        int res = 0;
6733        for (int user : users) {
6734            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
6735            if (resInner < 0) {
6736                res = resInner;
6737            }
6738        }
6739        return res;
6740    }
6741
6742    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
6743            PackageParser.Package changingLib) {
6744        if (file.path != null) {
6745            usesLibraryFiles.add(file.path);
6746            return;
6747        }
6748        PackageParser.Package p = mPackages.get(file.apk);
6749        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
6750            // If we are doing this while in the middle of updating a library apk,
6751            // then we need to make sure to use that new apk for determining the
6752            // dependencies here.  (We haven't yet finished committing the new apk
6753            // to the package manager state.)
6754            if (p == null || p.packageName.equals(changingLib.packageName)) {
6755                p = changingLib;
6756            }
6757        }
6758        if (p != null) {
6759            usesLibraryFiles.addAll(p.getAllCodePaths());
6760        }
6761    }
6762
6763    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
6764            PackageParser.Package changingLib) throws PackageManagerException {
6765        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
6766            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
6767            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
6768            for (int i=0; i<N; i++) {
6769                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
6770                if (file == null) {
6771                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
6772                            "Package " + pkg.packageName + " requires unavailable shared library "
6773                            + pkg.usesLibraries.get(i) + "; failing!");
6774                }
6775                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6776            }
6777            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
6778            for (int i=0; i<N; i++) {
6779                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
6780                if (file == null) {
6781                    Slog.w(TAG, "Package " + pkg.packageName
6782                            + " desires unavailable shared library "
6783                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
6784                } else {
6785                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
6786                }
6787            }
6788            N = usesLibraryFiles.size();
6789            if (N > 0) {
6790                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
6791            } else {
6792                pkg.usesLibraryFiles = null;
6793            }
6794        }
6795    }
6796
6797    private static boolean hasString(List<String> list, List<String> which) {
6798        if (list == null) {
6799            return false;
6800        }
6801        for (int i=list.size()-1; i>=0; i--) {
6802            for (int j=which.size()-1; j>=0; j--) {
6803                if (which.get(j).equals(list.get(i))) {
6804                    return true;
6805                }
6806            }
6807        }
6808        return false;
6809    }
6810
6811    private void updateAllSharedLibrariesLPw() {
6812        for (PackageParser.Package pkg : mPackages.values()) {
6813            try {
6814                updateSharedLibrariesLPw(pkg, null);
6815            } catch (PackageManagerException e) {
6816                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6817            }
6818        }
6819    }
6820
6821    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
6822            PackageParser.Package changingPkg) {
6823        ArrayList<PackageParser.Package> res = null;
6824        for (PackageParser.Package pkg : mPackages.values()) {
6825            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
6826                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
6827                if (res == null) {
6828                    res = new ArrayList<PackageParser.Package>();
6829                }
6830                res.add(pkg);
6831                try {
6832                    updateSharedLibrariesLPw(pkg, changingPkg);
6833                } catch (PackageManagerException e) {
6834                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
6835                }
6836            }
6837        }
6838        return res;
6839    }
6840
6841    /**
6842     * Derive the value of the {@code cpuAbiOverride} based on the provided
6843     * value and an optional stored value from the package settings.
6844     */
6845    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
6846        String cpuAbiOverride = null;
6847
6848        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
6849            cpuAbiOverride = null;
6850        } else if (abiOverride != null) {
6851            cpuAbiOverride = abiOverride;
6852        } else if (settings != null) {
6853            cpuAbiOverride = settings.cpuAbiOverrideString;
6854        }
6855
6856        return cpuAbiOverride;
6857    }
6858
6859    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
6860            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6861        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6862        try {
6863            return scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
6864        } finally {
6865            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6866        }
6867    }
6868
6869    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
6870            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6871        boolean success = false;
6872        try {
6873            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
6874                    currentTime, user);
6875            success = true;
6876            return res;
6877        } finally {
6878            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
6879                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
6880            }
6881        }
6882    }
6883
6884    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
6885            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
6886        final File scanFile = new File(pkg.codePath);
6887        if (pkg.applicationInfo.getCodePath() == null ||
6888                pkg.applicationInfo.getResourcePath() == null) {
6889            // Bail out. The resource and code paths haven't been set.
6890            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
6891                    "Code and resource paths haven't been set correctly");
6892        }
6893
6894        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
6895            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
6896        } else {
6897            // Only allow system apps to be flagged as core apps.
6898            pkg.coreApp = false;
6899        }
6900
6901        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
6902            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6903        }
6904
6905        if (mCustomResolverComponentName != null &&
6906                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
6907            setUpCustomResolverActivity(pkg);
6908        }
6909
6910        if (pkg.packageName.equals("android")) {
6911            synchronized (mPackages) {
6912                if (mAndroidApplication != null) {
6913                    Slog.w(TAG, "*************************************************");
6914                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
6915                    Slog.w(TAG, " file=" + scanFile);
6916                    Slog.w(TAG, "*************************************************");
6917                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6918                            "Core android package being redefined.  Skipping.");
6919                }
6920
6921                // Set up information for our fall-back user intent resolution activity.
6922                mPlatformPackage = pkg;
6923                pkg.mVersionCode = mSdkVersion;
6924                mAndroidApplication = pkg.applicationInfo;
6925
6926                if (!mResolverReplaced) {
6927                    mResolveActivity.applicationInfo = mAndroidApplication;
6928                    mResolveActivity.name = ResolverActivity.class.getName();
6929                    mResolveActivity.packageName = mAndroidApplication.packageName;
6930                    mResolveActivity.processName = "system:ui";
6931                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6932                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
6933                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
6934                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
6935                    mResolveActivity.exported = true;
6936                    mResolveActivity.enabled = true;
6937                    mResolveInfo.activityInfo = mResolveActivity;
6938                    mResolveInfo.priority = 0;
6939                    mResolveInfo.preferredOrder = 0;
6940                    mResolveInfo.match = 0;
6941                    mResolveComponentName = new ComponentName(
6942                            mAndroidApplication.packageName, mResolveActivity.name);
6943                }
6944            }
6945        }
6946
6947        if (DEBUG_PACKAGE_SCANNING) {
6948            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6949                Log.d(TAG, "Scanning package " + pkg.packageName);
6950        }
6951
6952        if (mPackages.containsKey(pkg.packageName)
6953                || mSharedLibraries.containsKey(pkg.packageName)) {
6954            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
6955                    "Application package " + pkg.packageName
6956                    + " already installed.  Skipping duplicate.");
6957        }
6958
6959        // If we're only installing presumed-existing packages, require that the
6960        // scanned APK is both already known and at the path previously established
6961        // for it.  Previously unknown packages we pick up normally, but if we have an
6962        // a priori expectation about this package's install presence, enforce it.
6963        // With a singular exception for new system packages. When an OTA contains
6964        // a new system package, we allow the codepath to change from a system location
6965        // to the user-installed location. If we don't allow this change, any newer,
6966        // user-installed version of the application will be ignored.
6967        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
6968            if (mExpectingBetter.containsKey(pkg.packageName)) {
6969                logCriticalInfo(Log.WARN,
6970                        "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
6971            } else {
6972                PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
6973                if (known != null) {
6974                    if (DEBUG_PACKAGE_SCANNING) {
6975                        Log.d(TAG, "Examining " + pkg.codePath
6976                                + " and requiring known paths " + known.codePathString
6977                                + " & " + known.resourcePathString);
6978                    }
6979                    if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
6980                            || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
6981                        throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
6982                                "Application package " + pkg.packageName
6983                                + " found at " + pkg.applicationInfo.getCodePath()
6984                                + " but expected at " + known.codePathString + "; ignoring.");
6985                    }
6986                }
6987            }
6988        }
6989
6990        // Initialize package source and resource directories
6991        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
6992        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
6993
6994        SharedUserSetting suid = null;
6995        PackageSetting pkgSetting = null;
6996
6997        if (!isSystemApp(pkg)) {
6998            // Only system apps can use these features.
6999            pkg.mOriginalPackages = null;
7000            pkg.mRealPackage = null;
7001            pkg.mAdoptPermissions = null;
7002        }
7003
7004        // writer
7005        synchronized (mPackages) {
7006            if (pkg.mSharedUserId != null) {
7007                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7008                if (suid == null) {
7009                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7010                            "Creating application package " + pkg.packageName
7011                            + " for shared user failed");
7012                }
7013                if (DEBUG_PACKAGE_SCANNING) {
7014                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7015                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7016                                + "): packages=" + suid.packages);
7017                }
7018            }
7019
7020            // Check if we are renaming from an original package name.
7021            PackageSetting origPackage = null;
7022            String realName = null;
7023            if (pkg.mOriginalPackages != null) {
7024                // This package may need to be renamed to a previously
7025                // installed name.  Let's check on that...
7026                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7027                if (pkg.mOriginalPackages.contains(renamed)) {
7028                    // This package had originally been installed as the
7029                    // original name, and we have already taken care of
7030                    // transitioning to the new one.  Just update the new
7031                    // one to continue using the old name.
7032                    realName = pkg.mRealPackage;
7033                    if (!pkg.packageName.equals(renamed)) {
7034                        // Callers into this function may have already taken
7035                        // care of renaming the package; only do it here if
7036                        // it is not already done.
7037                        pkg.setPackageName(renamed);
7038                    }
7039
7040                } else {
7041                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7042                        if ((origPackage = mSettings.peekPackageLPr(
7043                                pkg.mOriginalPackages.get(i))) != null) {
7044                            // We do have the package already installed under its
7045                            // original name...  should we use it?
7046                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7047                                // New package is not compatible with original.
7048                                origPackage = null;
7049                                continue;
7050                            } else if (origPackage.sharedUser != null) {
7051                                // Make sure uid is compatible between packages.
7052                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7053                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7054                                            + " to " + pkg.packageName + ": old uid "
7055                                            + origPackage.sharedUser.name
7056                                            + " differs from " + pkg.mSharedUserId);
7057                                    origPackage = null;
7058                                    continue;
7059                                }
7060                            } else {
7061                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7062                                        + pkg.packageName + " to old name " + origPackage.name);
7063                            }
7064                            break;
7065                        }
7066                    }
7067                }
7068            }
7069
7070            if (mTransferedPackages.contains(pkg.packageName)) {
7071                Slog.w(TAG, "Package " + pkg.packageName
7072                        + " was transferred to another, but its .apk remains");
7073            }
7074
7075            // Just create the setting, don't add it yet. For already existing packages
7076            // the PkgSetting exists already and doesn't have to be created.
7077            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7078                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7079                    pkg.applicationInfo.primaryCpuAbi,
7080                    pkg.applicationInfo.secondaryCpuAbi,
7081                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7082                    user, false);
7083            if (pkgSetting == null) {
7084                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7085                        "Creating application package " + pkg.packageName + " failed");
7086            }
7087
7088            if (pkgSetting.origPackage != null) {
7089                // If we are first transitioning from an original package,
7090                // fix up the new package's name now.  We need to do this after
7091                // looking up the package under its new name, so getPackageLP
7092                // can take care of fiddling things correctly.
7093                pkg.setPackageName(origPackage.name);
7094
7095                // File a report about this.
7096                String msg = "New package " + pkgSetting.realName
7097                        + " renamed to replace old package " + pkgSetting.name;
7098                reportSettingsProblem(Log.WARN, msg);
7099
7100                // Make a note of it.
7101                mTransferedPackages.add(origPackage.name);
7102
7103                // No longer need to retain this.
7104                pkgSetting.origPackage = null;
7105            }
7106
7107            if (realName != null) {
7108                // Make a note of it.
7109                mTransferedPackages.add(pkg.packageName);
7110            }
7111
7112            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7113                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7114            }
7115
7116            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7117                // Check all shared libraries and map to their actual file path.
7118                // We only do this here for apps not on a system dir, because those
7119                // are the only ones that can fail an install due to this.  We
7120                // will take care of the system apps by updating all of their
7121                // library paths after the scan is done.
7122                updateSharedLibrariesLPw(pkg, null);
7123            }
7124
7125            if (mFoundPolicyFile) {
7126                SELinuxMMAC.assignSeinfoValue(pkg);
7127            }
7128
7129            pkg.applicationInfo.uid = pkgSetting.appId;
7130            pkg.mExtras = pkgSetting;
7131            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7132                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7133                    // We just determined the app is signed correctly, so bring
7134                    // over the latest parsed certs.
7135                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7136                } else {
7137                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7138                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7139                                "Package " + pkg.packageName + " upgrade keys do not match the "
7140                                + "previously installed version");
7141                    } else {
7142                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7143                        String msg = "System package " + pkg.packageName
7144                            + " signature changed; retaining data.";
7145                        reportSettingsProblem(Log.WARN, msg);
7146                    }
7147                }
7148            } else {
7149                try {
7150                    verifySignaturesLP(pkgSetting, pkg);
7151                    // We just determined the app is signed correctly, so bring
7152                    // over the latest parsed certs.
7153                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7154                } catch (PackageManagerException e) {
7155                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7156                        throw e;
7157                    }
7158                    // The signature has changed, but this package is in the system
7159                    // image...  let's recover!
7160                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7161                    // However...  if this package is part of a shared user, but it
7162                    // doesn't match the signature of the shared user, let's fail.
7163                    // What this means is that you can't change the signatures
7164                    // associated with an overall shared user, which doesn't seem all
7165                    // that unreasonable.
7166                    if (pkgSetting.sharedUser != null) {
7167                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7168                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7169                            throw new PackageManagerException(
7170                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7171                                            "Signature mismatch for shared user: "
7172                                            + pkgSetting.sharedUser);
7173                        }
7174                    }
7175                    // File a report about this.
7176                    String msg = "System package " + pkg.packageName
7177                        + " signature changed; retaining data.";
7178                    reportSettingsProblem(Log.WARN, msg);
7179                }
7180            }
7181            // Verify that this new package doesn't have any content providers
7182            // that conflict with existing packages.  Only do this if the
7183            // package isn't already installed, since we don't want to break
7184            // things that are installed.
7185            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7186                final int N = pkg.providers.size();
7187                int i;
7188                for (i=0; i<N; i++) {
7189                    PackageParser.Provider p = pkg.providers.get(i);
7190                    if (p.info.authority != null) {
7191                        String names[] = p.info.authority.split(";");
7192                        for (int j = 0; j < names.length; j++) {
7193                            if (mProvidersByAuthority.containsKey(names[j])) {
7194                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7195                                final String otherPackageName =
7196                                        ((other != null && other.getComponentName() != null) ?
7197                                                other.getComponentName().getPackageName() : "?");
7198                                throw new PackageManagerException(
7199                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7200                                                "Can't install because provider name " + names[j]
7201                                                + " (in package " + pkg.applicationInfo.packageName
7202                                                + ") is already used by " + otherPackageName);
7203                            }
7204                        }
7205                    }
7206                }
7207            }
7208
7209            if (pkg.mAdoptPermissions != null) {
7210                // This package wants to adopt ownership of permissions from
7211                // another package.
7212                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7213                    final String origName = pkg.mAdoptPermissions.get(i);
7214                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7215                    if (orig != null) {
7216                        if (verifyPackageUpdateLPr(orig, pkg)) {
7217                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7218                                    + pkg.packageName);
7219                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7220                        }
7221                    }
7222                }
7223            }
7224        }
7225
7226        final String pkgName = pkg.packageName;
7227
7228        final long scanFileTime = scanFile.lastModified();
7229        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7230        pkg.applicationInfo.processName = fixProcessName(
7231                pkg.applicationInfo.packageName,
7232                pkg.applicationInfo.processName,
7233                pkg.applicationInfo.uid);
7234
7235        if (pkg != mPlatformPackage) {
7236            // This is a normal package, need to make its data directory.
7237            final File dataPath = Environment.getDataUserCredentialEncryptedPackageDirectory(
7238                    pkg.volumeUuid, UserHandle.USER_SYSTEM, pkg.packageName);
7239
7240            boolean uidError = false;
7241            if (dataPath.exists()) {
7242                int currentUid = 0;
7243                try {
7244                    StructStat stat = Os.stat(dataPath.getPath());
7245                    currentUid = stat.st_uid;
7246                } catch (ErrnoException e) {
7247                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
7248                }
7249
7250                // If we have mismatched owners for the data path, we have a problem.
7251                if (currentUid != pkg.applicationInfo.uid) {
7252                    boolean recovered = false;
7253                    if (currentUid == 0) {
7254                        // The directory somehow became owned by root.  Wow.
7255                        // This is probably because the system was stopped while
7256                        // installd was in the middle of messing with its libs
7257                        // directory.  Ask installd to fix that.
7258                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
7259                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
7260                        if (ret >= 0) {
7261                            recovered = true;
7262                            String msg = "Package " + pkg.packageName
7263                                    + " unexpectedly changed to uid 0; recovered to " +
7264                                    + pkg.applicationInfo.uid;
7265                            reportSettingsProblem(Log.WARN, msg);
7266                        }
7267                    }
7268                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7269                            || (scanFlags&SCAN_BOOTING) != 0)) {
7270                        // If this is a system app, we can at least delete its
7271                        // current data so the application will still work.
7272                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
7273                        if (ret >= 0) {
7274                            // TODO: Kill the processes first
7275                            // Old data gone!
7276                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
7277                                    ? "System package " : "Third party package ";
7278                            String msg = prefix + pkg.packageName
7279                                    + " has changed from uid: "
7280                                    + currentUid + " to "
7281                                    + pkg.applicationInfo.uid + "; old data erased";
7282                            reportSettingsProblem(Log.WARN, msg);
7283                            recovered = true;
7284                        }
7285                        if (!recovered) {
7286                            mHasSystemUidErrors = true;
7287                        }
7288                    } else if (!recovered) {
7289                        // If we allow this install to proceed, we will be broken.
7290                        // Abort, abort!
7291                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
7292                                "scanPackageLI");
7293                    }
7294                    if (!recovered) {
7295                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
7296                            + pkg.applicationInfo.uid + "/fs_"
7297                            + currentUid;
7298                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
7299                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
7300                        String msg = "Package " + pkg.packageName
7301                                + " has mismatched uid: "
7302                                + currentUid + " on disk, "
7303                                + pkg.applicationInfo.uid + " in settings";
7304                        // writer
7305                        synchronized (mPackages) {
7306                            mSettings.mReadMessages.append(msg);
7307                            mSettings.mReadMessages.append('\n');
7308                            uidError = true;
7309                            if (!pkgSetting.uidError) {
7310                                reportSettingsProblem(Log.ERROR, msg);
7311                            }
7312                        }
7313                    }
7314                }
7315
7316                // Ensure that directories are prepared
7317                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7318                        pkg.applicationInfo.seinfo);
7319
7320                if (mShouldRestoreconData) {
7321                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
7322                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
7323                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
7324                }
7325            } else {
7326                if (DEBUG_PACKAGE_SCANNING) {
7327                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7328                        Log.v(TAG, "Want this data dir: " + dataPath);
7329                }
7330                createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
7331                        pkg.applicationInfo.seinfo);
7332            }
7333
7334            // Get all of our default paths setup
7335            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7336
7337            pkgSetting.uidError = uidError;
7338        }
7339
7340        final String path = scanFile.getPath();
7341        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7342
7343        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7344            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7345
7346            // Some system apps still use directory structure for native libraries
7347            // in which case we might end up not detecting abi solely based on apk
7348            // structure. Try to detect abi based on directory structure.
7349            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7350                    pkg.applicationInfo.primaryCpuAbi == null) {
7351                setBundledAppAbisAndRoots(pkg, pkgSetting);
7352                setNativeLibraryPaths(pkg);
7353            }
7354
7355        } else {
7356            if ((scanFlags & SCAN_MOVE) != 0) {
7357                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7358                // but we already have this packages package info in the PackageSetting. We just
7359                // use that and derive the native library path based on the new codepath.
7360                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7361                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7362            }
7363
7364            // Set native library paths again. For moves, the path will be updated based on the
7365            // ABIs we've determined above. For non-moves, the path will be updated based on the
7366            // ABIs we determined during compilation, but the path will depend on the final
7367            // package path (after the rename away from the stage path).
7368            setNativeLibraryPaths(pkg);
7369        }
7370
7371        if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
7372        final int[] userIds = sUserManager.getUserIds();
7373        synchronized (mInstallLock) {
7374            // Make sure all user data directories are ready to roll; we're okay
7375            // if they already exist
7376            if (!TextUtils.isEmpty(pkg.volumeUuid)) {
7377                for (int userId : userIds) {
7378                    if (userId != UserHandle.USER_SYSTEM) {
7379                        mInstaller.createUserData(pkg.volumeUuid, pkg.packageName,
7380                                UserHandle.getUid(userId, pkg.applicationInfo.uid), userId,
7381                                pkg.applicationInfo.seinfo);
7382                    }
7383                }
7384            }
7385
7386            // Create a native library symlink only if we have native libraries
7387            // and if the native libraries are 32 bit libraries. We do not provide
7388            // this symlink for 64 bit libraries.
7389            if (pkg.applicationInfo.primaryCpuAbi != null &&
7390                    !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
7391                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "linkNativeLib");
7392                try {
7393                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
7394                    for (int userId : userIds) {
7395                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
7396                                nativeLibPath, userId) < 0) {
7397                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
7398                                    "Failed linking native library dir (user=" + userId + ")");
7399                        }
7400                    }
7401                } finally {
7402                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7403                }
7404            }
7405        }
7406
7407        // This is a special case for the "system" package, where the ABI is
7408        // dictated by the zygote configuration (and init.rc). We should keep track
7409        // of this ABI so that we can deal with "normal" applications that run under
7410        // the same UID correctly.
7411        if (mPlatformPackage == pkg) {
7412            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7413                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7414        }
7415
7416        // If there's a mismatch between the abi-override in the package setting
7417        // and the abiOverride specified for the install. Warn about this because we
7418        // would've already compiled the app without taking the package setting into
7419        // account.
7420        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7421            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7422                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7423                        " for package " + pkg.packageName);
7424            }
7425        }
7426
7427        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7428        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7429        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7430
7431        // Copy the derived override back to the parsed package, so that we can
7432        // update the package settings accordingly.
7433        pkg.cpuAbiOverride = cpuAbiOverride;
7434
7435        if (DEBUG_ABI_SELECTION) {
7436            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7437                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7438                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7439        }
7440
7441        // Push the derived path down into PackageSettings so we know what to
7442        // clean up at uninstall time.
7443        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7444
7445        if (DEBUG_ABI_SELECTION) {
7446            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7447                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7448                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7449        }
7450
7451        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7452            // We don't do this here during boot because we can do it all
7453            // at once after scanning all existing packages.
7454            //
7455            // We also do this *before* we perform dexopt on this package, so that
7456            // we can avoid redundant dexopts, and also to make sure we've got the
7457            // code and package path correct.
7458            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7459                    pkg, true /* boot complete */);
7460        }
7461
7462        if (mFactoryTest && pkg.requestedPermissions.contains(
7463                android.Manifest.permission.FACTORY_TEST)) {
7464            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7465        }
7466
7467        ArrayList<PackageParser.Package> clientLibPkgs = null;
7468
7469        // writer
7470        synchronized (mPackages) {
7471            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7472                // Only system apps can add new shared libraries.
7473                if (pkg.libraryNames != null) {
7474                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7475                        String name = pkg.libraryNames.get(i);
7476                        boolean allowed = false;
7477                        if (pkg.isUpdatedSystemApp()) {
7478                            // New library entries can only be added through the
7479                            // system image.  This is important to get rid of a lot
7480                            // of nasty edge cases: for example if we allowed a non-
7481                            // system update of the app to add a library, then uninstalling
7482                            // the update would make the library go away, and assumptions
7483                            // we made such as through app install filtering would now
7484                            // have allowed apps on the device which aren't compatible
7485                            // with it.  Better to just have the restriction here, be
7486                            // conservative, and create many fewer cases that can negatively
7487                            // impact the user experience.
7488                            final PackageSetting sysPs = mSettings
7489                                    .getDisabledSystemPkgLPr(pkg.packageName);
7490                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7491                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7492                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7493                                        allowed = true;
7494                                        break;
7495                                    }
7496                                }
7497                            }
7498                        } else {
7499                            allowed = true;
7500                        }
7501                        if (allowed) {
7502                            if (!mSharedLibraries.containsKey(name)) {
7503                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7504                            } else if (!name.equals(pkg.packageName)) {
7505                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7506                                        + name + " already exists; skipping");
7507                            }
7508                        } else {
7509                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7510                                    + name + " that is not declared on system image; skipping");
7511                        }
7512                    }
7513                    if ((scanFlags & SCAN_BOOTING) == 0) {
7514                        // If we are not booting, we need to update any applications
7515                        // that are clients of our shared library.  If we are booting,
7516                        // this will all be done once the scan is complete.
7517                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7518                    }
7519                }
7520            }
7521        }
7522
7523        // Request the ActivityManager to kill the process(only for existing packages)
7524        // so that we do not end up in a confused state while the user is still using the older
7525        // version of the application while the new one gets installed.
7526        if ((scanFlags & SCAN_REPLACING) != 0) {
7527            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7528
7529            killApplication(pkg.applicationInfo.packageName,
7530                        pkg.applicationInfo.uid, "replace pkg");
7531
7532            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7533        }
7534
7535        // Also need to kill any apps that are dependent on the library.
7536        if (clientLibPkgs != null) {
7537            for (int i=0; i<clientLibPkgs.size(); i++) {
7538                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7539                killApplication(clientPkg.applicationInfo.packageName,
7540                        clientPkg.applicationInfo.uid, "update lib");
7541            }
7542        }
7543
7544        // Make sure we're not adding any bogus keyset info
7545        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7546        ksms.assertScannedPackageValid(pkg);
7547
7548        // writer
7549        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7550
7551        boolean createIdmapFailed = false;
7552        synchronized (mPackages) {
7553            // We don't expect installation to fail beyond this point
7554
7555            // Add the new setting to mSettings
7556            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7557            // Add the new setting to mPackages
7558            mPackages.put(pkg.applicationInfo.packageName, pkg);
7559            // Make sure we don't accidentally delete its data.
7560            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
7561            while (iter.hasNext()) {
7562                PackageCleanItem item = iter.next();
7563                if (pkgName.equals(item.packageName)) {
7564                    iter.remove();
7565                }
7566            }
7567
7568            // Take care of first install / last update times.
7569            if (currentTime != 0) {
7570                if (pkgSetting.firstInstallTime == 0) {
7571                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
7572                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
7573                    pkgSetting.lastUpdateTime = currentTime;
7574                }
7575            } else if (pkgSetting.firstInstallTime == 0) {
7576                // We need *something*.  Take time time stamp of the file.
7577                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
7578            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
7579                if (scanFileTime != pkgSetting.timeStamp) {
7580                    // A package on the system image has changed; consider this
7581                    // to be an update.
7582                    pkgSetting.lastUpdateTime = scanFileTime;
7583                }
7584            }
7585
7586            // Add the package's KeySets to the global KeySetManagerService
7587            ksms.addScannedPackageLPw(pkg);
7588
7589            int N = pkg.providers.size();
7590            StringBuilder r = null;
7591            int i;
7592            for (i=0; i<N; i++) {
7593                PackageParser.Provider p = pkg.providers.get(i);
7594                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
7595                        p.info.processName, pkg.applicationInfo.uid);
7596                mProviders.addProvider(p);
7597                p.syncable = p.info.isSyncable;
7598                if (p.info.authority != null) {
7599                    String names[] = p.info.authority.split(";");
7600                    p.info.authority = null;
7601                    for (int j = 0; j < names.length; j++) {
7602                        if (j == 1 && p.syncable) {
7603                            // We only want the first authority for a provider to possibly be
7604                            // syncable, so if we already added this provider using a different
7605                            // authority clear the syncable flag. We copy the provider before
7606                            // changing it because the mProviders object contains a reference
7607                            // to a provider that we don't want to change.
7608                            // Only do this for the second authority since the resulting provider
7609                            // object can be the same for all future authorities for this provider.
7610                            p = new PackageParser.Provider(p);
7611                            p.syncable = false;
7612                        }
7613                        if (!mProvidersByAuthority.containsKey(names[j])) {
7614                            mProvidersByAuthority.put(names[j], p);
7615                            if (p.info.authority == null) {
7616                                p.info.authority = names[j];
7617                            } else {
7618                                p.info.authority = p.info.authority + ";" + names[j];
7619                            }
7620                            if (DEBUG_PACKAGE_SCANNING) {
7621                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7622                                    Log.d(TAG, "Registered content provider: " + names[j]
7623                                            + ", className = " + p.info.name + ", isSyncable = "
7624                                            + p.info.isSyncable);
7625                            }
7626                        } else {
7627                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7628                            Slog.w(TAG, "Skipping provider name " + names[j] +
7629                                    " (in package " + pkg.applicationInfo.packageName +
7630                                    "): name already used by "
7631                                    + ((other != null && other.getComponentName() != null)
7632                                            ? other.getComponentName().getPackageName() : "?"));
7633                        }
7634                    }
7635                }
7636                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7637                    if (r == null) {
7638                        r = new StringBuilder(256);
7639                    } else {
7640                        r.append(' ');
7641                    }
7642                    r.append(p.info.name);
7643                }
7644            }
7645            if (r != null) {
7646                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
7647            }
7648
7649            N = pkg.services.size();
7650            r = null;
7651            for (i=0; i<N; i++) {
7652                PackageParser.Service s = pkg.services.get(i);
7653                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
7654                        s.info.processName, pkg.applicationInfo.uid);
7655                mServices.addService(s);
7656                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7657                    if (r == null) {
7658                        r = new StringBuilder(256);
7659                    } else {
7660                        r.append(' ');
7661                    }
7662                    r.append(s.info.name);
7663                }
7664            }
7665            if (r != null) {
7666                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
7667            }
7668
7669            N = pkg.receivers.size();
7670            r = null;
7671            for (i=0; i<N; i++) {
7672                PackageParser.Activity a = pkg.receivers.get(i);
7673                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7674                        a.info.processName, pkg.applicationInfo.uid);
7675                mReceivers.addActivity(a, "receiver");
7676                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7677                    if (r == null) {
7678                        r = new StringBuilder(256);
7679                    } else {
7680                        r.append(' ');
7681                    }
7682                    r.append(a.info.name);
7683                }
7684            }
7685            if (r != null) {
7686                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
7687            }
7688
7689            N = pkg.activities.size();
7690            r = null;
7691            for (i=0; i<N; i++) {
7692                PackageParser.Activity a = pkg.activities.get(i);
7693                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
7694                        a.info.processName, pkg.applicationInfo.uid);
7695                mActivities.addActivity(a, "activity");
7696                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7697                    if (r == null) {
7698                        r = new StringBuilder(256);
7699                    } else {
7700                        r.append(' ');
7701                    }
7702                    r.append(a.info.name);
7703                }
7704            }
7705            if (r != null) {
7706                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
7707            }
7708
7709            N = pkg.permissionGroups.size();
7710            r = null;
7711            for (i=0; i<N; i++) {
7712                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
7713                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
7714                if (cur == null) {
7715                    mPermissionGroups.put(pg.info.name, pg);
7716                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7717                        if (r == null) {
7718                            r = new StringBuilder(256);
7719                        } else {
7720                            r.append(' ');
7721                        }
7722                        r.append(pg.info.name);
7723                    }
7724                } else {
7725                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
7726                            + pg.info.packageName + " ignored: original from "
7727                            + cur.info.packageName);
7728                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7729                        if (r == null) {
7730                            r = new StringBuilder(256);
7731                        } else {
7732                            r.append(' ');
7733                        }
7734                        r.append("DUP:");
7735                        r.append(pg.info.name);
7736                    }
7737                }
7738            }
7739            if (r != null) {
7740                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
7741            }
7742
7743            N = pkg.permissions.size();
7744            r = null;
7745            for (i=0; i<N; i++) {
7746                PackageParser.Permission p = pkg.permissions.get(i);
7747
7748                // Assume by default that we did not install this permission into the system.
7749                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
7750
7751                // Now that permission groups have a special meaning, we ignore permission
7752                // groups for legacy apps to prevent unexpected behavior. In particular,
7753                // permissions for one app being granted to someone just becuase they happen
7754                // to be in a group defined by another app (before this had no implications).
7755                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
7756                    p.group = mPermissionGroups.get(p.info.group);
7757                    // Warn for a permission in an unknown group.
7758                    if (p.info.group != null && p.group == null) {
7759                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7760                                + p.info.packageName + " in an unknown group " + p.info.group);
7761                    }
7762                }
7763
7764                ArrayMap<String, BasePermission> permissionMap =
7765                        p.tree ? mSettings.mPermissionTrees
7766                                : mSettings.mPermissions;
7767                BasePermission bp = permissionMap.get(p.info.name);
7768
7769                // Allow system apps to redefine non-system permissions
7770                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
7771                    final boolean currentOwnerIsSystem = (bp.perm != null
7772                            && isSystemApp(bp.perm.owner));
7773                    if (isSystemApp(p.owner)) {
7774                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
7775                            // It's a built-in permission and no owner, take ownership now
7776                            bp.packageSetting = pkgSetting;
7777                            bp.perm = p;
7778                            bp.uid = pkg.applicationInfo.uid;
7779                            bp.sourcePackage = p.info.packageName;
7780                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7781                        } else if (!currentOwnerIsSystem) {
7782                            String msg = "New decl " + p.owner + " of permission  "
7783                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
7784                            reportSettingsProblem(Log.WARN, msg);
7785                            bp = null;
7786                        }
7787                    }
7788                }
7789
7790                if (bp == null) {
7791                    bp = new BasePermission(p.info.name, p.info.packageName,
7792                            BasePermission.TYPE_NORMAL);
7793                    permissionMap.put(p.info.name, bp);
7794                }
7795
7796                if (bp.perm == null) {
7797                    if (bp.sourcePackage == null
7798                            || bp.sourcePackage.equals(p.info.packageName)) {
7799                        BasePermission tree = findPermissionTreeLP(p.info.name);
7800                        if (tree == null
7801                                || tree.sourcePackage.equals(p.info.packageName)) {
7802                            bp.packageSetting = pkgSetting;
7803                            bp.perm = p;
7804                            bp.uid = pkg.applicationInfo.uid;
7805                            bp.sourcePackage = p.info.packageName;
7806                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
7807                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7808                                if (r == null) {
7809                                    r = new StringBuilder(256);
7810                                } else {
7811                                    r.append(' ');
7812                                }
7813                                r.append(p.info.name);
7814                            }
7815                        } else {
7816                            Slog.w(TAG, "Permission " + p.info.name + " from package "
7817                                    + p.info.packageName + " ignored: base tree "
7818                                    + tree.name + " is from package "
7819                                    + tree.sourcePackage);
7820                        }
7821                    } else {
7822                        Slog.w(TAG, "Permission " + p.info.name + " from package "
7823                                + p.info.packageName + " ignored: original from "
7824                                + bp.sourcePackage);
7825                    }
7826                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7827                    if (r == null) {
7828                        r = new StringBuilder(256);
7829                    } else {
7830                        r.append(' ');
7831                    }
7832                    r.append("DUP:");
7833                    r.append(p.info.name);
7834                }
7835                if (bp.perm == p) {
7836                    bp.protectionLevel = p.info.protectionLevel;
7837                }
7838            }
7839
7840            if (r != null) {
7841                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
7842            }
7843
7844            N = pkg.instrumentation.size();
7845            r = null;
7846            for (i=0; i<N; i++) {
7847                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7848                a.info.packageName = pkg.applicationInfo.packageName;
7849                a.info.sourceDir = pkg.applicationInfo.sourceDir;
7850                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
7851                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
7852                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
7853                a.info.dataDir = pkg.applicationInfo.dataDir;
7854                a.info.deviceEncryptedDataDir = pkg.applicationInfo.deviceEncryptedDataDir;
7855                a.info.credentialEncryptedDataDir = pkg.applicationInfo.credentialEncryptedDataDir;
7856
7857                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
7858                // need other information about the application, like the ABI and what not ?
7859                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
7860                mInstrumentation.put(a.getComponentName(), a);
7861                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
7862                    if (r == null) {
7863                        r = new StringBuilder(256);
7864                    } else {
7865                        r.append(' ');
7866                    }
7867                    r.append(a.info.name);
7868                }
7869            }
7870            if (r != null) {
7871                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
7872            }
7873
7874            if (pkg.protectedBroadcasts != null) {
7875                N = pkg.protectedBroadcasts.size();
7876                for (i=0; i<N; i++) {
7877                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
7878                }
7879            }
7880
7881            pkgSetting.setTimeStamp(scanFileTime);
7882
7883            // Create idmap files for pairs of (packages, overlay packages).
7884            // Note: "android", ie framework-res.apk, is handled by native layers.
7885            if (pkg.mOverlayTarget != null) {
7886                // This is an overlay package.
7887                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
7888                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
7889                        mOverlays.put(pkg.mOverlayTarget,
7890                                new ArrayMap<String, PackageParser.Package>());
7891                    }
7892                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
7893                    map.put(pkg.packageName, pkg);
7894                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
7895                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
7896                        createIdmapFailed = true;
7897                    }
7898                }
7899            } else if (mOverlays.containsKey(pkg.packageName) &&
7900                    !pkg.packageName.equals("android")) {
7901                // This is a regular package, with one or more known overlay packages.
7902                createIdmapsForPackageLI(pkg);
7903            }
7904        }
7905
7906        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7907
7908        if (createIdmapFailed) {
7909            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7910                    "scanPackageLI failed to createIdmap");
7911        }
7912        return pkg;
7913    }
7914
7915    /**
7916     * Derive the ABI of a non-system package located at {@code scanFile}. This information
7917     * is derived purely on the basis of the contents of {@code scanFile} and
7918     * {@code cpuAbiOverride}.
7919     *
7920     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
7921     */
7922    public void derivePackageAbi(PackageParser.Package pkg, File scanFile,
7923                                 String cpuAbiOverride, boolean extractLibs)
7924            throws PackageManagerException {
7925        // TODO: We can probably be smarter about this stuff. For installed apps,
7926        // we can calculate this information at install time once and for all. For
7927        // system apps, we can probably assume that this information doesn't change
7928        // after the first boot scan. As things stand, we do lots of unnecessary work.
7929
7930        // Give ourselves some initial paths; we'll come back for another
7931        // pass once we've determined ABI below.
7932        setNativeLibraryPaths(pkg);
7933
7934        // We would never need to extract libs for forward-locked and external packages,
7935        // since the container service will do it for us. We shouldn't attempt to
7936        // extract libs from system app when it was not updated.
7937        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
7938                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
7939            extractLibs = false;
7940        }
7941
7942        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
7943        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
7944
7945        NativeLibraryHelper.Handle handle = null;
7946        try {
7947            handle = NativeLibraryHelper.Handle.create(pkg);
7948            // TODO(multiArch): This can be null for apps that didn't go through the
7949            // usual installation process. We can calculate it again, like we
7950            // do during install time.
7951            //
7952            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
7953            // unnecessary.
7954            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
7955
7956            // Null out the abis so that they can be recalculated.
7957            pkg.applicationInfo.primaryCpuAbi = null;
7958            pkg.applicationInfo.secondaryCpuAbi = null;
7959            if (isMultiArch(pkg.applicationInfo)) {
7960                // Warn if we've set an abiOverride for multi-lib packages..
7961                // By definition, we need to copy both 32 and 64 bit libraries for
7962                // such packages.
7963                if (pkg.cpuAbiOverride != null
7964                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
7965                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
7966                }
7967
7968                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
7969                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
7970                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
7971                    if (extractLibs) {
7972                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7973                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
7974                                useIsaSpecificSubdirs);
7975                    } else {
7976                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
7977                    }
7978                }
7979
7980                maybeThrowExceptionForMultiArchCopy(
7981                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
7982
7983                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
7984                    if (extractLibs) {
7985                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
7986                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
7987                                useIsaSpecificSubdirs);
7988                    } else {
7989                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
7990                    }
7991                }
7992
7993                maybeThrowExceptionForMultiArchCopy(
7994                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
7995
7996                if (abi64 >= 0) {
7997                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
7998                }
7999
8000                if (abi32 >= 0) {
8001                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8002                    if (abi64 >= 0) {
8003                        pkg.applicationInfo.secondaryCpuAbi = abi;
8004                    } else {
8005                        pkg.applicationInfo.primaryCpuAbi = abi;
8006                    }
8007                }
8008            } else {
8009                String[] abiList = (cpuAbiOverride != null) ?
8010                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8011
8012                // Enable gross and lame hacks for apps that are built with old
8013                // SDK tools. We must scan their APKs for renderscript bitcode and
8014                // not launch them if it's present. Don't bother checking on devices
8015                // that don't have 64 bit support.
8016                boolean needsRenderScriptOverride = false;
8017                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8018                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8019                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8020                    needsRenderScriptOverride = true;
8021                }
8022
8023                final int copyRet;
8024                if (extractLibs) {
8025                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8026                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8027                } else {
8028                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8029                }
8030
8031                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8032                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8033                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8034                }
8035
8036                if (copyRet >= 0) {
8037                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8038                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8039                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8040                } else if (needsRenderScriptOverride) {
8041                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8042                }
8043            }
8044        } catch (IOException ioe) {
8045            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8046        } finally {
8047            IoUtils.closeQuietly(handle);
8048        }
8049
8050        // Now that we've calculated the ABIs and determined if it's an internal app,
8051        // we will go ahead and populate the nativeLibraryPath.
8052        setNativeLibraryPaths(pkg);
8053    }
8054
8055    /**
8056     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8057     * i.e, so that all packages can be run inside a single process if required.
8058     *
8059     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8060     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8061     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8062     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8063     * updating a package that belongs to a shared user.
8064     *
8065     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8066     * adds unnecessary complexity.
8067     */
8068    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8069            PackageParser.Package scannedPackage, boolean bootComplete) {
8070        String requiredInstructionSet = null;
8071        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8072            requiredInstructionSet = VMRuntime.getInstructionSet(
8073                     scannedPackage.applicationInfo.primaryCpuAbi);
8074        }
8075
8076        PackageSetting requirer = null;
8077        for (PackageSetting ps : packagesForUser) {
8078            // If packagesForUser contains scannedPackage, we skip it. This will happen
8079            // when scannedPackage is an update of an existing package. Without this check,
8080            // we will never be able to change the ABI of any package belonging to a shared
8081            // user, even if it's compatible with other packages.
8082            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8083                if (ps.primaryCpuAbiString == null) {
8084                    continue;
8085                }
8086
8087                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8088                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8089                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8090                    // this but there's not much we can do.
8091                    String errorMessage = "Instruction set mismatch, "
8092                            + ((requirer == null) ? "[caller]" : requirer)
8093                            + " requires " + requiredInstructionSet + " whereas " + ps
8094                            + " requires " + instructionSet;
8095                    Slog.w(TAG, errorMessage);
8096                }
8097
8098                if (requiredInstructionSet == null) {
8099                    requiredInstructionSet = instructionSet;
8100                    requirer = ps;
8101                }
8102            }
8103        }
8104
8105        if (requiredInstructionSet != null) {
8106            String adjustedAbi;
8107            if (requirer != null) {
8108                // requirer != null implies that either scannedPackage was null or that scannedPackage
8109                // did not require an ABI, in which case we have to adjust scannedPackage to match
8110                // the ABI of the set (which is the same as requirer's ABI)
8111                adjustedAbi = requirer.primaryCpuAbiString;
8112                if (scannedPackage != null) {
8113                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8114                }
8115            } else {
8116                // requirer == null implies that we're updating all ABIs in the set to
8117                // match scannedPackage.
8118                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8119            }
8120
8121            for (PackageSetting ps : packagesForUser) {
8122                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8123                    if (ps.primaryCpuAbiString != null) {
8124                        continue;
8125                    }
8126
8127                    ps.primaryCpuAbiString = adjustedAbi;
8128                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
8129                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8130                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi);
8131                        mInstaller.rmdex(ps.codePathString,
8132                                getDexCodeInstructionSet(getPreferredInstructionSet()));
8133                    }
8134                }
8135            }
8136        }
8137    }
8138
8139    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8140        synchronized (mPackages) {
8141            mResolverReplaced = true;
8142            // Set up information for custom user intent resolution activity.
8143            mResolveActivity.applicationInfo = pkg.applicationInfo;
8144            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8145            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8146            mResolveActivity.processName = pkg.applicationInfo.packageName;
8147            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8148            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8149                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8150            mResolveActivity.theme = 0;
8151            mResolveActivity.exported = true;
8152            mResolveActivity.enabled = true;
8153            mResolveInfo.activityInfo = mResolveActivity;
8154            mResolveInfo.priority = 0;
8155            mResolveInfo.preferredOrder = 0;
8156            mResolveInfo.match = 0;
8157            mResolveComponentName = mCustomResolverComponentName;
8158            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8159                    mResolveComponentName);
8160        }
8161    }
8162
8163    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8164        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8165
8166        // Set up information for ephemeral installer activity
8167        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8168        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8169        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8170        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8171        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8172        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8173                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8174        mEphemeralInstallerActivity.theme = 0;
8175        mEphemeralInstallerActivity.exported = true;
8176        mEphemeralInstallerActivity.enabled = true;
8177        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8178        mEphemeralInstallerInfo.priority = 0;
8179        mEphemeralInstallerInfo.preferredOrder = 0;
8180        mEphemeralInstallerInfo.match = 0;
8181
8182        if (DEBUG_EPHEMERAL) {
8183            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8184        }
8185    }
8186
8187    private static String calculateBundledApkRoot(final String codePathString) {
8188        final File codePath = new File(codePathString);
8189        final File codeRoot;
8190        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8191            codeRoot = Environment.getRootDirectory();
8192        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8193            codeRoot = Environment.getOemDirectory();
8194        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8195            codeRoot = Environment.getVendorDirectory();
8196        } else {
8197            // Unrecognized code path; take its top real segment as the apk root:
8198            // e.g. /something/app/blah.apk => /something
8199            try {
8200                File f = codePath.getCanonicalFile();
8201                File parent = f.getParentFile();    // non-null because codePath is a file
8202                File tmp;
8203                while ((tmp = parent.getParentFile()) != null) {
8204                    f = parent;
8205                    parent = tmp;
8206                }
8207                codeRoot = f;
8208                Slog.w(TAG, "Unrecognized code path "
8209                        + codePath + " - using " + codeRoot);
8210            } catch (IOException e) {
8211                // Can't canonicalize the code path -- shenanigans?
8212                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8213                return Environment.getRootDirectory().getPath();
8214            }
8215        }
8216        return codeRoot.getPath();
8217    }
8218
8219    /**
8220     * Derive and set the location of native libraries for the given package,
8221     * which varies depending on where and how the package was installed.
8222     */
8223    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8224        final ApplicationInfo info = pkg.applicationInfo;
8225        final String codePath = pkg.codePath;
8226        final File codeFile = new File(codePath);
8227        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8228        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8229
8230        info.nativeLibraryRootDir = null;
8231        info.nativeLibraryRootRequiresIsa = false;
8232        info.nativeLibraryDir = null;
8233        info.secondaryNativeLibraryDir = null;
8234
8235        if (isApkFile(codeFile)) {
8236            // Monolithic install
8237            if (bundledApp) {
8238                // If "/system/lib64/apkname" exists, assume that is the per-package
8239                // native library directory to use; otherwise use "/system/lib/apkname".
8240                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8241                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8242                        getPrimaryInstructionSet(info));
8243
8244                // This is a bundled system app so choose the path based on the ABI.
8245                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8246                // is just the default path.
8247                final String apkName = deriveCodePathName(codePath);
8248                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8249                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8250                        apkName).getAbsolutePath();
8251
8252                if (info.secondaryCpuAbi != null) {
8253                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8254                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8255                            secondaryLibDir, apkName).getAbsolutePath();
8256                }
8257            } else if (asecApp) {
8258                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8259                        .getAbsolutePath();
8260            } else {
8261                final String apkName = deriveCodePathName(codePath);
8262                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8263                        .getAbsolutePath();
8264            }
8265
8266            info.nativeLibraryRootRequiresIsa = false;
8267            info.nativeLibraryDir = info.nativeLibraryRootDir;
8268        } else {
8269            // Cluster install
8270            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8271            info.nativeLibraryRootRequiresIsa = true;
8272
8273            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8274                    getPrimaryInstructionSet(info)).getAbsolutePath();
8275
8276            if (info.secondaryCpuAbi != null) {
8277                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8278                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8279            }
8280        }
8281    }
8282
8283    /**
8284     * Calculate the abis and roots for a bundled app. These can uniquely
8285     * be determined from the contents of the system partition, i.e whether
8286     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8287     * of this information, and instead assume that the system was built
8288     * sensibly.
8289     */
8290    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8291                                           PackageSetting pkgSetting) {
8292        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8293
8294        // If "/system/lib64/apkname" exists, assume that is the per-package
8295        // native library directory to use; otherwise use "/system/lib/apkname".
8296        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8297        setBundledAppAbi(pkg, apkRoot, apkName);
8298        // pkgSetting might be null during rescan following uninstall of updates
8299        // to a bundled app, so accommodate that possibility.  The settings in
8300        // that case will be established later from the parsed package.
8301        //
8302        // If the settings aren't null, sync them up with what we've just derived.
8303        // note that apkRoot isn't stored in the package settings.
8304        if (pkgSetting != null) {
8305            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8306            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8307        }
8308    }
8309
8310    /**
8311     * Deduces the ABI of a bundled app and sets the relevant fields on the
8312     * parsed pkg object.
8313     *
8314     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8315     *        under which system libraries are installed.
8316     * @param apkName the name of the installed package.
8317     */
8318    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8319        final File codeFile = new File(pkg.codePath);
8320
8321        final boolean has64BitLibs;
8322        final boolean has32BitLibs;
8323        if (isApkFile(codeFile)) {
8324            // Monolithic install
8325            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8326            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8327        } else {
8328            // Cluster install
8329            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8330            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8331                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8332                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8333                has64BitLibs = (new File(rootDir, isa)).exists();
8334            } else {
8335                has64BitLibs = false;
8336            }
8337            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8338                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8339                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8340                has32BitLibs = (new File(rootDir, isa)).exists();
8341            } else {
8342                has32BitLibs = false;
8343            }
8344        }
8345
8346        if (has64BitLibs && !has32BitLibs) {
8347            // The package has 64 bit libs, but not 32 bit libs. Its primary
8348            // ABI should be 64 bit. We can safely assume here that the bundled
8349            // native libraries correspond to the most preferred ABI in the list.
8350
8351            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8352            pkg.applicationInfo.secondaryCpuAbi = null;
8353        } else if (has32BitLibs && !has64BitLibs) {
8354            // The package has 32 bit libs but not 64 bit libs. Its primary
8355            // ABI should be 32 bit.
8356
8357            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8358            pkg.applicationInfo.secondaryCpuAbi = null;
8359        } else if (has32BitLibs && has64BitLibs) {
8360            // The application has both 64 and 32 bit bundled libraries. We check
8361            // here that the app declares multiArch support, and warn if it doesn't.
8362            //
8363            // We will be lenient here and record both ABIs. The primary will be the
8364            // ABI that's higher on the list, i.e, a device that's configured to prefer
8365            // 64 bit apps will see a 64 bit primary ABI,
8366
8367            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8368                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8369            }
8370
8371            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8372                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8373                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8374            } else {
8375                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8376                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8377            }
8378        } else {
8379            pkg.applicationInfo.primaryCpuAbi = null;
8380            pkg.applicationInfo.secondaryCpuAbi = null;
8381        }
8382    }
8383
8384    private void killApplication(String pkgName, int appId, String reason) {
8385        // Request the ActivityManager to kill the process(only for existing packages)
8386        // so that we do not end up in a confused state while the user is still using the older
8387        // version of the application while the new one gets installed.
8388        IActivityManager am = ActivityManagerNative.getDefault();
8389        if (am != null) {
8390            try {
8391                am.killApplicationWithAppId(pkgName, appId, reason);
8392            } catch (RemoteException e) {
8393            }
8394        }
8395    }
8396
8397    void removePackageLI(PackageSetting ps, boolean chatty) {
8398        if (DEBUG_INSTALL) {
8399            if (chatty)
8400                Log.d(TAG, "Removing package " + ps.name);
8401        }
8402
8403        // writer
8404        synchronized (mPackages) {
8405            mPackages.remove(ps.name);
8406            final PackageParser.Package pkg = ps.pkg;
8407            if (pkg != null) {
8408                cleanPackageDataStructuresLILPw(pkg, chatty);
8409            }
8410        }
8411    }
8412
8413    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8414        if (DEBUG_INSTALL) {
8415            if (chatty)
8416                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8417        }
8418
8419        // writer
8420        synchronized (mPackages) {
8421            mPackages.remove(pkg.applicationInfo.packageName);
8422            cleanPackageDataStructuresLILPw(pkg, chatty);
8423        }
8424    }
8425
8426    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8427        int N = pkg.providers.size();
8428        StringBuilder r = null;
8429        int i;
8430        for (i=0; i<N; i++) {
8431            PackageParser.Provider p = pkg.providers.get(i);
8432            mProviders.removeProvider(p);
8433            if (p.info.authority == null) {
8434
8435                /* There was another ContentProvider with this authority when
8436                 * this app was installed so this authority is null,
8437                 * Ignore it as we don't have to unregister the provider.
8438                 */
8439                continue;
8440            }
8441            String names[] = p.info.authority.split(";");
8442            for (int j = 0; j < names.length; j++) {
8443                if (mProvidersByAuthority.get(names[j]) == p) {
8444                    mProvidersByAuthority.remove(names[j]);
8445                    if (DEBUG_REMOVE) {
8446                        if (chatty)
8447                            Log.d(TAG, "Unregistered content provider: " + names[j]
8448                                    + ", className = " + p.info.name + ", isSyncable = "
8449                                    + p.info.isSyncable);
8450                    }
8451                }
8452            }
8453            if (DEBUG_REMOVE && chatty) {
8454                if (r == null) {
8455                    r = new StringBuilder(256);
8456                } else {
8457                    r.append(' ');
8458                }
8459                r.append(p.info.name);
8460            }
8461        }
8462        if (r != null) {
8463            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8464        }
8465
8466        N = pkg.services.size();
8467        r = null;
8468        for (i=0; i<N; i++) {
8469            PackageParser.Service s = pkg.services.get(i);
8470            mServices.removeService(s);
8471            if (chatty) {
8472                if (r == null) {
8473                    r = new StringBuilder(256);
8474                } else {
8475                    r.append(' ');
8476                }
8477                r.append(s.info.name);
8478            }
8479        }
8480        if (r != null) {
8481            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8482        }
8483
8484        N = pkg.receivers.size();
8485        r = null;
8486        for (i=0; i<N; i++) {
8487            PackageParser.Activity a = pkg.receivers.get(i);
8488            mReceivers.removeActivity(a, "receiver");
8489            if (DEBUG_REMOVE && chatty) {
8490                if (r == null) {
8491                    r = new StringBuilder(256);
8492                } else {
8493                    r.append(' ');
8494                }
8495                r.append(a.info.name);
8496            }
8497        }
8498        if (r != null) {
8499            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8500        }
8501
8502        N = pkg.activities.size();
8503        r = null;
8504        for (i=0; i<N; i++) {
8505            PackageParser.Activity a = pkg.activities.get(i);
8506            mActivities.removeActivity(a, "activity");
8507            if (DEBUG_REMOVE && chatty) {
8508                if (r == null) {
8509                    r = new StringBuilder(256);
8510                } else {
8511                    r.append(' ');
8512                }
8513                r.append(a.info.name);
8514            }
8515        }
8516        if (r != null) {
8517            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
8518        }
8519
8520        N = pkg.permissions.size();
8521        r = null;
8522        for (i=0; i<N; i++) {
8523            PackageParser.Permission p = pkg.permissions.get(i);
8524            BasePermission bp = mSettings.mPermissions.get(p.info.name);
8525            if (bp == null) {
8526                bp = mSettings.mPermissionTrees.get(p.info.name);
8527            }
8528            if (bp != null && bp.perm == p) {
8529                bp.perm = null;
8530                if (DEBUG_REMOVE && chatty) {
8531                    if (r == null) {
8532                        r = new StringBuilder(256);
8533                    } else {
8534                        r.append(' ');
8535                    }
8536                    r.append(p.info.name);
8537                }
8538            }
8539            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8540                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
8541                if (appOpPkgs != null) {
8542                    appOpPkgs.remove(pkg.packageName);
8543                }
8544            }
8545        }
8546        if (r != null) {
8547            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8548        }
8549
8550        N = pkg.requestedPermissions.size();
8551        r = null;
8552        for (i=0; i<N; i++) {
8553            String perm = pkg.requestedPermissions.get(i);
8554            BasePermission bp = mSettings.mPermissions.get(perm);
8555            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8556                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
8557                if (appOpPkgs != null) {
8558                    appOpPkgs.remove(pkg.packageName);
8559                    if (appOpPkgs.isEmpty()) {
8560                        mAppOpPermissionPackages.remove(perm);
8561                    }
8562                }
8563            }
8564        }
8565        if (r != null) {
8566            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
8567        }
8568
8569        N = pkg.instrumentation.size();
8570        r = null;
8571        for (i=0; i<N; i++) {
8572            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8573            mInstrumentation.remove(a.getComponentName());
8574            if (DEBUG_REMOVE && chatty) {
8575                if (r == null) {
8576                    r = new StringBuilder(256);
8577                } else {
8578                    r.append(' ');
8579                }
8580                r.append(a.info.name);
8581            }
8582        }
8583        if (r != null) {
8584            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
8585        }
8586
8587        r = null;
8588        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8589            // Only system apps can hold shared libraries.
8590            if (pkg.libraryNames != null) {
8591                for (i=0; i<pkg.libraryNames.size(); i++) {
8592                    String name = pkg.libraryNames.get(i);
8593                    SharedLibraryEntry cur = mSharedLibraries.get(name);
8594                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
8595                        mSharedLibraries.remove(name);
8596                        if (DEBUG_REMOVE && chatty) {
8597                            if (r == null) {
8598                                r = new StringBuilder(256);
8599                            } else {
8600                                r.append(' ');
8601                            }
8602                            r.append(name);
8603                        }
8604                    }
8605                }
8606            }
8607        }
8608        if (r != null) {
8609            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
8610        }
8611    }
8612
8613    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
8614        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
8615            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
8616                return true;
8617            }
8618        }
8619        return false;
8620    }
8621
8622    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
8623    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
8624    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
8625
8626    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
8627            int flags) {
8628        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
8629        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
8630    }
8631
8632    private void updatePermissionsLPw(String changingPkg,
8633            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
8634        // Make sure there are no dangling permission trees.
8635        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
8636        while (it.hasNext()) {
8637            final BasePermission bp = it.next();
8638            if (bp.packageSetting == null) {
8639                // We may not yet have parsed the package, so just see if
8640                // we still know about its settings.
8641                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8642            }
8643            if (bp.packageSetting == null) {
8644                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
8645                        + " from package " + bp.sourcePackage);
8646                it.remove();
8647            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8648                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8649                    Slog.i(TAG, "Removing old permission tree: " + bp.name
8650                            + " from package " + bp.sourcePackage);
8651                    flags |= UPDATE_PERMISSIONS_ALL;
8652                    it.remove();
8653                }
8654            }
8655        }
8656
8657        // Make sure all dynamic permissions have been assigned to a package,
8658        // and make sure there are no dangling permissions.
8659        it = mSettings.mPermissions.values().iterator();
8660        while (it.hasNext()) {
8661            final BasePermission bp = it.next();
8662            if (bp.type == BasePermission.TYPE_DYNAMIC) {
8663                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
8664                        + bp.name + " pkg=" + bp.sourcePackage
8665                        + " info=" + bp.pendingInfo);
8666                if (bp.packageSetting == null && bp.pendingInfo != null) {
8667                    final BasePermission tree = findPermissionTreeLP(bp.name);
8668                    if (tree != null && tree.perm != null) {
8669                        bp.packageSetting = tree.packageSetting;
8670                        bp.perm = new PackageParser.Permission(tree.perm.owner,
8671                                new PermissionInfo(bp.pendingInfo));
8672                        bp.perm.info.packageName = tree.perm.info.packageName;
8673                        bp.perm.info.name = bp.name;
8674                        bp.uid = tree.uid;
8675                    }
8676                }
8677            }
8678            if (bp.packageSetting == null) {
8679                // We may not yet have parsed the package, so just see if
8680                // we still know about its settings.
8681                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
8682            }
8683            if (bp.packageSetting == null) {
8684                Slog.w(TAG, "Removing dangling permission: " + bp.name
8685                        + " from package " + bp.sourcePackage);
8686                it.remove();
8687            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
8688                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
8689                    Slog.i(TAG, "Removing old permission: " + bp.name
8690                            + " from package " + bp.sourcePackage);
8691                    flags |= UPDATE_PERMISSIONS_ALL;
8692                    it.remove();
8693                }
8694            }
8695        }
8696
8697        // Now update the permissions for all packages, in particular
8698        // replace the granted permissions of the system packages.
8699        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
8700            for (PackageParser.Package pkg : mPackages.values()) {
8701                if (pkg != pkgInfo) {
8702                    // Only replace for packages on requested volume
8703                    final String volumeUuid = getVolumeUuidForPackage(pkg);
8704                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
8705                            && Objects.equals(replaceVolumeUuid, volumeUuid);
8706                    grantPermissionsLPw(pkg, replace, changingPkg);
8707                }
8708            }
8709        }
8710
8711        if (pkgInfo != null) {
8712            // Only replace for packages on requested volume
8713            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
8714            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
8715                    && Objects.equals(replaceVolumeUuid, volumeUuid);
8716            grantPermissionsLPw(pkgInfo, replace, changingPkg);
8717        }
8718    }
8719
8720    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
8721            String packageOfInterest) {
8722        // IMPORTANT: There are two types of permissions: install and runtime.
8723        // Install time permissions are granted when the app is installed to
8724        // all device users and users added in the future. Runtime permissions
8725        // are granted at runtime explicitly to specific users. Normal and signature
8726        // protected permissions are install time permissions. Dangerous permissions
8727        // are install permissions if the app's target SDK is Lollipop MR1 or older,
8728        // otherwise they are runtime permissions. This function does not manage
8729        // runtime permissions except for the case an app targeting Lollipop MR1
8730        // being upgraded to target a newer SDK, in which case dangerous permissions
8731        // are transformed from install time to runtime ones.
8732
8733        final PackageSetting ps = (PackageSetting) pkg.mExtras;
8734        if (ps == null) {
8735            return;
8736        }
8737
8738        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
8739
8740        PermissionsState permissionsState = ps.getPermissionsState();
8741        PermissionsState origPermissions = permissionsState;
8742
8743        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
8744
8745        boolean runtimePermissionsRevoked = false;
8746        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
8747
8748        boolean changedInstallPermission = false;
8749
8750        if (replace) {
8751            ps.installPermissionsFixed = false;
8752            if (!ps.isSharedUser()) {
8753                origPermissions = new PermissionsState(permissionsState);
8754                permissionsState.reset();
8755            } else {
8756                // We need to know only about runtime permission changes since the
8757                // calling code always writes the install permissions state but
8758                // the runtime ones are written only if changed. The only cases of
8759                // changed runtime permissions here are promotion of an install to
8760                // runtime and revocation of a runtime from a shared user.
8761                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
8762                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
8763                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
8764                    runtimePermissionsRevoked = true;
8765                }
8766            }
8767        }
8768
8769        permissionsState.setGlobalGids(mGlobalGids);
8770
8771        final int N = pkg.requestedPermissions.size();
8772        for (int i=0; i<N; i++) {
8773            final String name = pkg.requestedPermissions.get(i);
8774            final BasePermission bp = mSettings.mPermissions.get(name);
8775
8776            if (DEBUG_INSTALL) {
8777                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
8778            }
8779
8780            if (bp == null || bp.packageSetting == null) {
8781                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8782                    Slog.w(TAG, "Unknown permission " + name
8783                            + " in package " + pkg.packageName);
8784                }
8785                continue;
8786            }
8787
8788            final String perm = bp.name;
8789            boolean allowedSig = false;
8790            int grant = GRANT_DENIED;
8791
8792            // Keep track of app op permissions.
8793            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
8794                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
8795                if (pkgs == null) {
8796                    pkgs = new ArraySet<>();
8797                    mAppOpPermissionPackages.put(bp.name, pkgs);
8798                }
8799                pkgs.add(pkg.packageName);
8800            }
8801
8802            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
8803            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
8804                    >= Build.VERSION_CODES.M;
8805            switch (level) {
8806                case PermissionInfo.PROTECTION_NORMAL: {
8807                    // For all apps normal permissions are install time ones.
8808                    grant = GRANT_INSTALL;
8809                } break;
8810
8811                case PermissionInfo.PROTECTION_DANGEROUS: {
8812                    // If a permission review is required for legacy apps we represent
8813                    // their permissions as always granted runtime ones since we need
8814                    // to keep the review required permission flag per user while an
8815                    // install permission's state is shared across all users.
8816                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
8817                        // For legacy apps dangerous permissions are install time ones.
8818                        grant = GRANT_INSTALL;
8819                    } else if (origPermissions.hasInstallPermission(bp.name)) {
8820                        // For legacy apps that became modern, install becomes runtime.
8821                        grant = GRANT_UPGRADE;
8822                    } else if (mPromoteSystemApps
8823                            && isSystemApp(ps)
8824                            && mExistingSystemPackages.contains(ps.name)) {
8825                        // For legacy system apps, install becomes runtime.
8826                        // We cannot check hasInstallPermission() for system apps since those
8827                        // permissions were granted implicitly and not persisted pre-M.
8828                        grant = GRANT_UPGRADE;
8829                    } else {
8830                        // For modern apps keep runtime permissions unchanged.
8831                        grant = GRANT_RUNTIME;
8832                    }
8833                } break;
8834
8835                case PermissionInfo.PROTECTION_SIGNATURE: {
8836                    // For all apps signature permissions are install time ones.
8837                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
8838                    if (allowedSig) {
8839                        grant = GRANT_INSTALL;
8840                    }
8841                } break;
8842            }
8843
8844            if (DEBUG_INSTALL) {
8845                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
8846            }
8847
8848            if (grant != GRANT_DENIED) {
8849                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
8850                    // If this is an existing, non-system package, then
8851                    // we can't add any new permissions to it.
8852                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
8853                        // Except...  if this is a permission that was added
8854                        // to the platform (note: need to only do this when
8855                        // updating the platform).
8856                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
8857                            grant = GRANT_DENIED;
8858                        }
8859                    }
8860                }
8861
8862                switch (grant) {
8863                    case GRANT_INSTALL: {
8864                        // Revoke this as runtime permission to handle the case of
8865                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
8866                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8867                            if (origPermissions.getRuntimePermissionState(
8868                                    bp.name, userId) != null) {
8869                                // Revoke the runtime permission and clear the flags.
8870                                origPermissions.revokeRuntimePermission(bp, userId);
8871                                origPermissions.updatePermissionFlags(bp, userId,
8872                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
8873                                // If we revoked a permission permission, we have to write.
8874                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8875                                        changedRuntimePermissionUserIds, userId);
8876                            }
8877                        }
8878                        // Grant an install permission.
8879                        if (permissionsState.grantInstallPermission(bp) !=
8880                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
8881                            changedInstallPermission = true;
8882                        }
8883                    } break;
8884
8885                    case GRANT_RUNTIME: {
8886                        // Grant previously granted runtime permissions.
8887                        for (int userId : UserManagerService.getInstance().getUserIds()) {
8888                            PermissionState permissionState = origPermissions
8889                                    .getRuntimePermissionState(bp.name, userId);
8890                            int flags = permissionState != null
8891                                    ? permissionState.getFlags() : 0;
8892                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
8893                                if (permissionsState.grantRuntimePermission(bp, userId) ==
8894                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8895                                    // If we cannot put the permission as it was, we have to write.
8896                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8897                                            changedRuntimePermissionUserIds, userId);
8898                                }
8899                                // If the app supports runtime permissions no need for a review.
8900                                if (Build.PERMISSIONS_REVIEW_REQUIRED
8901                                        && appSupportsRuntimePermissions
8902                                        && (flags & PackageManager
8903                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
8904                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
8905                                    // Since we changed the flags, we have to write.
8906                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8907                                            changedRuntimePermissionUserIds, userId);
8908                                }
8909                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
8910                                    && !appSupportsRuntimePermissions) {
8911                                // For legacy apps that need a permission review, every new
8912                                // runtime permission is granted but it is pending a review.
8913                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
8914                                    permissionsState.grantRuntimePermission(bp, userId);
8915                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
8916                                    // We changed the permission and flags, hence have to write.
8917                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8918                                            changedRuntimePermissionUserIds, userId);
8919                                }
8920                            }
8921                            // Propagate the permission flags.
8922                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
8923                        }
8924                    } break;
8925
8926                    case GRANT_UPGRADE: {
8927                        // Grant runtime permissions for a previously held install permission.
8928                        PermissionState permissionState = origPermissions
8929                                .getInstallPermissionState(bp.name);
8930                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
8931
8932                        if (origPermissions.revokeInstallPermission(bp)
8933                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
8934                            // We will be transferring the permission flags, so clear them.
8935                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
8936                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
8937                            changedInstallPermission = true;
8938                        }
8939
8940                        // If the permission is not to be promoted to runtime we ignore it and
8941                        // also its other flags as they are not applicable to install permissions.
8942                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
8943                            for (int userId : currentUserIds) {
8944                                if (permissionsState.grantRuntimePermission(bp, userId) !=
8945                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8946                                    // Transfer the permission flags.
8947                                    permissionsState.updatePermissionFlags(bp, userId,
8948                                            flags, flags);
8949                                    // If we granted the permission, we have to write.
8950                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
8951                                            changedRuntimePermissionUserIds, userId);
8952                                }
8953                            }
8954                        }
8955                    } break;
8956
8957                    default: {
8958                        if (packageOfInterest == null
8959                                || packageOfInterest.equals(pkg.packageName)) {
8960                            Slog.w(TAG, "Not granting permission " + perm
8961                                    + " to package " + pkg.packageName
8962                                    + " because it was previously installed without");
8963                        }
8964                    } break;
8965                }
8966            } else {
8967                if (permissionsState.revokeInstallPermission(bp) !=
8968                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
8969                    // Also drop the permission flags.
8970                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
8971                            PackageManager.MASK_PERMISSION_FLAGS, 0);
8972                    changedInstallPermission = true;
8973                    Slog.i(TAG, "Un-granting permission " + perm
8974                            + " from package " + pkg.packageName
8975                            + " (protectionLevel=" + bp.protectionLevel
8976                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8977                            + ")");
8978                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
8979                    // Don't print warning for app op permissions, since it is fine for them
8980                    // not to be granted, there is a UI for the user to decide.
8981                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
8982                        Slog.w(TAG, "Not granting permission " + perm
8983                                + " to package " + pkg.packageName
8984                                + " (protectionLevel=" + bp.protectionLevel
8985                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
8986                                + ")");
8987                    }
8988                }
8989            }
8990        }
8991
8992        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
8993                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
8994            // This is the first that we have heard about this package, so the
8995            // permissions we have now selected are fixed until explicitly
8996            // changed.
8997            ps.installPermissionsFixed = true;
8998        }
8999
9000        // Persist the runtime permissions state for users with changes. If permissions
9001        // were revoked because no app in the shared user declares them we have to
9002        // write synchronously to avoid losing runtime permissions state.
9003        for (int userId : changedRuntimePermissionUserIds) {
9004            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9005        }
9006
9007        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9008    }
9009
9010    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9011        boolean allowed = false;
9012        final int NP = PackageParser.NEW_PERMISSIONS.length;
9013        for (int ip=0; ip<NP; ip++) {
9014            final PackageParser.NewPermissionInfo npi
9015                    = PackageParser.NEW_PERMISSIONS[ip];
9016            if (npi.name.equals(perm)
9017                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9018                allowed = true;
9019                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9020                        + pkg.packageName);
9021                break;
9022            }
9023        }
9024        return allowed;
9025    }
9026
9027    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9028            BasePermission bp, PermissionsState origPermissions) {
9029        boolean allowed;
9030        allowed = (compareSignatures(
9031                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9032                        == PackageManager.SIGNATURE_MATCH)
9033                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9034                        == PackageManager.SIGNATURE_MATCH);
9035        if (!allowed && (bp.protectionLevel
9036                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9037            if (isSystemApp(pkg)) {
9038                // For updated system applications, a system permission
9039                // is granted only if it had been defined by the original application.
9040                if (pkg.isUpdatedSystemApp()) {
9041                    final PackageSetting sysPs = mSettings
9042                            .getDisabledSystemPkgLPr(pkg.packageName);
9043                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
9044                        // If the original was granted this permission, we take
9045                        // that grant decision as read and propagate it to the
9046                        // update.
9047                        if (sysPs.isPrivileged()) {
9048                            allowed = true;
9049                        }
9050                    } else {
9051                        // The system apk may have been updated with an older
9052                        // version of the one on the data partition, but which
9053                        // granted a new system permission that it didn't have
9054                        // before.  In this case we do want to allow the app to
9055                        // now get the new permission if the ancestral apk is
9056                        // privileged to get it.
9057                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
9058                            for (int j=0;
9059                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
9060                                if (perm.equals(
9061                                        sysPs.pkg.requestedPermissions.get(j))) {
9062                                    allowed = true;
9063                                    break;
9064                                }
9065                            }
9066                        }
9067                    }
9068                } else {
9069                    allowed = isPrivilegedApp(pkg);
9070                }
9071            }
9072        }
9073        if (!allowed) {
9074            if (!allowed && (bp.protectionLevel
9075                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9076                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9077                // If this was a previously normal/dangerous permission that got moved
9078                // to a system permission as part of the runtime permission redesign, then
9079                // we still want to blindly grant it to old apps.
9080                allowed = true;
9081            }
9082            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9083                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9084                // If this permission is to be granted to the system installer and
9085                // this app is an installer, then it gets the permission.
9086                allowed = true;
9087            }
9088            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9089                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9090                // If this permission is to be granted to the system verifier and
9091                // this app is a verifier, then it gets the permission.
9092                allowed = true;
9093            }
9094            if (!allowed && (bp.protectionLevel
9095                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9096                    && isSystemApp(pkg)) {
9097                // Any pre-installed system app is allowed to get this permission.
9098                allowed = true;
9099            }
9100            if (!allowed && (bp.protectionLevel
9101                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9102                // For development permissions, a development permission
9103                // is granted only if it was already granted.
9104                allowed = origPermissions.hasInstallPermission(perm);
9105            }
9106        }
9107        return allowed;
9108    }
9109
9110    final class ActivityIntentResolver
9111            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9112        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9113                boolean defaultOnly, int userId) {
9114            if (!sUserManager.exists(userId)) return null;
9115            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9116            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9117        }
9118
9119        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9120                int userId) {
9121            if (!sUserManager.exists(userId)) return null;
9122            mFlags = flags;
9123            return super.queryIntent(intent, resolvedType,
9124                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9125        }
9126
9127        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9128                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9129            if (!sUserManager.exists(userId)) return null;
9130            if (packageActivities == null) {
9131                return null;
9132            }
9133            mFlags = flags;
9134            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9135            final int N = packageActivities.size();
9136            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9137                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9138
9139            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9140            for (int i = 0; i < N; ++i) {
9141                intentFilters = packageActivities.get(i).intents;
9142                if (intentFilters != null && intentFilters.size() > 0) {
9143                    PackageParser.ActivityIntentInfo[] array =
9144                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9145                    intentFilters.toArray(array);
9146                    listCut.add(array);
9147                }
9148            }
9149            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9150        }
9151
9152        public final void addActivity(PackageParser.Activity a, String type) {
9153            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9154            mActivities.put(a.getComponentName(), a);
9155            if (DEBUG_SHOW_INFO)
9156                Log.v(
9157                TAG, "  " + type + " " +
9158                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9159            if (DEBUG_SHOW_INFO)
9160                Log.v(TAG, "    Class=" + a.info.name);
9161            final int NI = a.intents.size();
9162            for (int j=0; j<NI; j++) {
9163                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9164                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9165                    intent.setPriority(0);
9166                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9167                            + a.className + " with priority > 0, forcing to 0");
9168                }
9169                if (DEBUG_SHOW_INFO) {
9170                    Log.v(TAG, "    IntentFilter:");
9171                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9172                }
9173                if (!intent.debugCheck()) {
9174                    Log.w(TAG, "==> For Activity " + a.info.name);
9175                }
9176                addFilter(intent);
9177            }
9178        }
9179
9180        public final void removeActivity(PackageParser.Activity a, String type) {
9181            mActivities.remove(a.getComponentName());
9182            if (DEBUG_SHOW_INFO) {
9183                Log.v(TAG, "  " + type + " "
9184                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9185                                : a.info.name) + ":");
9186                Log.v(TAG, "    Class=" + a.info.name);
9187            }
9188            final int NI = a.intents.size();
9189            for (int j=0; j<NI; j++) {
9190                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9191                if (DEBUG_SHOW_INFO) {
9192                    Log.v(TAG, "    IntentFilter:");
9193                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9194                }
9195                removeFilter(intent);
9196            }
9197        }
9198
9199        @Override
9200        protected boolean allowFilterResult(
9201                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9202            ActivityInfo filterAi = filter.activity.info;
9203            for (int i=dest.size()-1; i>=0; i--) {
9204                ActivityInfo destAi = dest.get(i).activityInfo;
9205                if (destAi.name == filterAi.name
9206                        && destAi.packageName == filterAi.packageName) {
9207                    return false;
9208                }
9209            }
9210            return true;
9211        }
9212
9213        @Override
9214        protected ActivityIntentInfo[] newArray(int size) {
9215            return new ActivityIntentInfo[size];
9216        }
9217
9218        @Override
9219        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9220            if (!sUserManager.exists(userId)) return true;
9221            PackageParser.Package p = filter.activity.owner;
9222            if (p != null) {
9223                PackageSetting ps = (PackageSetting)p.mExtras;
9224                if (ps != null) {
9225                    // System apps are never considered stopped for purposes of
9226                    // filtering, because there may be no way for the user to
9227                    // actually re-launch them.
9228                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9229                            && ps.getStopped(userId);
9230                }
9231            }
9232            return false;
9233        }
9234
9235        @Override
9236        protected boolean isPackageForFilter(String packageName,
9237                PackageParser.ActivityIntentInfo info) {
9238            return packageName.equals(info.activity.owner.packageName);
9239        }
9240
9241        @Override
9242        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9243                int match, int userId) {
9244            if (!sUserManager.exists(userId)) return null;
9245            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9246                return null;
9247            }
9248            final PackageParser.Activity activity = info.activity;
9249            if (mSafeMode && (activity.info.applicationInfo.flags
9250                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9251                return null;
9252            }
9253            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9254            if (ps == null) {
9255                return null;
9256            }
9257            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9258                    ps.readUserState(userId), userId);
9259            if (ai == null) {
9260                return null;
9261            }
9262            final ResolveInfo res = new ResolveInfo();
9263            res.activityInfo = ai;
9264            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9265                res.filter = info;
9266            }
9267            if (info != null) {
9268                res.handleAllWebDataURI = info.handleAllWebDataURI();
9269            }
9270            res.priority = info.getPriority();
9271            res.preferredOrder = activity.owner.mPreferredOrder;
9272            //System.out.println("Result: " + res.activityInfo.className +
9273            //                   " = " + res.priority);
9274            res.match = match;
9275            res.isDefault = info.hasDefault;
9276            res.labelRes = info.labelRes;
9277            res.nonLocalizedLabel = info.nonLocalizedLabel;
9278            if (userNeedsBadging(userId)) {
9279                res.noResourceId = true;
9280            } else {
9281                res.icon = info.icon;
9282            }
9283            res.iconResourceId = info.icon;
9284            res.system = res.activityInfo.applicationInfo.isSystemApp();
9285            return res;
9286        }
9287
9288        @Override
9289        protected void sortResults(List<ResolveInfo> results) {
9290            Collections.sort(results, mResolvePrioritySorter);
9291        }
9292
9293        @Override
9294        protected void dumpFilter(PrintWriter out, String prefix,
9295                PackageParser.ActivityIntentInfo filter) {
9296            out.print(prefix); out.print(
9297                    Integer.toHexString(System.identityHashCode(filter.activity)));
9298                    out.print(' ');
9299                    filter.activity.printComponentShortName(out);
9300                    out.print(" filter ");
9301                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9302        }
9303
9304        @Override
9305        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9306            return filter.activity;
9307        }
9308
9309        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9310            PackageParser.Activity activity = (PackageParser.Activity)label;
9311            out.print(prefix); out.print(
9312                    Integer.toHexString(System.identityHashCode(activity)));
9313                    out.print(' ');
9314                    activity.printComponentShortName(out);
9315            if (count > 1) {
9316                out.print(" ("); out.print(count); out.print(" filters)");
9317            }
9318            out.println();
9319        }
9320
9321//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9322//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9323//            final List<ResolveInfo> retList = Lists.newArrayList();
9324//            while (i.hasNext()) {
9325//                final ResolveInfo resolveInfo = i.next();
9326//                if (isEnabledLP(resolveInfo.activityInfo)) {
9327//                    retList.add(resolveInfo);
9328//                }
9329//            }
9330//            return retList;
9331//        }
9332
9333        // Keys are String (activity class name), values are Activity.
9334        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9335                = new ArrayMap<ComponentName, PackageParser.Activity>();
9336        private int mFlags;
9337    }
9338
9339    private final class ServiceIntentResolver
9340            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9341        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9342                boolean defaultOnly, int userId) {
9343            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9344            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9345        }
9346
9347        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9348                int userId) {
9349            if (!sUserManager.exists(userId)) return null;
9350            mFlags = flags;
9351            return super.queryIntent(intent, resolvedType,
9352                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9353        }
9354
9355        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9356                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9357            if (!sUserManager.exists(userId)) return null;
9358            if (packageServices == null) {
9359                return null;
9360            }
9361            mFlags = flags;
9362            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9363            final int N = packageServices.size();
9364            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9365                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9366
9367            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9368            for (int i = 0; i < N; ++i) {
9369                intentFilters = packageServices.get(i).intents;
9370                if (intentFilters != null && intentFilters.size() > 0) {
9371                    PackageParser.ServiceIntentInfo[] array =
9372                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9373                    intentFilters.toArray(array);
9374                    listCut.add(array);
9375                }
9376            }
9377            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9378        }
9379
9380        public final void addService(PackageParser.Service s) {
9381            mServices.put(s.getComponentName(), s);
9382            if (DEBUG_SHOW_INFO) {
9383                Log.v(TAG, "  "
9384                        + (s.info.nonLocalizedLabel != null
9385                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9386                Log.v(TAG, "    Class=" + s.info.name);
9387            }
9388            final int NI = s.intents.size();
9389            int j;
9390            for (j=0; j<NI; j++) {
9391                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9392                if (DEBUG_SHOW_INFO) {
9393                    Log.v(TAG, "    IntentFilter:");
9394                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9395                }
9396                if (!intent.debugCheck()) {
9397                    Log.w(TAG, "==> For Service " + s.info.name);
9398                }
9399                addFilter(intent);
9400            }
9401        }
9402
9403        public final void removeService(PackageParser.Service s) {
9404            mServices.remove(s.getComponentName());
9405            if (DEBUG_SHOW_INFO) {
9406                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9407                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9408                Log.v(TAG, "    Class=" + s.info.name);
9409            }
9410            final int NI = s.intents.size();
9411            int j;
9412            for (j=0; j<NI; j++) {
9413                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9414                if (DEBUG_SHOW_INFO) {
9415                    Log.v(TAG, "    IntentFilter:");
9416                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9417                }
9418                removeFilter(intent);
9419            }
9420        }
9421
9422        @Override
9423        protected boolean allowFilterResult(
9424                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9425            ServiceInfo filterSi = filter.service.info;
9426            for (int i=dest.size()-1; i>=0; i--) {
9427                ServiceInfo destAi = dest.get(i).serviceInfo;
9428                if (destAi.name == filterSi.name
9429                        && destAi.packageName == filterSi.packageName) {
9430                    return false;
9431                }
9432            }
9433            return true;
9434        }
9435
9436        @Override
9437        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9438            return new PackageParser.ServiceIntentInfo[size];
9439        }
9440
9441        @Override
9442        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9443            if (!sUserManager.exists(userId)) return true;
9444            PackageParser.Package p = filter.service.owner;
9445            if (p != null) {
9446                PackageSetting ps = (PackageSetting)p.mExtras;
9447                if (ps != null) {
9448                    // System apps are never considered stopped for purposes of
9449                    // filtering, because there may be no way for the user to
9450                    // actually re-launch them.
9451                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9452                            && ps.getStopped(userId);
9453                }
9454            }
9455            return false;
9456        }
9457
9458        @Override
9459        protected boolean isPackageForFilter(String packageName,
9460                PackageParser.ServiceIntentInfo info) {
9461            return packageName.equals(info.service.owner.packageName);
9462        }
9463
9464        @Override
9465        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
9466                int match, int userId) {
9467            if (!sUserManager.exists(userId)) return null;
9468            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
9469            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
9470                return null;
9471            }
9472            final PackageParser.Service service = info.service;
9473            if (mSafeMode && (service.info.applicationInfo.flags
9474                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
9475                return null;
9476            }
9477            PackageSetting ps = (PackageSetting) service.owner.mExtras;
9478            if (ps == null) {
9479                return null;
9480            }
9481            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
9482                    ps.readUserState(userId), userId);
9483            if (si == null) {
9484                return null;
9485            }
9486            final ResolveInfo res = new ResolveInfo();
9487            res.serviceInfo = si;
9488            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9489                res.filter = filter;
9490            }
9491            res.priority = info.getPriority();
9492            res.preferredOrder = service.owner.mPreferredOrder;
9493            res.match = match;
9494            res.isDefault = info.hasDefault;
9495            res.labelRes = info.labelRes;
9496            res.nonLocalizedLabel = info.nonLocalizedLabel;
9497            res.icon = info.icon;
9498            res.system = res.serviceInfo.applicationInfo.isSystemApp();
9499            return res;
9500        }
9501
9502        @Override
9503        protected void sortResults(List<ResolveInfo> results) {
9504            Collections.sort(results, mResolvePrioritySorter);
9505        }
9506
9507        @Override
9508        protected void dumpFilter(PrintWriter out, String prefix,
9509                PackageParser.ServiceIntentInfo filter) {
9510            out.print(prefix); out.print(
9511                    Integer.toHexString(System.identityHashCode(filter.service)));
9512                    out.print(' ');
9513                    filter.service.printComponentShortName(out);
9514                    out.print(" filter ");
9515                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9516        }
9517
9518        @Override
9519        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
9520            return filter.service;
9521        }
9522
9523        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9524            PackageParser.Service service = (PackageParser.Service)label;
9525            out.print(prefix); out.print(
9526                    Integer.toHexString(System.identityHashCode(service)));
9527                    out.print(' ');
9528                    service.printComponentShortName(out);
9529            if (count > 1) {
9530                out.print(" ("); out.print(count); out.print(" filters)");
9531            }
9532            out.println();
9533        }
9534
9535//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9536//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9537//            final List<ResolveInfo> retList = Lists.newArrayList();
9538//            while (i.hasNext()) {
9539//                final ResolveInfo resolveInfo = (ResolveInfo) i;
9540//                if (isEnabledLP(resolveInfo.serviceInfo)) {
9541//                    retList.add(resolveInfo);
9542//                }
9543//            }
9544//            return retList;
9545//        }
9546
9547        // Keys are String (activity class name), values are Activity.
9548        private final ArrayMap<ComponentName, PackageParser.Service> mServices
9549                = new ArrayMap<ComponentName, PackageParser.Service>();
9550        private int mFlags;
9551    };
9552
9553    private final class ProviderIntentResolver
9554            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
9555        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9556                boolean defaultOnly, int userId) {
9557            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9558            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9559        }
9560
9561        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9562                int userId) {
9563            if (!sUserManager.exists(userId))
9564                return null;
9565            mFlags = flags;
9566            return super.queryIntent(intent, resolvedType,
9567                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9568        }
9569
9570        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9571                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
9572            if (!sUserManager.exists(userId))
9573                return null;
9574            if (packageProviders == null) {
9575                return null;
9576            }
9577            mFlags = flags;
9578            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
9579            final int N = packageProviders.size();
9580            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
9581                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
9582
9583            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
9584            for (int i = 0; i < N; ++i) {
9585                intentFilters = packageProviders.get(i).intents;
9586                if (intentFilters != null && intentFilters.size() > 0) {
9587                    PackageParser.ProviderIntentInfo[] array =
9588                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
9589                    intentFilters.toArray(array);
9590                    listCut.add(array);
9591                }
9592            }
9593            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9594        }
9595
9596        public final void addProvider(PackageParser.Provider p) {
9597            if (mProviders.containsKey(p.getComponentName())) {
9598                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
9599                return;
9600            }
9601
9602            mProviders.put(p.getComponentName(), p);
9603            if (DEBUG_SHOW_INFO) {
9604                Log.v(TAG, "  "
9605                        + (p.info.nonLocalizedLabel != null
9606                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
9607                Log.v(TAG, "    Class=" + p.info.name);
9608            }
9609            final int NI = p.intents.size();
9610            int j;
9611            for (j = 0; j < NI; j++) {
9612                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9613                if (DEBUG_SHOW_INFO) {
9614                    Log.v(TAG, "    IntentFilter:");
9615                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9616                }
9617                if (!intent.debugCheck()) {
9618                    Log.w(TAG, "==> For Provider " + p.info.name);
9619                }
9620                addFilter(intent);
9621            }
9622        }
9623
9624        public final void removeProvider(PackageParser.Provider p) {
9625            mProviders.remove(p.getComponentName());
9626            if (DEBUG_SHOW_INFO) {
9627                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
9628                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
9629                Log.v(TAG, "    Class=" + p.info.name);
9630            }
9631            final int NI = p.intents.size();
9632            int j;
9633            for (j = 0; j < NI; j++) {
9634                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
9635                if (DEBUG_SHOW_INFO) {
9636                    Log.v(TAG, "    IntentFilter:");
9637                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9638                }
9639                removeFilter(intent);
9640            }
9641        }
9642
9643        @Override
9644        protected boolean allowFilterResult(
9645                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
9646            ProviderInfo filterPi = filter.provider.info;
9647            for (int i = dest.size() - 1; i >= 0; i--) {
9648                ProviderInfo destPi = dest.get(i).providerInfo;
9649                if (destPi.name == filterPi.name
9650                        && destPi.packageName == filterPi.packageName) {
9651                    return false;
9652                }
9653            }
9654            return true;
9655        }
9656
9657        @Override
9658        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
9659            return new PackageParser.ProviderIntentInfo[size];
9660        }
9661
9662        @Override
9663        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
9664            if (!sUserManager.exists(userId))
9665                return true;
9666            PackageParser.Package p = filter.provider.owner;
9667            if (p != null) {
9668                PackageSetting ps = (PackageSetting) p.mExtras;
9669                if (ps != null) {
9670                    // System apps are never considered stopped for purposes of
9671                    // filtering, because there may be no way for the user to
9672                    // actually re-launch them.
9673                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9674                            && ps.getStopped(userId);
9675                }
9676            }
9677            return false;
9678        }
9679
9680        @Override
9681        protected boolean isPackageForFilter(String packageName,
9682                PackageParser.ProviderIntentInfo info) {
9683            return packageName.equals(info.provider.owner.packageName);
9684        }
9685
9686        @Override
9687        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
9688                int match, int userId) {
9689            if (!sUserManager.exists(userId))
9690                return null;
9691            final PackageParser.ProviderIntentInfo info = filter;
9692            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
9693                return null;
9694            }
9695            final PackageParser.Provider provider = info.provider;
9696            if (mSafeMode && (provider.info.applicationInfo.flags
9697                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
9698                return null;
9699            }
9700            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
9701            if (ps == null) {
9702                return null;
9703            }
9704            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
9705                    ps.readUserState(userId), userId);
9706            if (pi == null) {
9707                return null;
9708            }
9709            final ResolveInfo res = new ResolveInfo();
9710            res.providerInfo = pi;
9711            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
9712                res.filter = filter;
9713            }
9714            res.priority = info.getPriority();
9715            res.preferredOrder = provider.owner.mPreferredOrder;
9716            res.match = match;
9717            res.isDefault = info.hasDefault;
9718            res.labelRes = info.labelRes;
9719            res.nonLocalizedLabel = info.nonLocalizedLabel;
9720            res.icon = info.icon;
9721            res.system = res.providerInfo.applicationInfo.isSystemApp();
9722            return res;
9723        }
9724
9725        @Override
9726        protected void sortResults(List<ResolveInfo> results) {
9727            Collections.sort(results, mResolvePrioritySorter);
9728        }
9729
9730        @Override
9731        protected void dumpFilter(PrintWriter out, String prefix,
9732                PackageParser.ProviderIntentInfo filter) {
9733            out.print(prefix);
9734            out.print(
9735                    Integer.toHexString(System.identityHashCode(filter.provider)));
9736            out.print(' ');
9737            filter.provider.printComponentShortName(out);
9738            out.print(" filter ");
9739            out.println(Integer.toHexString(System.identityHashCode(filter)));
9740        }
9741
9742        @Override
9743        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
9744            return filter.provider;
9745        }
9746
9747        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9748            PackageParser.Provider provider = (PackageParser.Provider)label;
9749            out.print(prefix); out.print(
9750                    Integer.toHexString(System.identityHashCode(provider)));
9751                    out.print(' ');
9752                    provider.printComponentShortName(out);
9753            if (count > 1) {
9754                out.print(" ("); out.print(count); out.print(" filters)");
9755            }
9756            out.println();
9757        }
9758
9759        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
9760                = new ArrayMap<ComponentName, PackageParser.Provider>();
9761        private int mFlags;
9762    }
9763
9764    private static final class EphemeralIntentResolver
9765            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
9766        @Override
9767        protected EphemeralResolveIntentInfo[] newArray(int size) {
9768            return new EphemeralResolveIntentInfo[size];
9769        }
9770
9771        @Override
9772        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
9773            return true;
9774        }
9775
9776        @Override
9777        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
9778                int userId) {
9779            if (!sUserManager.exists(userId)) {
9780                return null;
9781            }
9782            return info.getEphemeralResolveInfo();
9783        }
9784    }
9785
9786    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
9787            new Comparator<ResolveInfo>() {
9788        public int compare(ResolveInfo r1, ResolveInfo r2) {
9789            int v1 = r1.priority;
9790            int v2 = r2.priority;
9791            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
9792            if (v1 != v2) {
9793                return (v1 > v2) ? -1 : 1;
9794            }
9795            v1 = r1.preferredOrder;
9796            v2 = r2.preferredOrder;
9797            if (v1 != v2) {
9798                return (v1 > v2) ? -1 : 1;
9799            }
9800            if (r1.isDefault != r2.isDefault) {
9801                return r1.isDefault ? -1 : 1;
9802            }
9803            v1 = r1.match;
9804            v2 = r2.match;
9805            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
9806            if (v1 != v2) {
9807                return (v1 > v2) ? -1 : 1;
9808            }
9809            if (r1.system != r2.system) {
9810                return r1.system ? -1 : 1;
9811            }
9812            if (r1.activityInfo != null) {
9813                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
9814            }
9815            if (r1.serviceInfo != null) {
9816                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
9817            }
9818            if (r1.providerInfo != null) {
9819                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
9820            }
9821            return 0;
9822        }
9823    };
9824
9825    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
9826            new Comparator<ProviderInfo>() {
9827        public int compare(ProviderInfo p1, ProviderInfo p2) {
9828            final int v1 = p1.initOrder;
9829            final int v2 = p2.initOrder;
9830            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
9831        }
9832    };
9833
9834    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
9835            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
9836            final int[] userIds) {
9837        mHandler.post(new Runnable() {
9838            @Override
9839            public void run() {
9840                try {
9841                    final IActivityManager am = ActivityManagerNative.getDefault();
9842                    if (am == null) return;
9843                    final int[] resolvedUserIds;
9844                    if (userIds == null) {
9845                        resolvedUserIds = am.getRunningUserIds();
9846                    } else {
9847                        resolvedUserIds = userIds;
9848                    }
9849                    for (int id : resolvedUserIds) {
9850                        final Intent intent = new Intent(action,
9851                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
9852                        if (extras != null) {
9853                            intent.putExtras(extras);
9854                        }
9855                        if (targetPkg != null) {
9856                            intent.setPackage(targetPkg);
9857                        }
9858                        // Modify the UID when posting to other users
9859                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
9860                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
9861                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
9862                            intent.putExtra(Intent.EXTRA_UID, uid);
9863                        }
9864                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
9865                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
9866                        if (DEBUG_BROADCASTS) {
9867                            RuntimeException here = new RuntimeException("here");
9868                            here.fillInStackTrace();
9869                            Slog.d(TAG, "Sending to user " + id + ": "
9870                                    + intent.toShortString(false, true, false, false)
9871                                    + " " + intent.getExtras(), here);
9872                        }
9873                        am.broadcastIntent(null, intent, null, finishedReceiver,
9874                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
9875                                null, finishedReceiver != null, false, id);
9876                    }
9877                } catch (RemoteException ex) {
9878                }
9879            }
9880        });
9881    }
9882
9883    /**
9884     * Check if the external storage media is available. This is true if there
9885     * is a mounted external storage medium or if the external storage is
9886     * emulated.
9887     */
9888    private boolean isExternalMediaAvailable() {
9889        return mMediaMounted || Environment.isExternalStorageEmulated();
9890    }
9891
9892    @Override
9893    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
9894        // writer
9895        synchronized (mPackages) {
9896            if (!isExternalMediaAvailable()) {
9897                // If the external storage is no longer mounted at this point,
9898                // the caller may not have been able to delete all of this
9899                // packages files and can not delete any more.  Bail.
9900                return null;
9901            }
9902            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
9903            if (lastPackage != null) {
9904                pkgs.remove(lastPackage);
9905            }
9906            if (pkgs.size() > 0) {
9907                return pkgs.get(0);
9908            }
9909        }
9910        return null;
9911    }
9912
9913    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
9914        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
9915                userId, andCode ? 1 : 0, packageName);
9916        if (mSystemReady) {
9917            msg.sendToTarget();
9918        } else {
9919            if (mPostSystemReadyMessages == null) {
9920                mPostSystemReadyMessages = new ArrayList<>();
9921            }
9922            mPostSystemReadyMessages.add(msg);
9923        }
9924    }
9925
9926    void startCleaningPackages() {
9927        // reader
9928        synchronized (mPackages) {
9929            if (!isExternalMediaAvailable()) {
9930                return;
9931            }
9932            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
9933                return;
9934            }
9935        }
9936        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
9937        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
9938        IActivityManager am = ActivityManagerNative.getDefault();
9939        if (am != null) {
9940            try {
9941                am.startService(null, intent, null, mContext.getOpPackageName(),
9942                        UserHandle.USER_SYSTEM);
9943            } catch (RemoteException e) {
9944            }
9945        }
9946    }
9947
9948    @Override
9949    public void installPackage(String originPath, IPackageInstallObserver2 observer,
9950            int installFlags, String installerPackageName, VerificationParams verificationParams,
9951            String packageAbiOverride) {
9952        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
9953                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
9954    }
9955
9956    @Override
9957    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
9958            int installFlags, String installerPackageName, VerificationParams verificationParams,
9959            String packageAbiOverride, int userId) {
9960        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
9961
9962        final int callingUid = Binder.getCallingUid();
9963        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
9964
9965        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
9966            try {
9967                if (observer != null) {
9968                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
9969                }
9970            } catch (RemoteException re) {
9971            }
9972            return;
9973        }
9974
9975        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
9976            installFlags |= PackageManager.INSTALL_FROM_ADB;
9977
9978        } else {
9979            // Caller holds INSTALL_PACKAGES permission, so we're less strict
9980            // about installerPackageName.
9981
9982            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
9983            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
9984        }
9985
9986        UserHandle user;
9987        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
9988            user = UserHandle.ALL;
9989        } else {
9990            user = new UserHandle(userId);
9991        }
9992
9993        // Only system components can circumvent runtime permissions when installing.
9994        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
9995                && mContext.checkCallingOrSelfPermission(Manifest.permission
9996                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
9997            throw new SecurityException("You need the "
9998                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
9999                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10000        }
10001
10002        verificationParams.setInstallerUid(callingUid);
10003
10004        final File originFile = new File(originPath);
10005        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10006
10007        final Message msg = mHandler.obtainMessage(INIT_COPY);
10008        final InstallParams params = new InstallParams(origin, null, observer, installFlags,
10009                installerPackageName, null, verificationParams, user, packageAbiOverride, null);
10010        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10011        msg.obj = params;
10012
10013        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10014                System.identityHashCode(msg.obj));
10015        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10016                System.identityHashCode(msg.obj));
10017
10018        mHandler.sendMessage(msg);
10019    }
10020
10021    void installStage(String packageName, File stagedDir, String stagedCid,
10022            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10023            String installerPackageName, int installerUid, UserHandle user) {
10024        if (DEBUG_EPHEMERAL) {
10025            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10026                Slog.d(TAG, "Ephemeral install of " + packageName);
10027            }
10028        }
10029        final VerificationParams verifParams = new VerificationParams(
10030                null, sessionParams.originatingUri, sessionParams.referrerUri,
10031                sessionParams.originatingUid);
10032        verifParams.setInstallerUid(installerUid);
10033
10034        final OriginInfo origin;
10035        if (stagedDir != null) {
10036            origin = OriginInfo.fromStagedFile(stagedDir);
10037        } else {
10038            origin = OriginInfo.fromStagedContainer(stagedCid);
10039        }
10040
10041        final Message msg = mHandler.obtainMessage(INIT_COPY);
10042        final InstallParams params = new InstallParams(origin, null, observer,
10043                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10044                verifParams, user, sessionParams.abiOverride,
10045                sessionParams.grantedRuntimePermissions);
10046        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10047        msg.obj = params;
10048
10049        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10050                System.identityHashCode(msg.obj));
10051        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10052                System.identityHashCode(msg.obj));
10053
10054        mHandler.sendMessage(msg);
10055    }
10056
10057    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
10058        Bundle extras = new Bundle(1);
10059        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
10060
10061        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10062                packageName, extras, 0, null, null, new int[] {userId});
10063        try {
10064            IActivityManager am = ActivityManagerNative.getDefault();
10065            final boolean isSystem =
10066                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10067            if (isSystem && am.isUserRunning(userId, 0)) {
10068                // The just-installed/enabled app is bundled on the system, so presumed
10069                // to be able to run automatically without needing an explicit launch.
10070                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10071                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10072                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10073                        .setPackage(packageName);
10074                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10075                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10076            }
10077        } catch (RemoteException e) {
10078            // shouldn't happen
10079            Slog.w(TAG, "Unable to bootstrap installed package", e);
10080        }
10081    }
10082
10083    @Override
10084    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10085            int userId) {
10086        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10087        PackageSetting pkgSetting;
10088        final int uid = Binder.getCallingUid();
10089        enforceCrossUserPermission(uid, userId, true, true,
10090                "setApplicationHiddenSetting for user " + userId);
10091
10092        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10093            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10094            return false;
10095        }
10096
10097        long callingId = Binder.clearCallingIdentity();
10098        try {
10099            boolean sendAdded = false;
10100            boolean sendRemoved = false;
10101            // writer
10102            synchronized (mPackages) {
10103                pkgSetting = mSettings.mPackages.get(packageName);
10104                if (pkgSetting == null) {
10105                    return false;
10106                }
10107                if (pkgSetting.getHidden(userId) != hidden) {
10108                    pkgSetting.setHidden(hidden, userId);
10109                    mSettings.writePackageRestrictionsLPr(userId);
10110                    if (hidden) {
10111                        sendRemoved = true;
10112                    } else {
10113                        sendAdded = true;
10114                    }
10115                }
10116            }
10117            if (sendAdded) {
10118                sendPackageAddedForUser(packageName, pkgSetting, userId);
10119                return true;
10120            }
10121            if (sendRemoved) {
10122                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10123                        "hiding pkg");
10124                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10125                return true;
10126            }
10127        } finally {
10128            Binder.restoreCallingIdentity(callingId);
10129        }
10130        return false;
10131    }
10132
10133    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10134            int userId) {
10135        final PackageRemovedInfo info = new PackageRemovedInfo();
10136        info.removedPackage = packageName;
10137        info.removedUsers = new int[] {userId};
10138        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10139        info.sendBroadcast(false, false, false);
10140    }
10141
10142    /**
10143     * Returns true if application is not found or there was an error. Otherwise it returns
10144     * the hidden state of the package for the given user.
10145     */
10146    @Override
10147    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10148        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10149        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
10150                false, "getApplicationHidden for user " + userId);
10151        PackageSetting pkgSetting;
10152        long callingId = Binder.clearCallingIdentity();
10153        try {
10154            // writer
10155            synchronized (mPackages) {
10156                pkgSetting = mSettings.mPackages.get(packageName);
10157                if (pkgSetting == null) {
10158                    return true;
10159                }
10160                return pkgSetting.getHidden(userId);
10161            }
10162        } finally {
10163            Binder.restoreCallingIdentity(callingId);
10164        }
10165    }
10166
10167    /**
10168     * @hide
10169     */
10170    @Override
10171    public int installExistingPackageAsUser(String packageName, int userId) {
10172        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10173                null);
10174        PackageSetting pkgSetting;
10175        final int uid = Binder.getCallingUid();
10176        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
10177                + userId);
10178        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10179            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10180        }
10181
10182        long callingId = Binder.clearCallingIdentity();
10183        try {
10184            boolean sendAdded = false;
10185
10186            // writer
10187            synchronized (mPackages) {
10188                pkgSetting = mSettings.mPackages.get(packageName);
10189                if (pkgSetting == null) {
10190                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10191                }
10192                if (!pkgSetting.getInstalled(userId)) {
10193                    pkgSetting.setInstalled(true, userId);
10194                    pkgSetting.setHidden(false, userId);
10195                    mSettings.writePackageRestrictionsLPr(userId);
10196                    sendAdded = true;
10197                }
10198            }
10199
10200            if (sendAdded) {
10201                sendPackageAddedForUser(packageName, pkgSetting, userId);
10202            }
10203        } finally {
10204            Binder.restoreCallingIdentity(callingId);
10205        }
10206
10207        return PackageManager.INSTALL_SUCCEEDED;
10208    }
10209
10210    boolean isUserRestricted(int userId, String restrictionKey) {
10211        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10212        if (restrictions.getBoolean(restrictionKey, false)) {
10213            Log.w(TAG, "User is restricted: " + restrictionKey);
10214            return true;
10215        }
10216        return false;
10217    }
10218
10219    @Override
10220    public boolean setPackageSuspendedAsUser(String packageName, boolean suspended, int userId) {
10221        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10222        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, true,
10223                "setPackageSuspended for user " + userId);
10224
10225        long callingId = Binder.clearCallingIdentity();
10226        try {
10227            synchronized (mPackages) {
10228                final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10229                if (pkgSetting != null) {
10230                    if (pkgSetting.getSuspended(userId) != suspended) {
10231                        pkgSetting.setSuspended(suspended, userId);
10232                        mSettings.writePackageRestrictionsLPr(userId);
10233                    }
10234
10235                    // TODO:
10236                    // * broadcast a PACKAGE_(UN)SUSPENDED intent for launchers to pick up
10237                    // * remove app from recents (kill app it if it is running)
10238                    // * erase existing notifications for this app
10239                    return true;
10240                }
10241
10242                return false;
10243            }
10244        } finally {
10245            Binder.restoreCallingIdentity(callingId);
10246        }
10247    }
10248
10249    @Override
10250    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10251        mContext.enforceCallingOrSelfPermission(
10252                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10253                "Only package verification agents can verify applications");
10254
10255        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10256        final PackageVerificationResponse response = new PackageVerificationResponse(
10257                verificationCode, Binder.getCallingUid());
10258        msg.arg1 = id;
10259        msg.obj = response;
10260        mHandler.sendMessage(msg);
10261    }
10262
10263    @Override
10264    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10265            long millisecondsToDelay) {
10266        mContext.enforceCallingOrSelfPermission(
10267                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10268                "Only package verification agents can extend verification timeouts");
10269
10270        final PackageVerificationState state = mPendingVerification.get(id);
10271        final PackageVerificationResponse response = new PackageVerificationResponse(
10272                verificationCodeAtTimeout, Binder.getCallingUid());
10273
10274        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10275            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10276        }
10277        if (millisecondsToDelay < 0) {
10278            millisecondsToDelay = 0;
10279        }
10280        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10281                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10282            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10283        }
10284
10285        if ((state != null) && !state.timeoutExtended()) {
10286            state.extendTimeout();
10287
10288            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10289            msg.arg1 = id;
10290            msg.obj = response;
10291            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10292        }
10293    }
10294
10295    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10296            int verificationCode, UserHandle user) {
10297        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10298        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10299        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10300        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10301        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10302
10303        mContext.sendBroadcastAsUser(intent, user,
10304                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10305    }
10306
10307    private ComponentName matchComponentForVerifier(String packageName,
10308            List<ResolveInfo> receivers) {
10309        ActivityInfo targetReceiver = null;
10310
10311        final int NR = receivers.size();
10312        for (int i = 0; i < NR; i++) {
10313            final ResolveInfo info = receivers.get(i);
10314            if (info.activityInfo == null) {
10315                continue;
10316            }
10317
10318            if (packageName.equals(info.activityInfo.packageName)) {
10319                targetReceiver = info.activityInfo;
10320                break;
10321            }
10322        }
10323
10324        if (targetReceiver == null) {
10325            return null;
10326        }
10327
10328        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10329    }
10330
10331    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10332            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10333        if (pkgInfo.verifiers.length == 0) {
10334            return null;
10335        }
10336
10337        final int N = pkgInfo.verifiers.length;
10338        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10339        for (int i = 0; i < N; i++) {
10340            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10341
10342            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10343                    receivers);
10344            if (comp == null) {
10345                continue;
10346            }
10347
10348            final int verifierUid = getUidForVerifier(verifierInfo);
10349            if (verifierUid == -1) {
10350                continue;
10351            }
10352
10353            if (DEBUG_VERIFY) {
10354                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10355                        + " with the correct signature");
10356            }
10357            sufficientVerifiers.add(comp);
10358            verificationState.addSufficientVerifier(verifierUid);
10359        }
10360
10361        return sufficientVerifiers;
10362    }
10363
10364    private int getUidForVerifier(VerifierInfo verifierInfo) {
10365        synchronized (mPackages) {
10366            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
10367            if (pkg == null) {
10368                return -1;
10369            } else if (pkg.mSignatures.length != 1) {
10370                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10371                        + " has more than one signature; ignoring");
10372                return -1;
10373            }
10374
10375            /*
10376             * If the public key of the package's signature does not match
10377             * our expected public key, then this is a different package and
10378             * we should skip.
10379             */
10380
10381            final byte[] expectedPublicKey;
10382            try {
10383                final Signature verifierSig = pkg.mSignatures[0];
10384                final PublicKey publicKey = verifierSig.getPublicKey();
10385                expectedPublicKey = publicKey.getEncoded();
10386            } catch (CertificateException e) {
10387                return -1;
10388            }
10389
10390            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
10391
10392            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
10393                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
10394                        + " does not have the expected public key; ignoring");
10395                return -1;
10396            }
10397
10398            return pkg.applicationInfo.uid;
10399        }
10400    }
10401
10402    @Override
10403    public void finishPackageInstall(int token) {
10404        enforceSystemOrRoot("Only the system is allowed to finish installs");
10405
10406        if (DEBUG_INSTALL) {
10407            Slog.v(TAG, "BM finishing package install for " + token);
10408        }
10409        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10410
10411        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10412        mHandler.sendMessage(msg);
10413    }
10414
10415    /**
10416     * Get the verification agent timeout.
10417     *
10418     * @return verification timeout in milliseconds
10419     */
10420    private long getVerificationTimeout() {
10421        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
10422                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
10423                DEFAULT_VERIFICATION_TIMEOUT);
10424    }
10425
10426    /**
10427     * Get the default verification agent response code.
10428     *
10429     * @return default verification response code
10430     */
10431    private int getDefaultVerificationResponse() {
10432        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10433                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
10434                DEFAULT_VERIFICATION_RESPONSE);
10435    }
10436
10437    /**
10438     * Check whether or not package verification has been enabled.
10439     *
10440     * @return true if verification should be performed
10441     */
10442    private boolean isVerificationEnabled(int userId, int installFlags) {
10443        if (!DEFAULT_VERIFY_ENABLE) {
10444            return false;
10445        }
10446        // Ephemeral apps don't get the full verification treatment
10447        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10448            if (DEBUG_EPHEMERAL) {
10449                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
10450            }
10451            return false;
10452        }
10453
10454        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
10455
10456        // Check if installing from ADB
10457        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
10458            // Do not run verification in a test harness environment
10459            if (ActivityManager.isRunningInTestHarness()) {
10460                return false;
10461            }
10462            if (ensureVerifyAppsEnabled) {
10463                return true;
10464            }
10465            // Check if the developer does not want package verification for ADB installs
10466            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10467                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
10468                return false;
10469            }
10470        }
10471
10472        if (ensureVerifyAppsEnabled) {
10473            return true;
10474        }
10475
10476        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10477                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
10478    }
10479
10480    @Override
10481    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
10482            throws RemoteException {
10483        mContext.enforceCallingOrSelfPermission(
10484                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
10485                "Only intentfilter verification agents can verify applications");
10486
10487        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
10488        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
10489                Binder.getCallingUid(), verificationCode, failedDomains);
10490        msg.arg1 = id;
10491        msg.obj = response;
10492        mHandler.sendMessage(msg);
10493    }
10494
10495    @Override
10496    public int getIntentVerificationStatus(String packageName, int userId) {
10497        synchronized (mPackages) {
10498            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
10499        }
10500    }
10501
10502    @Override
10503    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
10504        mContext.enforceCallingOrSelfPermission(
10505                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10506
10507        boolean result = false;
10508        synchronized (mPackages) {
10509            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
10510        }
10511        if (result) {
10512            scheduleWritePackageRestrictionsLocked(userId);
10513        }
10514        return result;
10515    }
10516
10517    @Override
10518    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
10519        synchronized (mPackages) {
10520            return mSettings.getIntentFilterVerificationsLPr(packageName);
10521        }
10522    }
10523
10524    @Override
10525    public List<IntentFilter> getAllIntentFilters(String packageName) {
10526        if (TextUtils.isEmpty(packageName)) {
10527            return Collections.<IntentFilter>emptyList();
10528        }
10529        synchronized (mPackages) {
10530            PackageParser.Package pkg = mPackages.get(packageName);
10531            if (pkg == null || pkg.activities == null) {
10532                return Collections.<IntentFilter>emptyList();
10533            }
10534            final int count = pkg.activities.size();
10535            ArrayList<IntentFilter> result = new ArrayList<>();
10536            for (int n=0; n<count; n++) {
10537                PackageParser.Activity activity = pkg.activities.get(n);
10538                if (activity.intents != null && activity.intents.size() > 0) {
10539                    result.addAll(activity.intents);
10540                }
10541            }
10542            return result;
10543        }
10544    }
10545
10546    @Override
10547    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
10548        mContext.enforceCallingOrSelfPermission(
10549                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
10550
10551        synchronized (mPackages) {
10552            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
10553            if (packageName != null) {
10554                result |= updateIntentVerificationStatus(packageName,
10555                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
10556                        userId);
10557                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
10558                        packageName, userId);
10559            }
10560            return result;
10561        }
10562    }
10563
10564    @Override
10565    public String getDefaultBrowserPackageName(int userId) {
10566        synchronized (mPackages) {
10567            return mSettings.getDefaultBrowserPackageNameLPw(userId);
10568        }
10569    }
10570
10571    /**
10572     * Get the "allow unknown sources" setting.
10573     *
10574     * @return the current "allow unknown sources" setting
10575     */
10576    private int getUnknownSourcesSettings() {
10577        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
10578                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
10579                -1);
10580    }
10581
10582    @Override
10583    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
10584        final int uid = Binder.getCallingUid();
10585        // writer
10586        synchronized (mPackages) {
10587            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
10588            if (targetPackageSetting == null) {
10589                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
10590            }
10591
10592            PackageSetting installerPackageSetting;
10593            if (installerPackageName != null) {
10594                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
10595                if (installerPackageSetting == null) {
10596                    throw new IllegalArgumentException("Unknown installer package: "
10597                            + installerPackageName);
10598                }
10599            } else {
10600                installerPackageSetting = null;
10601            }
10602
10603            Signature[] callerSignature;
10604            Object obj = mSettings.getUserIdLPr(uid);
10605            if (obj != null) {
10606                if (obj instanceof SharedUserSetting) {
10607                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
10608                } else if (obj instanceof PackageSetting) {
10609                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
10610                } else {
10611                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
10612                }
10613            } else {
10614                throw new SecurityException("Unknown calling UID: " + uid);
10615            }
10616
10617            // Verify: can't set installerPackageName to a package that is
10618            // not signed with the same cert as the caller.
10619            if (installerPackageSetting != null) {
10620                if (compareSignatures(callerSignature,
10621                        installerPackageSetting.signatures.mSignatures)
10622                        != PackageManager.SIGNATURE_MATCH) {
10623                    throw new SecurityException(
10624                            "Caller does not have same cert as new installer package "
10625                            + installerPackageName);
10626                }
10627            }
10628
10629            // Verify: if target already has an installer package, it must
10630            // be signed with the same cert as the caller.
10631            if (targetPackageSetting.installerPackageName != null) {
10632                PackageSetting setting = mSettings.mPackages.get(
10633                        targetPackageSetting.installerPackageName);
10634                // If the currently set package isn't valid, then it's always
10635                // okay to change it.
10636                if (setting != null) {
10637                    if (compareSignatures(callerSignature,
10638                            setting.signatures.mSignatures)
10639                            != PackageManager.SIGNATURE_MATCH) {
10640                        throw new SecurityException(
10641                                "Caller does not have same cert as old installer package "
10642                                + targetPackageSetting.installerPackageName);
10643                    }
10644                }
10645            }
10646
10647            // Okay!
10648            targetPackageSetting.installerPackageName = installerPackageName;
10649            scheduleWriteSettingsLocked();
10650        }
10651    }
10652
10653    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
10654        // Queue up an async operation since the package installation may take a little while.
10655        mHandler.post(new Runnable() {
10656            public void run() {
10657                mHandler.removeCallbacks(this);
10658                 // Result object to be returned
10659                PackageInstalledInfo res = new PackageInstalledInfo();
10660                res.returnCode = currentStatus;
10661                res.uid = -1;
10662                res.pkg = null;
10663                res.removedInfo = new PackageRemovedInfo();
10664                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10665                    args.doPreInstall(res.returnCode);
10666                    synchronized (mInstallLock) {
10667                        installPackageTracedLI(args, res);
10668                    }
10669                    args.doPostInstall(res.returnCode, res.uid);
10670                }
10671
10672                // A restore should be performed at this point if (a) the install
10673                // succeeded, (b) the operation is not an update, and (c) the new
10674                // package has not opted out of backup participation.
10675                final boolean update = res.removedInfo.removedPackage != null;
10676                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
10677                boolean doRestore = !update
10678                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
10679
10680                // Set up the post-install work request bookkeeping.  This will be used
10681                // and cleaned up by the post-install event handling regardless of whether
10682                // there's a restore pass performed.  Token values are >= 1.
10683                int token;
10684                if (mNextInstallToken < 0) mNextInstallToken = 1;
10685                token = mNextInstallToken++;
10686
10687                PostInstallData data = new PostInstallData(args, res);
10688                mRunningInstalls.put(token, data);
10689                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
10690
10691                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
10692                    // Pass responsibility to the Backup Manager.  It will perform a
10693                    // restore if appropriate, then pass responsibility back to the
10694                    // Package Manager to run the post-install observer callbacks
10695                    // and broadcasts.
10696                    IBackupManager bm = IBackupManager.Stub.asInterface(
10697                            ServiceManager.getService(Context.BACKUP_SERVICE));
10698                    if (bm != null) {
10699                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
10700                                + " to BM for possible restore");
10701                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
10702                        try {
10703                            // TODO: http://b/22388012
10704                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
10705                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
10706                            } else {
10707                                doRestore = false;
10708                            }
10709                        } catch (RemoteException e) {
10710                            // can't happen; the backup manager is local
10711                        } catch (Exception e) {
10712                            Slog.e(TAG, "Exception trying to enqueue restore", e);
10713                            doRestore = false;
10714                        }
10715                    } else {
10716                        Slog.e(TAG, "Backup Manager not found!");
10717                        doRestore = false;
10718                    }
10719                }
10720
10721                if (!doRestore) {
10722                    // No restore possible, or the Backup Manager was mysteriously not
10723                    // available -- just fire the post-install work request directly.
10724                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
10725
10726                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
10727
10728                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
10729                    mHandler.sendMessage(msg);
10730                }
10731            }
10732        });
10733    }
10734
10735    private abstract class HandlerParams {
10736        private static final int MAX_RETRIES = 4;
10737
10738        /**
10739         * Number of times startCopy() has been attempted and had a non-fatal
10740         * error.
10741         */
10742        private int mRetries = 0;
10743
10744        /** User handle for the user requesting the information or installation. */
10745        private final UserHandle mUser;
10746        String traceMethod;
10747        int traceCookie;
10748
10749        HandlerParams(UserHandle user) {
10750            mUser = user;
10751        }
10752
10753        UserHandle getUser() {
10754            return mUser;
10755        }
10756
10757        HandlerParams setTraceMethod(String traceMethod) {
10758            this.traceMethod = traceMethod;
10759            return this;
10760        }
10761
10762        HandlerParams setTraceCookie(int traceCookie) {
10763            this.traceCookie = traceCookie;
10764            return this;
10765        }
10766
10767        final boolean startCopy() {
10768            boolean res;
10769            try {
10770                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
10771
10772                if (++mRetries > MAX_RETRIES) {
10773                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
10774                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
10775                    handleServiceError();
10776                    return false;
10777                } else {
10778                    handleStartCopy();
10779                    res = true;
10780                }
10781            } catch (RemoteException e) {
10782                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
10783                mHandler.sendEmptyMessage(MCS_RECONNECT);
10784                res = false;
10785            }
10786            handleReturnCode();
10787            return res;
10788        }
10789
10790        final void serviceError() {
10791            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
10792            handleServiceError();
10793            handleReturnCode();
10794        }
10795
10796        abstract void handleStartCopy() throws RemoteException;
10797        abstract void handleServiceError();
10798        abstract void handleReturnCode();
10799    }
10800
10801    class MeasureParams extends HandlerParams {
10802        private final PackageStats mStats;
10803        private boolean mSuccess;
10804
10805        private final IPackageStatsObserver mObserver;
10806
10807        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
10808            super(new UserHandle(stats.userHandle));
10809            mObserver = observer;
10810            mStats = stats;
10811        }
10812
10813        @Override
10814        public String toString() {
10815            return "MeasureParams{"
10816                + Integer.toHexString(System.identityHashCode(this))
10817                + " " + mStats.packageName + "}";
10818        }
10819
10820        @Override
10821        void handleStartCopy() throws RemoteException {
10822            synchronized (mInstallLock) {
10823                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
10824            }
10825
10826            if (mSuccess) {
10827                final boolean mounted;
10828                if (Environment.isExternalStorageEmulated()) {
10829                    mounted = true;
10830                } else {
10831                    final String status = Environment.getExternalStorageState();
10832                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
10833                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
10834                }
10835
10836                if (mounted) {
10837                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
10838
10839                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
10840                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
10841
10842                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
10843                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
10844
10845                    // Always subtract cache size, since it's a subdirectory
10846                    mStats.externalDataSize -= mStats.externalCacheSize;
10847
10848                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
10849                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
10850
10851                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
10852                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
10853                }
10854            }
10855        }
10856
10857        @Override
10858        void handleReturnCode() {
10859            if (mObserver != null) {
10860                try {
10861                    mObserver.onGetStatsCompleted(mStats, mSuccess);
10862                } catch (RemoteException e) {
10863                    Slog.i(TAG, "Observer no longer exists.");
10864                }
10865            }
10866        }
10867
10868        @Override
10869        void handleServiceError() {
10870            Slog.e(TAG, "Could not measure application " + mStats.packageName
10871                            + " external storage");
10872        }
10873    }
10874
10875    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
10876            throws RemoteException {
10877        long result = 0;
10878        for (File path : paths) {
10879            result += mcs.calculateDirectorySize(path.getAbsolutePath());
10880        }
10881        return result;
10882    }
10883
10884    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
10885        for (File path : paths) {
10886            try {
10887                mcs.clearDirectory(path.getAbsolutePath());
10888            } catch (RemoteException e) {
10889            }
10890        }
10891    }
10892
10893    static class OriginInfo {
10894        /**
10895         * Location where install is coming from, before it has been
10896         * copied/renamed into place. This could be a single monolithic APK
10897         * file, or a cluster directory. This location may be untrusted.
10898         */
10899        final File file;
10900        final String cid;
10901
10902        /**
10903         * Flag indicating that {@link #file} or {@link #cid} has already been
10904         * staged, meaning downstream users don't need to defensively copy the
10905         * contents.
10906         */
10907        final boolean staged;
10908
10909        /**
10910         * Flag indicating that {@link #file} or {@link #cid} is an already
10911         * installed app that is being moved.
10912         */
10913        final boolean existing;
10914
10915        final String resolvedPath;
10916        final File resolvedFile;
10917
10918        static OriginInfo fromNothing() {
10919            return new OriginInfo(null, null, false, false);
10920        }
10921
10922        static OriginInfo fromUntrustedFile(File file) {
10923            return new OriginInfo(file, null, false, false);
10924        }
10925
10926        static OriginInfo fromExistingFile(File file) {
10927            return new OriginInfo(file, null, false, true);
10928        }
10929
10930        static OriginInfo fromStagedFile(File file) {
10931            return new OriginInfo(file, null, true, false);
10932        }
10933
10934        static OriginInfo fromStagedContainer(String cid) {
10935            return new OriginInfo(null, cid, true, false);
10936        }
10937
10938        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
10939            this.file = file;
10940            this.cid = cid;
10941            this.staged = staged;
10942            this.existing = existing;
10943
10944            if (cid != null) {
10945                resolvedPath = PackageHelper.getSdDir(cid);
10946                resolvedFile = new File(resolvedPath);
10947            } else if (file != null) {
10948                resolvedPath = file.getAbsolutePath();
10949                resolvedFile = file;
10950            } else {
10951                resolvedPath = null;
10952                resolvedFile = null;
10953            }
10954        }
10955    }
10956
10957    static class MoveInfo {
10958        final int moveId;
10959        final String fromUuid;
10960        final String toUuid;
10961        final String packageName;
10962        final String dataAppName;
10963        final int appId;
10964        final String seinfo;
10965
10966        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
10967                String dataAppName, int appId, String seinfo) {
10968            this.moveId = moveId;
10969            this.fromUuid = fromUuid;
10970            this.toUuid = toUuid;
10971            this.packageName = packageName;
10972            this.dataAppName = dataAppName;
10973            this.appId = appId;
10974            this.seinfo = seinfo;
10975        }
10976    }
10977
10978    class InstallParams extends HandlerParams {
10979        final OriginInfo origin;
10980        final MoveInfo move;
10981        final IPackageInstallObserver2 observer;
10982        int installFlags;
10983        final String installerPackageName;
10984        final String volumeUuid;
10985        final VerificationParams verificationParams;
10986        private InstallArgs mArgs;
10987        private int mRet;
10988        final String packageAbiOverride;
10989        final String[] grantedRuntimePermissions;
10990
10991        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10992                int installFlags, String installerPackageName, String volumeUuid,
10993                VerificationParams verificationParams, UserHandle user, String packageAbiOverride,
10994                String[] grantedPermissions) {
10995            super(user);
10996            this.origin = origin;
10997            this.move = move;
10998            this.observer = observer;
10999            this.installFlags = installFlags;
11000            this.installerPackageName = installerPackageName;
11001            this.volumeUuid = volumeUuid;
11002            this.verificationParams = verificationParams;
11003            this.packageAbiOverride = packageAbiOverride;
11004            this.grantedRuntimePermissions = grantedPermissions;
11005        }
11006
11007        @Override
11008        public String toString() {
11009            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11010                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11011        }
11012
11013        private int installLocationPolicy(PackageInfoLite pkgLite) {
11014            String packageName = pkgLite.packageName;
11015            int installLocation = pkgLite.installLocation;
11016            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11017            // reader
11018            synchronized (mPackages) {
11019                PackageParser.Package pkg = mPackages.get(packageName);
11020                if (pkg != null) {
11021                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11022                        // Check for downgrading.
11023                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
11024                            try {
11025                                checkDowngrade(pkg, pkgLite);
11026                            } catch (PackageManagerException e) {
11027                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11028                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11029                            }
11030                        }
11031                        // Check for updated system application.
11032                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11033                            if (onSd) {
11034                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11035                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11036                            }
11037                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11038                        } else {
11039                            if (onSd) {
11040                                // Install flag overrides everything.
11041                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11042                            }
11043                            // If current upgrade specifies particular preference
11044                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11045                                // Application explicitly specified internal.
11046                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11047                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11048                                // App explictly prefers external. Let policy decide
11049                            } else {
11050                                // Prefer previous location
11051                                if (isExternal(pkg)) {
11052                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11053                                }
11054                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11055                            }
11056                        }
11057                    } else {
11058                        // Invalid install. Return error code
11059                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11060                    }
11061                }
11062            }
11063            // All the special cases have been taken care of.
11064            // Return result based on recommended install location.
11065            if (onSd) {
11066                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11067            }
11068            return pkgLite.recommendedInstallLocation;
11069        }
11070
11071        /*
11072         * Invoke remote method to get package information and install
11073         * location values. Override install location based on default
11074         * policy if needed and then create install arguments based
11075         * on the install location.
11076         */
11077        public void handleStartCopy() throws RemoteException {
11078            int ret = PackageManager.INSTALL_SUCCEEDED;
11079
11080            // If we're already staged, we've firmly committed to an install location
11081            if (origin.staged) {
11082                if (origin.file != null) {
11083                    installFlags |= PackageManager.INSTALL_INTERNAL;
11084                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11085                } else if (origin.cid != null) {
11086                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11087                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11088                } else {
11089                    throw new IllegalStateException("Invalid stage location");
11090                }
11091            }
11092
11093            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11094            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11095            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11096            PackageInfoLite pkgLite = null;
11097
11098            if (onInt && onSd) {
11099                // Check if both bits are set.
11100                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11101                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11102            } else if (onSd && ephemeral) {
11103                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11104                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11105            } else {
11106                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11107                        packageAbiOverride);
11108
11109                if (DEBUG_EPHEMERAL && ephemeral) {
11110                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11111                }
11112
11113                /*
11114                 * If we have too little free space, try to free cache
11115                 * before giving up.
11116                 */
11117                if (!origin.staged && pkgLite.recommendedInstallLocation
11118                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11119                    // TODO: focus freeing disk space on the target device
11120                    final StorageManager storage = StorageManager.from(mContext);
11121                    final long lowThreshold = storage.getStorageLowBytes(
11122                            Environment.getDataDirectory());
11123
11124                    final long sizeBytes = mContainerService.calculateInstalledSize(
11125                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11126
11127                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
11128                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11129                                installFlags, packageAbiOverride);
11130                    }
11131
11132                    /*
11133                     * The cache free must have deleted the file we
11134                     * downloaded to install.
11135                     *
11136                     * TODO: fix the "freeCache" call to not delete
11137                     *       the file we care about.
11138                     */
11139                    if (pkgLite.recommendedInstallLocation
11140                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11141                        pkgLite.recommendedInstallLocation
11142                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11143                    }
11144                }
11145            }
11146
11147            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11148                int loc = pkgLite.recommendedInstallLocation;
11149                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11150                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11151                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11152                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11153                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11154                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11155                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11156                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11157                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11158                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11159                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11160                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11161                } else {
11162                    // Override with defaults if needed.
11163                    loc = installLocationPolicy(pkgLite);
11164                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11165                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11166                    } else if (!onSd && !onInt) {
11167                        // Override install location with flags
11168                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11169                            // Set the flag to install on external media.
11170                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11171                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11172                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11173                            if (DEBUG_EPHEMERAL) {
11174                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11175                            }
11176                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11177                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11178                                    |PackageManager.INSTALL_INTERNAL);
11179                        } else {
11180                            // Make sure the flag for installing on external
11181                            // media is unset
11182                            installFlags |= PackageManager.INSTALL_INTERNAL;
11183                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11184                        }
11185                    }
11186                }
11187            }
11188
11189            final InstallArgs args = createInstallArgs(this);
11190            mArgs = args;
11191
11192            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11193                // TODO: http://b/22976637
11194                // Apps installed for "all" users use the device owner to verify the app
11195                UserHandle verifierUser = getUser();
11196                if (verifierUser == UserHandle.ALL) {
11197                    verifierUser = UserHandle.SYSTEM;
11198                }
11199
11200                /*
11201                 * Determine if we have any installed package verifiers. If we
11202                 * do, then we'll defer to them to verify the packages.
11203                 */
11204                final int requiredUid = mRequiredVerifierPackage == null ? -1
11205                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11206                                verifierUser.getIdentifier());
11207                if (!origin.existing && requiredUid != -1
11208                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11209                    final Intent verification = new Intent(
11210                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11211                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11212                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11213                            PACKAGE_MIME_TYPE);
11214                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11215
11216                    // Query all live verifiers based on current user state
11217                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
11218                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11219
11220                    if (DEBUG_VERIFY) {
11221                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11222                                + verification.toString() + " with " + pkgLite.verifiers.length
11223                                + " optional verifiers");
11224                    }
11225
11226                    final int verificationId = mPendingVerificationToken++;
11227
11228                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11229
11230                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11231                            installerPackageName);
11232
11233                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11234                            installFlags);
11235
11236                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11237                            pkgLite.packageName);
11238
11239                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11240                            pkgLite.versionCode);
11241
11242                    if (verificationParams != null) {
11243                        if (verificationParams.getVerificationURI() != null) {
11244                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
11245                                 verificationParams.getVerificationURI());
11246                        }
11247                        if (verificationParams.getOriginatingURI() != null) {
11248                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11249                                  verificationParams.getOriginatingURI());
11250                        }
11251                        if (verificationParams.getReferrer() != null) {
11252                            verification.putExtra(Intent.EXTRA_REFERRER,
11253                                  verificationParams.getReferrer());
11254                        }
11255                        if (verificationParams.getOriginatingUid() >= 0) {
11256                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11257                                  verificationParams.getOriginatingUid());
11258                        }
11259                        if (verificationParams.getInstallerUid() >= 0) {
11260                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11261                                  verificationParams.getInstallerUid());
11262                        }
11263                    }
11264
11265                    final PackageVerificationState verificationState = new PackageVerificationState(
11266                            requiredUid, args);
11267
11268                    mPendingVerification.append(verificationId, verificationState);
11269
11270                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11271                            receivers, verificationState);
11272
11273                    /*
11274                     * If any sufficient verifiers were listed in the package
11275                     * manifest, attempt to ask them.
11276                     */
11277                    if (sufficientVerifiers != null) {
11278                        final int N = sufficientVerifiers.size();
11279                        if (N == 0) {
11280                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11281                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11282                        } else {
11283                            for (int i = 0; i < N; i++) {
11284                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11285
11286                                final Intent sufficientIntent = new Intent(verification);
11287                                sufficientIntent.setComponent(verifierComponent);
11288                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11289                            }
11290                        }
11291                    }
11292
11293                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11294                            mRequiredVerifierPackage, receivers);
11295                    if (ret == PackageManager.INSTALL_SUCCEEDED
11296                            && mRequiredVerifierPackage != null) {
11297                        Trace.asyncTraceBegin(
11298                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11299                        /*
11300                         * Send the intent to the required verification agent,
11301                         * but only start the verification timeout after the
11302                         * target BroadcastReceivers have run.
11303                         */
11304                        verification.setComponent(requiredVerifierComponent);
11305                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11306                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11307                                new BroadcastReceiver() {
11308                                    @Override
11309                                    public void onReceive(Context context, Intent intent) {
11310                                        final Message msg = mHandler
11311                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11312                                        msg.arg1 = verificationId;
11313                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11314                                    }
11315                                }, null, 0, null, null);
11316
11317                        /*
11318                         * We don't want the copy to proceed until verification
11319                         * succeeds, so null out this field.
11320                         */
11321                        mArgs = null;
11322                    }
11323                } else {
11324                    /*
11325                     * No package verification is enabled, so immediately start
11326                     * the remote call to initiate copy using temporary file.
11327                     */
11328                    ret = args.copyApk(mContainerService, true);
11329                }
11330            }
11331
11332            mRet = ret;
11333        }
11334
11335        @Override
11336        void handleReturnCode() {
11337            // If mArgs is null, then MCS couldn't be reached. When it
11338            // reconnects, it will try again to install. At that point, this
11339            // will succeed.
11340            if (mArgs != null) {
11341                processPendingInstall(mArgs, mRet);
11342            }
11343        }
11344
11345        @Override
11346        void handleServiceError() {
11347            mArgs = createInstallArgs(this);
11348            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11349        }
11350
11351        public boolean isForwardLocked() {
11352            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11353        }
11354    }
11355
11356    /**
11357     * Used during creation of InstallArgs
11358     *
11359     * @param installFlags package installation flags
11360     * @return true if should be installed on external storage
11361     */
11362    private static boolean installOnExternalAsec(int installFlags) {
11363        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
11364            return false;
11365        }
11366        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
11367            return true;
11368        }
11369        return false;
11370    }
11371
11372    /**
11373     * Used during creation of InstallArgs
11374     *
11375     * @param installFlags package installation flags
11376     * @return true if should be installed as forward locked
11377     */
11378    private static boolean installForwardLocked(int installFlags) {
11379        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11380    }
11381
11382    private InstallArgs createInstallArgs(InstallParams params) {
11383        if (params.move != null) {
11384            return new MoveInstallArgs(params);
11385        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
11386            return new AsecInstallArgs(params);
11387        } else {
11388            return new FileInstallArgs(params);
11389        }
11390    }
11391
11392    /**
11393     * Create args that describe an existing installed package. Typically used
11394     * when cleaning up old installs, or used as a move source.
11395     */
11396    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
11397            String resourcePath, String[] instructionSets) {
11398        final boolean isInAsec;
11399        if (installOnExternalAsec(installFlags)) {
11400            /* Apps on SD card are always in ASEC containers. */
11401            isInAsec = true;
11402        } else if (installForwardLocked(installFlags)
11403                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
11404            /*
11405             * Forward-locked apps are only in ASEC containers if they're the
11406             * new style
11407             */
11408            isInAsec = true;
11409        } else {
11410            isInAsec = false;
11411        }
11412
11413        if (isInAsec) {
11414            return new AsecInstallArgs(codePath, instructionSets,
11415                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
11416        } else {
11417            return new FileInstallArgs(codePath, resourcePath, instructionSets);
11418        }
11419    }
11420
11421    static abstract class InstallArgs {
11422        /** @see InstallParams#origin */
11423        final OriginInfo origin;
11424        /** @see InstallParams#move */
11425        final MoveInfo move;
11426
11427        final IPackageInstallObserver2 observer;
11428        // Always refers to PackageManager flags only
11429        final int installFlags;
11430        final String installerPackageName;
11431        final String volumeUuid;
11432        final UserHandle user;
11433        final String abiOverride;
11434        final String[] installGrantPermissions;
11435        /** If non-null, drop an async trace when the install completes */
11436        final String traceMethod;
11437        final int traceCookie;
11438
11439        // The list of instruction sets supported by this app. This is currently
11440        // only used during the rmdex() phase to clean up resources. We can get rid of this
11441        // if we move dex files under the common app path.
11442        /* nullable */ String[] instructionSets;
11443
11444        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11445                int installFlags, String installerPackageName, String volumeUuid,
11446                UserHandle user, String[] instructionSets,
11447                String abiOverride, String[] installGrantPermissions,
11448                String traceMethod, int traceCookie) {
11449            this.origin = origin;
11450            this.move = move;
11451            this.installFlags = installFlags;
11452            this.observer = observer;
11453            this.installerPackageName = installerPackageName;
11454            this.volumeUuid = volumeUuid;
11455            this.user = user;
11456            this.instructionSets = instructionSets;
11457            this.abiOverride = abiOverride;
11458            this.installGrantPermissions = installGrantPermissions;
11459            this.traceMethod = traceMethod;
11460            this.traceCookie = traceCookie;
11461        }
11462
11463        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
11464        abstract int doPreInstall(int status);
11465
11466        /**
11467         * Rename package into final resting place. All paths on the given
11468         * scanned package should be updated to reflect the rename.
11469         */
11470        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
11471        abstract int doPostInstall(int status, int uid);
11472
11473        /** @see PackageSettingBase#codePathString */
11474        abstract String getCodePath();
11475        /** @see PackageSettingBase#resourcePathString */
11476        abstract String getResourcePath();
11477
11478        // Need installer lock especially for dex file removal.
11479        abstract void cleanUpResourcesLI();
11480        abstract boolean doPostDeleteLI(boolean delete);
11481
11482        /**
11483         * Called before the source arguments are copied. This is used mostly
11484         * for MoveParams when it needs to read the source file to put it in the
11485         * destination.
11486         */
11487        int doPreCopy() {
11488            return PackageManager.INSTALL_SUCCEEDED;
11489        }
11490
11491        /**
11492         * Called after the source arguments are copied. This is used mostly for
11493         * MoveParams when it needs to read the source file to put it in the
11494         * destination.
11495         *
11496         * @return
11497         */
11498        int doPostCopy(int uid) {
11499            return PackageManager.INSTALL_SUCCEEDED;
11500        }
11501
11502        protected boolean isFwdLocked() {
11503            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
11504        }
11505
11506        protected boolean isExternalAsec() {
11507            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11508        }
11509
11510        protected boolean isEphemeral() {
11511            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11512        }
11513
11514        UserHandle getUser() {
11515            return user;
11516        }
11517    }
11518
11519    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
11520        if (!allCodePaths.isEmpty()) {
11521            if (instructionSets == null) {
11522                throw new IllegalStateException("instructionSet == null");
11523            }
11524            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
11525            for (String codePath : allCodePaths) {
11526                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
11527                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
11528                    if (retCode < 0) {
11529                        Slog.w(TAG, "Couldn't remove dex file for package at location " + codePath
11530                                + ", retcode=" + retCode);
11531                        // we don't consider this to be a failure of the core package deletion
11532                    }
11533                }
11534            }
11535        }
11536    }
11537
11538    /**
11539     * Logic to handle installation of non-ASEC applications, including copying
11540     * and renaming logic.
11541     */
11542    class FileInstallArgs extends InstallArgs {
11543        private File codeFile;
11544        private File resourceFile;
11545
11546        // Example topology:
11547        // /data/app/com.example/base.apk
11548        // /data/app/com.example/split_foo.apk
11549        // /data/app/com.example/lib/arm/libfoo.so
11550        // /data/app/com.example/lib/arm64/libfoo.so
11551        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
11552
11553        /** New install */
11554        FileInstallArgs(InstallParams params) {
11555            super(params.origin, params.move, params.observer, params.installFlags,
11556                    params.installerPackageName, params.volumeUuid,
11557                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11558                    params.grantedRuntimePermissions,
11559                    params.traceMethod, params.traceCookie);
11560            if (isFwdLocked()) {
11561                throw new IllegalArgumentException("Forward locking only supported in ASEC");
11562            }
11563        }
11564
11565        /** Existing install */
11566        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
11567            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
11568                    null, null, null, 0);
11569            this.codeFile = (codePath != null) ? new File(codePath) : null;
11570            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
11571        }
11572
11573        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11574            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
11575            try {
11576                return doCopyApk(imcs, temp);
11577            } finally {
11578                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11579            }
11580        }
11581
11582        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11583            if (origin.staged) {
11584                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
11585                codeFile = origin.file;
11586                resourceFile = origin.file;
11587                return PackageManager.INSTALL_SUCCEEDED;
11588            }
11589
11590            try {
11591                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11592                final File tempDir =
11593                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
11594                codeFile = tempDir;
11595                resourceFile = tempDir;
11596            } catch (IOException e) {
11597                Slog.w(TAG, "Failed to create copy file: " + e);
11598                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11599            }
11600
11601            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
11602                @Override
11603                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
11604                    if (!FileUtils.isValidExtFilename(name)) {
11605                        throw new IllegalArgumentException("Invalid filename: " + name);
11606                    }
11607                    try {
11608                        final File file = new File(codeFile, name);
11609                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
11610                                O_RDWR | O_CREAT, 0644);
11611                        Os.chmod(file.getAbsolutePath(), 0644);
11612                        return new ParcelFileDescriptor(fd);
11613                    } catch (ErrnoException e) {
11614                        throw new RemoteException("Failed to open: " + e.getMessage());
11615                    }
11616                }
11617            };
11618
11619            int ret = PackageManager.INSTALL_SUCCEEDED;
11620            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
11621            if (ret != PackageManager.INSTALL_SUCCEEDED) {
11622                Slog.e(TAG, "Failed to copy package");
11623                return ret;
11624            }
11625
11626            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
11627            NativeLibraryHelper.Handle handle = null;
11628            try {
11629                handle = NativeLibraryHelper.Handle.create(codeFile);
11630                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
11631                        abiOverride);
11632            } catch (IOException e) {
11633                Slog.e(TAG, "Copying native libraries failed", e);
11634                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
11635            } finally {
11636                IoUtils.closeQuietly(handle);
11637            }
11638
11639            return ret;
11640        }
11641
11642        int doPreInstall(int status) {
11643            if (status != PackageManager.INSTALL_SUCCEEDED) {
11644                cleanUp();
11645            }
11646            return status;
11647        }
11648
11649        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11650            if (status != PackageManager.INSTALL_SUCCEEDED) {
11651                cleanUp();
11652                return false;
11653            }
11654
11655            final File targetDir = codeFile.getParentFile();
11656            final File beforeCodeFile = codeFile;
11657            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
11658
11659            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
11660            try {
11661                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
11662            } catch (ErrnoException e) {
11663                Slog.w(TAG, "Failed to rename", e);
11664                return false;
11665            }
11666
11667            if (!SELinux.restoreconRecursive(afterCodeFile)) {
11668                Slog.w(TAG, "Failed to restorecon");
11669                return false;
11670            }
11671
11672            // Reflect the rename internally
11673            codeFile = afterCodeFile;
11674            resourceFile = afterCodeFile;
11675
11676            // Reflect the rename in scanned details
11677            pkg.codePath = afterCodeFile.getAbsolutePath();
11678            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11679                    pkg.baseCodePath);
11680            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11681                    pkg.splitCodePaths);
11682
11683            // Reflect the rename in app info
11684            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11685            pkg.applicationInfo.setCodePath(pkg.codePath);
11686            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11687            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11688            pkg.applicationInfo.setResourcePath(pkg.codePath);
11689            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11690            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11691
11692            return true;
11693        }
11694
11695        int doPostInstall(int status, int uid) {
11696            if (status != PackageManager.INSTALL_SUCCEEDED) {
11697                cleanUp();
11698            }
11699            return status;
11700        }
11701
11702        @Override
11703        String getCodePath() {
11704            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
11705        }
11706
11707        @Override
11708        String getResourcePath() {
11709            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
11710        }
11711
11712        private boolean cleanUp() {
11713            if (codeFile == null || !codeFile.exists()) {
11714                return false;
11715            }
11716
11717            if (codeFile.isDirectory()) {
11718                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
11719            } else {
11720                codeFile.delete();
11721            }
11722
11723            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
11724                resourceFile.delete();
11725            }
11726
11727            return true;
11728        }
11729
11730        void cleanUpResourcesLI() {
11731            // Try enumerating all code paths before deleting
11732            List<String> allCodePaths = Collections.EMPTY_LIST;
11733            if (codeFile != null && codeFile.exists()) {
11734                try {
11735                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
11736                    allCodePaths = pkg.getAllCodePaths();
11737                } catch (PackageParserException e) {
11738                    // Ignored; we tried our best
11739                }
11740            }
11741
11742            cleanUp();
11743            removeDexFiles(allCodePaths, instructionSets);
11744        }
11745
11746        boolean doPostDeleteLI(boolean delete) {
11747            // XXX err, shouldn't we respect the delete flag?
11748            cleanUpResourcesLI();
11749            return true;
11750        }
11751    }
11752
11753    private boolean isAsecExternal(String cid) {
11754        final String asecPath = PackageHelper.getSdFilesystem(cid);
11755        return !asecPath.startsWith(mAsecInternalPath);
11756    }
11757
11758    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
11759            PackageManagerException {
11760        if (copyRet < 0) {
11761            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
11762                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
11763                throw new PackageManagerException(copyRet, message);
11764            }
11765        }
11766    }
11767
11768    /**
11769     * Extract the MountService "container ID" from the full code path of an
11770     * .apk.
11771     */
11772    static String cidFromCodePath(String fullCodePath) {
11773        int eidx = fullCodePath.lastIndexOf("/");
11774        String subStr1 = fullCodePath.substring(0, eidx);
11775        int sidx = subStr1.lastIndexOf("/");
11776        return subStr1.substring(sidx+1, eidx);
11777    }
11778
11779    /**
11780     * Logic to handle installation of ASEC applications, including copying and
11781     * renaming logic.
11782     */
11783    class AsecInstallArgs extends InstallArgs {
11784        static final String RES_FILE_NAME = "pkg.apk";
11785        static final String PUBLIC_RES_FILE_NAME = "res.zip";
11786
11787        String cid;
11788        String packagePath;
11789        String resourcePath;
11790
11791        /** New install */
11792        AsecInstallArgs(InstallParams params) {
11793            super(params.origin, params.move, params.observer, params.installFlags,
11794                    params.installerPackageName, params.volumeUuid,
11795                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
11796                    params.grantedRuntimePermissions,
11797                    params.traceMethod, params.traceCookie);
11798        }
11799
11800        /** Existing install */
11801        AsecInstallArgs(String fullCodePath, String[] instructionSets,
11802                        boolean isExternal, boolean isForwardLocked) {
11803            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
11804                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11805                    instructionSets, null, null, null, 0);
11806            // Hackily pretend we're still looking at a full code path
11807            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
11808                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
11809            }
11810
11811            // Extract cid from fullCodePath
11812            int eidx = fullCodePath.lastIndexOf("/");
11813            String subStr1 = fullCodePath.substring(0, eidx);
11814            int sidx = subStr1.lastIndexOf("/");
11815            cid = subStr1.substring(sidx+1, eidx);
11816            setMountPath(subStr1);
11817        }
11818
11819        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
11820            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
11821                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
11822                    instructionSets, null, null, null, 0);
11823            this.cid = cid;
11824            setMountPath(PackageHelper.getSdDir(cid));
11825        }
11826
11827        void createCopyFile() {
11828            cid = mInstallerService.allocateExternalStageCidLegacy();
11829        }
11830
11831        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
11832            if (origin.staged && origin.cid != null) {
11833                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
11834                cid = origin.cid;
11835                setMountPath(PackageHelper.getSdDir(cid));
11836                return PackageManager.INSTALL_SUCCEEDED;
11837            }
11838
11839            if (temp) {
11840                createCopyFile();
11841            } else {
11842                /*
11843                 * Pre-emptively destroy the container since it's destroyed if
11844                 * copying fails due to it existing anyway.
11845                 */
11846                PackageHelper.destroySdDir(cid);
11847            }
11848
11849            final String newMountPath = imcs.copyPackageToContainer(
11850                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
11851                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
11852
11853            if (newMountPath != null) {
11854                setMountPath(newMountPath);
11855                return PackageManager.INSTALL_SUCCEEDED;
11856            } else {
11857                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11858            }
11859        }
11860
11861        @Override
11862        String getCodePath() {
11863            return packagePath;
11864        }
11865
11866        @Override
11867        String getResourcePath() {
11868            return resourcePath;
11869        }
11870
11871        int doPreInstall(int status) {
11872            if (status != PackageManager.INSTALL_SUCCEEDED) {
11873                // Destroy container
11874                PackageHelper.destroySdDir(cid);
11875            } else {
11876                boolean mounted = PackageHelper.isContainerMounted(cid);
11877                if (!mounted) {
11878                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
11879                            Process.SYSTEM_UID);
11880                    if (newMountPath != null) {
11881                        setMountPath(newMountPath);
11882                    } else {
11883                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11884                    }
11885                }
11886            }
11887            return status;
11888        }
11889
11890        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
11891            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
11892            String newMountPath = null;
11893            if (PackageHelper.isContainerMounted(cid)) {
11894                // Unmount the container
11895                if (!PackageHelper.unMountSdDir(cid)) {
11896                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
11897                    return false;
11898                }
11899            }
11900            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11901                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
11902                        " which might be stale. Will try to clean up.");
11903                // Clean up the stale container and proceed to recreate.
11904                if (!PackageHelper.destroySdDir(newCacheId)) {
11905                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
11906                    return false;
11907                }
11908                // Successfully cleaned up stale container. Try to rename again.
11909                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
11910                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
11911                            + " inspite of cleaning it up.");
11912                    return false;
11913                }
11914            }
11915            if (!PackageHelper.isContainerMounted(newCacheId)) {
11916                Slog.w(TAG, "Mounting container " + newCacheId);
11917                newMountPath = PackageHelper.mountSdDir(newCacheId,
11918                        getEncryptKey(), Process.SYSTEM_UID);
11919            } else {
11920                newMountPath = PackageHelper.getSdDir(newCacheId);
11921            }
11922            if (newMountPath == null) {
11923                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
11924                return false;
11925            }
11926            Log.i(TAG, "Succesfully renamed " + cid +
11927                    " to " + newCacheId +
11928                    " at new path: " + newMountPath);
11929            cid = newCacheId;
11930
11931            final File beforeCodeFile = new File(packagePath);
11932            setMountPath(newMountPath);
11933            final File afterCodeFile = new File(packagePath);
11934
11935            // Reflect the rename in scanned details
11936            pkg.codePath = afterCodeFile.getAbsolutePath();
11937            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11938                    pkg.baseCodePath);
11939            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
11940                    pkg.splitCodePaths);
11941
11942            // Reflect the rename in app info
11943            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
11944            pkg.applicationInfo.setCodePath(pkg.codePath);
11945            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
11946            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
11947            pkg.applicationInfo.setResourcePath(pkg.codePath);
11948            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
11949            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
11950
11951            return true;
11952        }
11953
11954        private void setMountPath(String mountPath) {
11955            final File mountFile = new File(mountPath);
11956
11957            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
11958            if (monolithicFile.exists()) {
11959                packagePath = monolithicFile.getAbsolutePath();
11960                if (isFwdLocked()) {
11961                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
11962                } else {
11963                    resourcePath = packagePath;
11964                }
11965            } else {
11966                packagePath = mountFile.getAbsolutePath();
11967                resourcePath = packagePath;
11968            }
11969        }
11970
11971        int doPostInstall(int status, int uid) {
11972            if (status != PackageManager.INSTALL_SUCCEEDED) {
11973                cleanUp();
11974            } else {
11975                final int groupOwner;
11976                final String protectedFile;
11977                if (isFwdLocked()) {
11978                    groupOwner = UserHandle.getSharedAppGid(uid);
11979                    protectedFile = RES_FILE_NAME;
11980                } else {
11981                    groupOwner = -1;
11982                    protectedFile = null;
11983                }
11984
11985                if (uid < Process.FIRST_APPLICATION_UID
11986                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
11987                    Slog.e(TAG, "Failed to finalize " + cid);
11988                    PackageHelper.destroySdDir(cid);
11989                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
11990                }
11991
11992                boolean mounted = PackageHelper.isContainerMounted(cid);
11993                if (!mounted) {
11994                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
11995                }
11996            }
11997            return status;
11998        }
11999
12000        private void cleanUp() {
12001            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12002
12003            // Destroy secure container
12004            PackageHelper.destroySdDir(cid);
12005        }
12006
12007        private List<String> getAllCodePaths() {
12008            final File codeFile = new File(getCodePath());
12009            if (codeFile != null && codeFile.exists()) {
12010                try {
12011                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12012                    return pkg.getAllCodePaths();
12013                } catch (PackageParserException e) {
12014                    // Ignored; we tried our best
12015                }
12016            }
12017            return Collections.EMPTY_LIST;
12018        }
12019
12020        void cleanUpResourcesLI() {
12021            // Enumerate all code paths before deleting
12022            cleanUpResourcesLI(getAllCodePaths());
12023        }
12024
12025        private void cleanUpResourcesLI(List<String> allCodePaths) {
12026            cleanUp();
12027            removeDexFiles(allCodePaths, instructionSets);
12028        }
12029
12030        String getPackageName() {
12031            return getAsecPackageName(cid);
12032        }
12033
12034        boolean doPostDeleteLI(boolean delete) {
12035            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12036            final List<String> allCodePaths = getAllCodePaths();
12037            boolean mounted = PackageHelper.isContainerMounted(cid);
12038            if (mounted) {
12039                // Unmount first
12040                if (PackageHelper.unMountSdDir(cid)) {
12041                    mounted = false;
12042                }
12043            }
12044            if (!mounted && delete) {
12045                cleanUpResourcesLI(allCodePaths);
12046            }
12047            return !mounted;
12048        }
12049
12050        @Override
12051        int doPreCopy() {
12052            if (isFwdLocked()) {
12053                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12054                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12055                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12056                }
12057            }
12058
12059            return PackageManager.INSTALL_SUCCEEDED;
12060        }
12061
12062        @Override
12063        int doPostCopy(int uid) {
12064            if (isFwdLocked()) {
12065                if (uid < Process.FIRST_APPLICATION_UID
12066                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12067                                RES_FILE_NAME)) {
12068                    Slog.e(TAG, "Failed to finalize " + cid);
12069                    PackageHelper.destroySdDir(cid);
12070                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12071                }
12072            }
12073
12074            return PackageManager.INSTALL_SUCCEEDED;
12075        }
12076    }
12077
12078    /**
12079     * Logic to handle movement of existing installed applications.
12080     */
12081    class MoveInstallArgs extends InstallArgs {
12082        private File codeFile;
12083        private File resourceFile;
12084
12085        /** New install */
12086        MoveInstallArgs(InstallParams params) {
12087            super(params.origin, params.move, params.observer, params.installFlags,
12088                    params.installerPackageName, params.volumeUuid,
12089                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12090                    params.grantedRuntimePermissions,
12091                    params.traceMethod, params.traceCookie);
12092        }
12093
12094        int copyApk(IMediaContainerService imcs, boolean temp) {
12095            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12096                    + move.fromUuid + " to " + move.toUuid);
12097            synchronized (mInstaller) {
12098                if (mInstaller.copyCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12099                        move.dataAppName, move.appId, move.seinfo) != 0) {
12100                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12101                }
12102            }
12103
12104            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12105            resourceFile = codeFile;
12106            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12107
12108            return PackageManager.INSTALL_SUCCEEDED;
12109        }
12110
12111        int doPreInstall(int status) {
12112            if (status != PackageManager.INSTALL_SUCCEEDED) {
12113                cleanUp(move.toUuid);
12114            }
12115            return status;
12116        }
12117
12118        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12119            if (status != PackageManager.INSTALL_SUCCEEDED) {
12120                cleanUp(move.toUuid);
12121                return false;
12122            }
12123
12124            // Reflect the move in app info
12125            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
12126            pkg.applicationInfo.setCodePath(pkg.codePath);
12127            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
12128            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
12129            pkg.applicationInfo.setResourcePath(pkg.codePath);
12130            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
12131            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
12132
12133            return true;
12134        }
12135
12136        int doPostInstall(int status, int uid) {
12137            if (status == PackageManager.INSTALL_SUCCEEDED) {
12138                cleanUp(move.fromUuid);
12139            } else {
12140                cleanUp(move.toUuid);
12141            }
12142            return status;
12143        }
12144
12145        @Override
12146        String getCodePath() {
12147            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12148        }
12149
12150        @Override
12151        String getResourcePath() {
12152            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12153        }
12154
12155        private boolean cleanUp(String volumeUuid) {
12156            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12157                    move.dataAppName);
12158            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12159            synchronized (mInstallLock) {
12160                // Clean up both app data and code
12161                removeDataDirsLI(volumeUuid, move.packageName);
12162                if (codeFile.isDirectory()) {
12163                    mInstaller.rmPackageDir(codeFile.getAbsolutePath());
12164                } else {
12165                    codeFile.delete();
12166                }
12167            }
12168            return true;
12169        }
12170
12171        void cleanUpResourcesLI() {
12172            throw new UnsupportedOperationException();
12173        }
12174
12175        boolean doPostDeleteLI(boolean delete) {
12176            throw new UnsupportedOperationException();
12177        }
12178    }
12179
12180    static String getAsecPackageName(String packageCid) {
12181        int idx = packageCid.lastIndexOf("-");
12182        if (idx == -1) {
12183            return packageCid;
12184        }
12185        return packageCid.substring(0, idx);
12186    }
12187
12188    // Utility method used to create code paths based on package name and available index.
12189    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12190        String idxStr = "";
12191        int idx = 1;
12192        // Fall back to default value of idx=1 if prefix is not
12193        // part of oldCodePath
12194        if (oldCodePath != null) {
12195            String subStr = oldCodePath;
12196            // Drop the suffix right away
12197            if (suffix != null && subStr.endsWith(suffix)) {
12198                subStr = subStr.substring(0, subStr.length() - suffix.length());
12199            }
12200            // If oldCodePath already contains prefix find out the
12201            // ending index to either increment or decrement.
12202            int sidx = subStr.lastIndexOf(prefix);
12203            if (sidx != -1) {
12204                subStr = subStr.substring(sidx + prefix.length());
12205                if (subStr != null) {
12206                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12207                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12208                    }
12209                    try {
12210                        idx = Integer.parseInt(subStr);
12211                        if (idx <= 1) {
12212                            idx++;
12213                        } else {
12214                            idx--;
12215                        }
12216                    } catch(NumberFormatException e) {
12217                    }
12218                }
12219            }
12220        }
12221        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12222        return prefix + idxStr;
12223    }
12224
12225    private File getNextCodePath(File targetDir, String packageName) {
12226        int suffix = 1;
12227        File result;
12228        do {
12229            result = new File(targetDir, packageName + "-" + suffix);
12230            suffix++;
12231        } while (result.exists());
12232        return result;
12233    }
12234
12235    // Utility method that returns the relative package path with respect
12236    // to the installation directory. Like say for /data/data/com.test-1.apk
12237    // string com.test-1 is returned.
12238    static String deriveCodePathName(String codePath) {
12239        if (codePath == null) {
12240            return null;
12241        }
12242        final File codeFile = new File(codePath);
12243        final String name = codeFile.getName();
12244        if (codeFile.isDirectory()) {
12245            return name;
12246        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12247            final int lastDot = name.lastIndexOf('.');
12248            return name.substring(0, lastDot);
12249        } else {
12250            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12251            return null;
12252        }
12253    }
12254
12255    static class PackageInstalledInfo {
12256        String name;
12257        int uid;
12258        // The set of users that originally had this package installed.
12259        int[] origUsers;
12260        // The set of users that now have this package installed.
12261        int[] newUsers;
12262        PackageParser.Package pkg;
12263        int returnCode;
12264        String returnMsg;
12265        PackageRemovedInfo removedInfo;
12266
12267        public void setError(int code, String msg) {
12268            returnCode = code;
12269            returnMsg = msg;
12270            Slog.w(TAG, msg);
12271        }
12272
12273        public void setError(String msg, PackageParserException e) {
12274            returnCode = e.error;
12275            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12276            Slog.w(TAG, msg, e);
12277        }
12278
12279        public void setError(String msg, PackageManagerException e) {
12280            returnCode = e.error;
12281            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
12282            Slog.w(TAG, msg, e);
12283        }
12284
12285        // In some error cases we want to convey more info back to the observer
12286        String origPackage;
12287        String origPermission;
12288    }
12289
12290    /*
12291     * Install a non-existing package.
12292     */
12293    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12294            UserHandle user, String installerPackageName, String volumeUuid,
12295            PackageInstalledInfo res) {
12296        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12297
12298        // Remember this for later, in case we need to rollback this install
12299        String pkgName = pkg.packageName;
12300
12301        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12302        // TODO: b/23350563
12303        final boolean dataDirExists = Environment
12304                .getDataUserPackageDirectory(volumeUuid, UserHandle.USER_SYSTEM, pkgName).exists();
12305
12306        synchronized(mPackages) {
12307            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
12308                // A package with the same name is already installed, though
12309                // it has been renamed to an older name.  The package we
12310                // are trying to install should be installed as an update to
12311                // the existing one, but that has not been requested, so bail.
12312                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12313                        + " without first uninstalling package running as "
12314                        + mSettings.mRenamedPackages.get(pkgName));
12315                return;
12316            }
12317            if (mPackages.containsKey(pkgName)) {
12318                // Don't allow installation over an existing package with the same name.
12319                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
12320                        + " without first uninstalling.");
12321                return;
12322            }
12323        }
12324
12325        try {
12326            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
12327                    System.currentTimeMillis(), user);
12328
12329            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
12330            // delete the partially installed application. the data directory will have to be
12331            // restored if it was already existing
12332            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12333                // remove package from internal structures.  Note that we want deletePackageX to
12334                // delete the package data and cache directories that it created in
12335                // scanPackageLocked, unless those directories existed before we even tried to
12336                // install.
12337                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
12338                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
12339                                res.removedInfo, true);
12340            }
12341
12342        } catch (PackageManagerException e) {
12343            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12344        }
12345
12346        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12347    }
12348
12349    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
12350        // Can't rotate keys during boot or if sharedUser.
12351        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
12352                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
12353            return false;
12354        }
12355        // app is using upgradeKeySets; make sure all are valid
12356        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12357        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
12358        for (int i = 0; i < upgradeKeySets.length; i++) {
12359            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
12360                Slog.wtf(TAG, "Package "
12361                         + (oldPs.name != null ? oldPs.name : "<null>")
12362                         + " contains upgrade-key-set reference to unknown key-set: "
12363                         + upgradeKeySets[i]
12364                         + " reverting to signatures check.");
12365                return false;
12366            }
12367        }
12368        return true;
12369    }
12370
12371    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
12372        // Upgrade keysets are being used.  Determine if new package has a superset of the
12373        // required keys.
12374        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
12375        KeySetManagerService ksms = mSettings.mKeySetManagerService;
12376        for (int i = 0; i < upgradeKeySets.length; i++) {
12377            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
12378            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
12379                return true;
12380            }
12381        }
12382        return false;
12383    }
12384
12385    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12386            UserHandle user, String installerPackageName, String volumeUuid,
12387            PackageInstalledInfo res) {
12388        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
12389
12390        final PackageParser.Package oldPackage;
12391        final String pkgName = pkg.packageName;
12392        final int[] allUsers;
12393        final boolean[] perUserInstalled;
12394
12395        // First find the old package info and check signatures
12396        synchronized(mPackages) {
12397            oldPackage = mPackages.get(pkgName);
12398            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
12399            if (isEphemeral && !oldIsEphemeral) {
12400                // can't downgrade from full to ephemeral
12401                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
12402                res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12403                return;
12404            }
12405            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
12406            final PackageSetting ps = mSettings.mPackages.get(pkgName);
12407            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12408                if(!checkUpgradeKeySetLP(ps, pkg)) {
12409                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12410                            "New package not signed by keys specified by upgrade-keysets: "
12411                            + pkgName);
12412                    return;
12413                }
12414            } else {
12415                // default to original signature matching
12416                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
12417                    != PackageManager.SIGNATURE_MATCH) {
12418                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
12419                            "New package has a different signature: " + pkgName);
12420                    return;
12421                }
12422            }
12423
12424            // In case of rollback, remember per-user/profile install state
12425            allUsers = sUserManager.getUserIds();
12426            perUserInstalled = new boolean[allUsers.length];
12427            for (int i = 0; i < allUsers.length; i++) {
12428                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
12429            }
12430        }
12431
12432        boolean sysPkg = (isSystemApp(oldPackage));
12433        if (sysPkg) {
12434            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12435                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12436        } else {
12437            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
12438                    user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
12439        }
12440    }
12441
12442    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
12443            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12444            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12445            String volumeUuid, PackageInstalledInfo res) {
12446        String pkgName = deletedPackage.packageName;
12447        boolean deletedPkg = true;
12448        boolean updatedSettings = false;
12449
12450        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
12451                + deletedPackage);
12452        long origUpdateTime;
12453        if (pkg.mExtras != null) {
12454            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
12455        } else {
12456            origUpdateTime = 0;
12457        }
12458
12459        // First delete the existing package while retaining the data directory
12460        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
12461                res.removedInfo, true)) {
12462            // If the existing package wasn't successfully deleted
12463            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
12464            deletedPkg = false;
12465        } else {
12466            // Successfully deleted the old package; proceed with replace.
12467
12468            // If deleted package lived in a container, give users a chance to
12469            // relinquish resources before killing.
12470            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
12471                if (DEBUG_INSTALL) {
12472                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
12473                }
12474                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
12475                final ArrayList<String> pkgList = new ArrayList<String>(1);
12476                pkgList.add(deletedPackage.applicationInfo.packageName);
12477                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
12478            }
12479
12480            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
12481            try {
12482                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
12483                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
12484                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12485                        perUserInstalled, res, user);
12486                updatedSettings = true;
12487            } catch (PackageManagerException e) {
12488                res.setError("Package couldn't be installed in " + pkg.codePath, e);
12489            }
12490        }
12491
12492        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12493            // remove package from internal structures.  Note that we want deletePackageX to
12494            // delete the package data and cache directories that it created in
12495            // scanPackageLocked, unless those directories existed before we even tried to
12496            // install.
12497            if(updatedSettings) {
12498                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
12499                deletePackageLI(
12500                        pkgName, null, true, allUsers, perUserInstalled,
12501                        PackageManager.DELETE_KEEP_DATA,
12502                                res.removedInfo, true);
12503            }
12504            // Since we failed to install the new package we need to restore the old
12505            // package that we deleted.
12506            if (deletedPkg) {
12507                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
12508                File restoreFile = new File(deletedPackage.codePath);
12509                // Parse old package
12510                boolean oldExternal = isExternal(deletedPackage);
12511                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
12512                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
12513                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
12514                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
12515                try {
12516                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
12517                            null);
12518                } catch (PackageManagerException e) {
12519                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
12520                            + e.getMessage());
12521                    return;
12522                }
12523                // Restore of old package succeeded. Update permissions.
12524                // writer
12525                synchronized (mPackages) {
12526                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
12527                            UPDATE_PERMISSIONS_ALL);
12528                    // can downgrade to reader
12529                    mSettings.writeLPr();
12530                }
12531                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
12532            }
12533        }
12534    }
12535
12536    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
12537            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
12538            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
12539            String volumeUuid, PackageInstalledInfo res) {
12540        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
12541                + ", old=" + deletedPackage);
12542        boolean disabledSystem = false;
12543        boolean updatedSettings = false;
12544        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
12545        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
12546                != 0) {
12547            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12548        }
12549        String packageName = deletedPackage.packageName;
12550        if (packageName == null) {
12551            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12552                    "Attempt to delete null packageName.");
12553            return;
12554        }
12555        PackageParser.Package oldPkg;
12556        PackageSetting oldPkgSetting;
12557        // reader
12558        synchronized (mPackages) {
12559            oldPkg = mPackages.get(packageName);
12560            oldPkgSetting = mSettings.mPackages.get(packageName);
12561            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
12562                    (oldPkgSetting == null)) {
12563                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
12564                        "Couldn't find package " + packageName + " information");
12565                return;
12566            }
12567        }
12568
12569        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
12570
12571        res.removedInfo.uid = oldPkg.applicationInfo.uid;
12572        res.removedInfo.removedPackage = packageName;
12573        // Remove existing system package
12574        removePackageLI(oldPkgSetting, true);
12575        // writer
12576        synchronized (mPackages) {
12577            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
12578            if (!disabledSystem && deletedPackage != null) {
12579                // We didn't need to disable the .apk as a current system package,
12580                // which means we are replacing another update that is already
12581                // installed.  We need to make sure to delete the older one's .apk.
12582                res.removedInfo.args = createInstallArgsForExisting(0,
12583                        deletedPackage.applicationInfo.getCodePath(),
12584                        deletedPackage.applicationInfo.getResourcePath(),
12585                        getAppDexInstructionSets(deletedPackage.applicationInfo));
12586            } else {
12587                res.removedInfo.args = null;
12588            }
12589        }
12590
12591        // Successfully disabled the old package. Now proceed with re-installation
12592        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
12593
12594        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12595        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
12596
12597        PackageParser.Package newPackage = null;
12598        try {
12599            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
12600            if (newPackage.mExtras != null) {
12601                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
12602                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
12603                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
12604
12605                // is the update attempting to change shared user? that isn't going to work...
12606                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
12607                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
12608                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
12609                            + " to " + newPkgSetting.sharedUser);
12610                    updatedSettings = true;
12611                }
12612            }
12613
12614            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
12615                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
12616                        perUserInstalled, res, user);
12617                updatedSettings = true;
12618            }
12619
12620        } catch (PackageManagerException e) {
12621            res.setError("Package couldn't be installed in " + pkg.codePath, e);
12622        }
12623
12624        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
12625            // Re installation failed. Restore old information
12626            // Remove new pkg information
12627            if (newPackage != null) {
12628                removeInstalledPackageLI(newPackage, true);
12629            }
12630            // Add back the old system package
12631            try {
12632                scanPackageTracedLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
12633            } catch (PackageManagerException e) {
12634                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
12635            }
12636            // Restore the old system information in Settings
12637            synchronized (mPackages) {
12638                if (disabledSystem) {
12639                    mSettings.enableSystemPackageLPw(packageName);
12640                }
12641                if (updatedSettings) {
12642                    mSettings.setInstallerPackageName(packageName,
12643                            oldPkgSetting.installerPackageName);
12644                }
12645                mSettings.writeLPr();
12646            }
12647        }
12648    }
12649
12650    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
12651        // Collect all used permissions in the UID
12652        ArraySet<String> usedPermissions = new ArraySet<>();
12653        final int packageCount = su.packages.size();
12654        for (int i = 0; i < packageCount; i++) {
12655            PackageSetting ps = su.packages.valueAt(i);
12656            if (ps.pkg == null) {
12657                continue;
12658            }
12659            final int requestedPermCount = ps.pkg.requestedPermissions.size();
12660            for (int j = 0; j < requestedPermCount; j++) {
12661                String permission = ps.pkg.requestedPermissions.get(j);
12662                BasePermission bp = mSettings.mPermissions.get(permission);
12663                if (bp != null) {
12664                    usedPermissions.add(permission);
12665                }
12666            }
12667        }
12668
12669        PermissionsState permissionsState = su.getPermissionsState();
12670        // Prune install permissions
12671        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
12672        final int installPermCount = installPermStates.size();
12673        for (int i = installPermCount - 1; i >= 0;  i--) {
12674            PermissionState permissionState = installPermStates.get(i);
12675            if (!usedPermissions.contains(permissionState.getName())) {
12676                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12677                if (bp != null) {
12678                    permissionsState.revokeInstallPermission(bp);
12679                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12680                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12681                }
12682            }
12683        }
12684
12685        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
12686
12687        // Prune runtime permissions
12688        for (int userId : allUserIds) {
12689            List<PermissionState> runtimePermStates = permissionsState
12690                    .getRuntimePermissionStates(userId);
12691            final int runtimePermCount = runtimePermStates.size();
12692            for (int i = runtimePermCount - 1; i >= 0; i--) {
12693                PermissionState permissionState = runtimePermStates.get(i);
12694                if (!usedPermissions.contains(permissionState.getName())) {
12695                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
12696                    if (bp != null) {
12697                        permissionsState.revokeRuntimePermission(bp, userId);
12698                        permissionsState.updatePermissionFlags(bp, userId,
12699                                PackageManager.MASK_PERMISSION_FLAGS, 0);
12700                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
12701                                runtimePermissionChangedUserIds, userId);
12702                    }
12703                }
12704            }
12705        }
12706
12707        return runtimePermissionChangedUserIds;
12708    }
12709
12710    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
12711            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
12712            UserHandle user) {
12713        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12714
12715        String pkgName = newPackage.packageName;
12716        synchronized (mPackages) {
12717            //write settings. the installStatus will be incomplete at this stage.
12718            //note that the new package setting would have already been
12719            //added to mPackages. It hasn't been persisted yet.
12720            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
12721            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12722            mSettings.writeLPr();
12723            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12724        }
12725
12726        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
12727        synchronized (mPackages) {
12728            updatePermissionsLPw(newPackage.packageName, newPackage,
12729                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
12730                            ? UPDATE_PERMISSIONS_ALL : 0));
12731            // For system-bundled packages, we assume that installing an upgraded version
12732            // of the package implies that the user actually wants to run that new code,
12733            // so we enable the package.
12734            PackageSetting ps = mSettings.mPackages.get(pkgName);
12735            if (ps != null) {
12736                if (isSystemApp(newPackage)) {
12737                    // NB: implicit assumption that system package upgrades apply to all users
12738                    if (DEBUG_INSTALL) {
12739                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
12740                    }
12741                    if (res.origUsers != null) {
12742                        for (int userHandle : res.origUsers) {
12743                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
12744                                    userHandle, installerPackageName);
12745                        }
12746                    }
12747                    // Also convey the prior install/uninstall state
12748                    if (allUsers != null && perUserInstalled != null) {
12749                        for (int i = 0; i < allUsers.length; i++) {
12750                            if (DEBUG_INSTALL) {
12751                                Slog.d(TAG, "    user " + allUsers[i]
12752                                        + " => " + perUserInstalled[i]);
12753                            }
12754                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
12755                        }
12756                        // these install state changes will be persisted in the
12757                        // upcoming call to mSettings.writeLPr().
12758                    }
12759                }
12760                // It's implied that when a user requests installation, they want the app to be
12761                // installed and enabled.
12762                int userId = user.getIdentifier();
12763                if (userId != UserHandle.USER_ALL) {
12764                    ps.setInstalled(true, userId);
12765                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
12766                }
12767            }
12768            res.name = pkgName;
12769            res.uid = newPackage.applicationInfo.uid;
12770            res.pkg = newPackage;
12771            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
12772            mSettings.setInstallerPackageName(pkgName, installerPackageName);
12773            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12774            //to update install status
12775            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
12776            mSettings.writeLPr();
12777            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12778        }
12779
12780        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12781    }
12782
12783    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
12784        try {
12785            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
12786            installPackageLI(args, res);
12787        } finally {
12788            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12789        }
12790    }
12791
12792    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
12793        final int installFlags = args.installFlags;
12794        final String installerPackageName = args.installerPackageName;
12795        final String volumeUuid = args.volumeUuid;
12796        final File tmpPackageFile = new File(args.getCodePath());
12797        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
12798        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
12799                || (args.volumeUuid != null));
12800        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
12801        boolean replace = false;
12802        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
12803        if (args.move != null) {
12804            // moving a complete application; perfom an initial scan on the new install location
12805            scanFlags |= SCAN_INITIAL;
12806        }
12807        // Result object to be returned
12808        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
12809
12810        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
12811
12812        // Sanity check
12813        if (ephemeral && (forwardLocked || onExternal)) {
12814            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
12815                    + " external=" + onExternal);
12816            res.returnCode = PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
12817            return;
12818        }
12819
12820        // Retrieve PackageSettings and parse package
12821        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
12822                | PackageParser.PARSE_ENFORCE_CODE
12823                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
12824                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
12825                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
12826        PackageParser pp = new PackageParser();
12827        pp.setSeparateProcesses(mSeparateProcesses);
12828        pp.setDisplayMetrics(mMetrics);
12829
12830        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
12831        final PackageParser.Package pkg;
12832        try {
12833            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
12834        } catch (PackageParserException e) {
12835            res.setError("Failed parse during installPackageLI", e);
12836            return;
12837        } finally {
12838            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12839        }
12840
12841        // Mark that we have an install time CPU ABI override.
12842        pkg.cpuAbiOverride = args.abiOverride;
12843
12844        String pkgName = res.name = pkg.packageName;
12845        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
12846            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
12847                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
12848                return;
12849            }
12850        }
12851
12852        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
12853        try {
12854            pp.collectCertificates(pkg, parseFlags);
12855        } catch (PackageParserException e) {
12856            res.setError("Failed collect during installPackageLI", e);
12857            return;
12858        } finally {
12859            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12860        }
12861
12862        // Get rid of all references to package scan path via parser.
12863        pp = null;
12864        String oldCodePath = null;
12865        boolean systemApp = false;
12866        synchronized (mPackages) {
12867            // Check if installing already existing package
12868            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12869                String oldName = mSettings.mRenamedPackages.get(pkgName);
12870                if (pkg.mOriginalPackages != null
12871                        && pkg.mOriginalPackages.contains(oldName)
12872                        && mPackages.containsKey(oldName)) {
12873                    // This package is derived from an original package,
12874                    // and this device has been updating from that original
12875                    // name.  We must continue using the original name, so
12876                    // rename the new package here.
12877                    pkg.setPackageName(oldName);
12878                    pkgName = pkg.packageName;
12879                    replace = true;
12880                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
12881                            + oldName + " pkgName=" + pkgName);
12882                } else if (mPackages.containsKey(pkgName)) {
12883                    // This package, under its official name, already exists
12884                    // on the device; we should replace it.
12885                    replace = true;
12886                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
12887                }
12888
12889                // Prevent apps opting out from runtime permissions
12890                if (replace) {
12891                    PackageParser.Package oldPackage = mPackages.get(pkgName);
12892                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
12893                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
12894                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
12895                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
12896                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
12897                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
12898                                        + " doesn't support runtime permissions but the old"
12899                                        + " target SDK " + oldTargetSdk + " does.");
12900                        return;
12901                    }
12902                }
12903            }
12904
12905            PackageSetting ps = mSettings.mPackages.get(pkgName);
12906            if (ps != null) {
12907                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
12908
12909                // Quick sanity check that we're signed correctly if updating;
12910                // we'll check this again later when scanning, but we want to
12911                // bail early here before tripping over redefined permissions.
12912                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
12913                    if (!checkUpgradeKeySetLP(ps, pkg)) {
12914                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
12915                                + pkg.packageName + " upgrade keys do not match the "
12916                                + "previously installed version");
12917                        return;
12918                    }
12919                } else {
12920                    try {
12921                        verifySignaturesLP(ps, pkg);
12922                    } catch (PackageManagerException e) {
12923                        res.setError(e.error, e.getMessage());
12924                        return;
12925                    }
12926                }
12927
12928                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
12929                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
12930                    systemApp = (ps.pkg.applicationInfo.flags &
12931                            ApplicationInfo.FLAG_SYSTEM) != 0;
12932                }
12933                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
12934            }
12935
12936            // Check whether the newly-scanned package wants to define an already-defined perm
12937            int N = pkg.permissions.size();
12938            for (int i = N-1; i >= 0; i--) {
12939                PackageParser.Permission perm = pkg.permissions.get(i);
12940                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
12941                if (bp != null) {
12942                    // If the defining package is signed with our cert, it's okay.  This
12943                    // also includes the "updating the same package" case, of course.
12944                    // "updating same package" could also involve key-rotation.
12945                    final boolean sigsOk;
12946                    if (bp.sourcePackage.equals(pkg.packageName)
12947                            && (bp.packageSetting instanceof PackageSetting)
12948                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
12949                                    scanFlags))) {
12950                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
12951                    } else {
12952                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
12953                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
12954                    }
12955                    if (!sigsOk) {
12956                        // If the owning package is the system itself, we log but allow
12957                        // install to proceed; we fail the install on all other permission
12958                        // redefinitions.
12959                        if (!bp.sourcePackage.equals("android")) {
12960                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
12961                                    + pkg.packageName + " attempting to redeclare permission "
12962                                    + perm.info.name + " already owned by " + bp.sourcePackage);
12963                            res.origPermission = perm.info.name;
12964                            res.origPackage = bp.sourcePackage;
12965                            return;
12966                        } else {
12967                            Slog.w(TAG, "Package " + pkg.packageName
12968                                    + " attempting to redeclare system permission "
12969                                    + perm.info.name + "; ignoring new declaration");
12970                            pkg.permissions.remove(i);
12971                        }
12972                    }
12973                }
12974            }
12975
12976        }
12977
12978        if (systemApp) {
12979            if (onExternal) {
12980                // Abort update; system app can't be replaced with app on sdcard
12981                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
12982                        "Cannot install updates to system apps on sdcard");
12983                return;
12984            } else if (ephemeral) {
12985                // Abort update; system app can't be replaced with an ephemeral app
12986                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
12987                        "Cannot update a system app with an ephemeral app");
12988                return;
12989            }
12990        }
12991
12992        if (args.move != null) {
12993            // We did an in-place move, so dex is ready to roll
12994            scanFlags |= SCAN_NO_DEX;
12995            scanFlags |= SCAN_MOVE;
12996
12997            synchronized (mPackages) {
12998                final PackageSetting ps = mSettings.mPackages.get(pkgName);
12999                if (ps == null) {
13000                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13001                            "Missing settings for moved package " + pkgName);
13002                }
13003
13004                // We moved the entire application as-is, so bring over the
13005                // previously derived ABI information.
13006                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13007                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13008            }
13009
13010        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13011            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13012            scanFlags |= SCAN_NO_DEX;
13013
13014            try {
13015                derivePackageAbi(pkg, new File(pkg.codePath), args.abiOverride,
13016                        true /* extract libs */);
13017            } catch (PackageManagerException pme) {
13018                Slog.e(TAG, "Error deriving application ABI", pme);
13019                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13020                return;
13021            }
13022        }
13023
13024        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13025            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13026            return;
13027        }
13028
13029        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13030
13031        if (replace) {
13032            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13033                    installerPackageName, volumeUuid, res);
13034        } else {
13035            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13036                    args.user, installerPackageName, volumeUuid, res);
13037        }
13038        synchronized (mPackages) {
13039            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13040            if (ps != null) {
13041                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13042            }
13043        }
13044    }
13045
13046    private void startIntentFilterVerifications(int userId, boolean replacing,
13047            PackageParser.Package pkg) {
13048        if (mIntentFilterVerifierComponent == null) {
13049            Slog.w(TAG, "No IntentFilter verification will not be done as "
13050                    + "there is no IntentFilterVerifier available!");
13051            return;
13052        }
13053
13054        final int verifierUid = getPackageUid(
13055                mIntentFilterVerifierComponent.getPackageName(),
13056                MATCH_DEBUG_TRIAGED_MISSING,
13057                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
13058
13059        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
13060        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
13061        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
13062        mHandler.sendMessage(msg);
13063    }
13064
13065    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
13066            PackageParser.Package pkg) {
13067        int size = pkg.activities.size();
13068        if (size == 0) {
13069            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13070                    "No activity, so no need to verify any IntentFilter!");
13071            return;
13072        }
13073
13074        final boolean hasDomainURLs = hasDomainURLs(pkg);
13075        if (!hasDomainURLs) {
13076            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13077                    "No domain URLs, so no need to verify any IntentFilter!");
13078            return;
13079        }
13080
13081        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
13082                + " if any IntentFilter from the " + size
13083                + " Activities needs verification ...");
13084
13085        int count = 0;
13086        final String packageName = pkg.packageName;
13087
13088        synchronized (mPackages) {
13089            // If this is a new install and we see that we've already run verification for this
13090            // package, we have nothing to do: it means the state was restored from backup.
13091            if (!replacing) {
13092                IntentFilterVerificationInfo ivi =
13093                        mSettings.getIntentFilterVerificationLPr(packageName);
13094                if (ivi != null) {
13095                    if (DEBUG_DOMAIN_VERIFICATION) {
13096                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
13097                                + ivi.getStatusString());
13098                    }
13099                    return;
13100                }
13101            }
13102
13103            // If any filters need to be verified, then all need to be.
13104            boolean needToVerify = false;
13105            for (PackageParser.Activity a : pkg.activities) {
13106                for (ActivityIntentInfo filter : a.intents) {
13107                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
13108                        if (DEBUG_DOMAIN_VERIFICATION) {
13109                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
13110                        }
13111                        needToVerify = true;
13112                        break;
13113                    }
13114                }
13115            }
13116
13117            if (needToVerify) {
13118                final int verificationId = mIntentFilterVerificationToken++;
13119                for (PackageParser.Activity a : pkg.activities) {
13120                    for (ActivityIntentInfo filter : a.intents) {
13121                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
13122                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
13123                                    "Verification needed for IntentFilter:" + filter.toString());
13124                            mIntentFilterVerifier.addOneIntentFilterVerification(
13125                                    verifierUid, userId, verificationId, filter, packageName);
13126                            count++;
13127                        }
13128                    }
13129                }
13130            }
13131        }
13132
13133        if (count > 0) {
13134            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
13135                    + " IntentFilter verification" + (count > 1 ? "s" : "")
13136                    +  " for userId:" + userId);
13137            mIntentFilterVerifier.startVerifications(userId);
13138        } else {
13139            if (DEBUG_DOMAIN_VERIFICATION) {
13140                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
13141            }
13142        }
13143    }
13144
13145    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
13146        final ComponentName cn  = filter.activity.getComponentName();
13147        final String packageName = cn.getPackageName();
13148
13149        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
13150                packageName);
13151        if (ivi == null) {
13152            return true;
13153        }
13154        int status = ivi.getStatus();
13155        switch (status) {
13156            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
13157            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
13158                return true;
13159
13160            default:
13161                // Nothing to do
13162                return false;
13163        }
13164    }
13165
13166    private static boolean isMultiArch(ApplicationInfo info) {
13167        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
13168    }
13169
13170    private static boolean isExternal(PackageParser.Package pkg) {
13171        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13172    }
13173
13174    private static boolean isExternal(PackageSetting ps) {
13175        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
13176    }
13177
13178    private static boolean isEphemeral(PackageParser.Package pkg) {
13179        return pkg.applicationInfo.isEphemeralApp();
13180    }
13181
13182    private static boolean isEphemeral(PackageSetting ps) {
13183        return ps.pkg != null && isEphemeral(ps.pkg);
13184    }
13185
13186    private static boolean isSystemApp(PackageParser.Package pkg) {
13187        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
13188    }
13189
13190    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
13191        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
13192    }
13193
13194    private static boolean hasDomainURLs(PackageParser.Package pkg) {
13195        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
13196    }
13197
13198    private static boolean isSystemApp(PackageSetting ps) {
13199        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
13200    }
13201
13202    private static boolean isUpdatedSystemApp(PackageSetting ps) {
13203        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
13204    }
13205
13206    private int packageFlagsToInstallFlags(PackageSetting ps) {
13207        int installFlags = 0;
13208        if (isEphemeral(ps)) {
13209            installFlags |= PackageManager.INSTALL_EPHEMERAL;
13210        }
13211        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
13212            // This existing package was an external ASEC install when we have
13213            // the external flag without a UUID
13214            installFlags |= PackageManager.INSTALL_EXTERNAL;
13215        }
13216        if (ps.isForwardLocked()) {
13217            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13218        }
13219        return installFlags;
13220    }
13221
13222    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
13223        if (isExternal(pkg)) {
13224            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13225                return StorageManager.UUID_PRIMARY_PHYSICAL;
13226            } else {
13227                return pkg.volumeUuid;
13228            }
13229        } else {
13230            return StorageManager.UUID_PRIVATE_INTERNAL;
13231        }
13232    }
13233
13234    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
13235        if (isExternal(pkg)) {
13236            if (TextUtils.isEmpty(pkg.volumeUuid)) {
13237                return mSettings.getExternalVersion();
13238            } else {
13239                return mSettings.findOrCreateVersion(pkg.volumeUuid);
13240            }
13241        } else {
13242            return mSettings.getInternalVersion();
13243        }
13244    }
13245
13246    private void deleteTempPackageFiles() {
13247        final FilenameFilter filter = new FilenameFilter() {
13248            public boolean accept(File dir, String name) {
13249                return name.startsWith("vmdl") && name.endsWith(".tmp");
13250            }
13251        };
13252        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
13253            file.delete();
13254        }
13255    }
13256
13257    @Override
13258    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
13259            int flags) {
13260        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
13261                flags);
13262    }
13263
13264    @Override
13265    public void deletePackage(final String packageName,
13266            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
13267        mContext.enforceCallingOrSelfPermission(
13268                android.Manifest.permission.DELETE_PACKAGES, null);
13269        Preconditions.checkNotNull(packageName);
13270        Preconditions.checkNotNull(observer);
13271        final int uid = Binder.getCallingUid();
13272        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
13273        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
13274        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
13275            mContext.enforceCallingOrSelfPermission(
13276                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
13277                    "deletePackage for user " + userId);
13278        }
13279
13280        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
13281            try {
13282                observer.onPackageDeleted(packageName,
13283                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
13284            } catch (RemoteException re) {
13285            }
13286            return;
13287        }
13288
13289        for (int currentUserId : users) {
13290            if (getBlockUninstallForUser(packageName, currentUserId)) {
13291                try {
13292                    observer.onPackageDeleted(packageName,
13293                            PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
13294                } catch (RemoteException re) {
13295                }
13296                return;
13297            }
13298        }
13299
13300        if (DEBUG_REMOVE) {
13301            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
13302        }
13303        // Queue up an async operation since the package deletion may take a little while.
13304        mHandler.post(new Runnable() {
13305            public void run() {
13306                mHandler.removeCallbacks(this);
13307                final int returnCode = deletePackageX(packageName, userId, flags);
13308                try {
13309                    observer.onPackageDeleted(packageName, returnCode, null);
13310                } catch (RemoteException e) {
13311                    Log.i(TAG, "Observer no longer exists.");
13312                } //end catch
13313            } //end run
13314        });
13315    }
13316
13317    private boolean isPackageDeviceAdmin(String packageName, int userId) {
13318        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13319                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13320        try {
13321            if (dpm != null) {
13322                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
13323                        /* callingUserOnly =*/ false);
13324                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
13325                        : deviceOwnerComponentName.getPackageName();
13326                // Does the package contains the device owner?
13327                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
13328                // this check is probably not needed, since DO should be registered as a device
13329                // admin on some user too. (Original bug for this: b/17657954)
13330                if (packageName.equals(deviceOwnerPackageName)) {
13331                    return true;
13332                }
13333                // Does it contain a device admin for any user?
13334                int[] users;
13335                if (userId == UserHandle.USER_ALL) {
13336                    users = sUserManager.getUserIds();
13337                } else {
13338                    users = new int[]{userId};
13339                }
13340                for (int i = 0; i < users.length; ++i) {
13341                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
13342                        return true;
13343                    }
13344                }
13345            }
13346        } catch (RemoteException e) {
13347        }
13348        return false;
13349    }
13350
13351    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
13352        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
13353    }
13354
13355    /**
13356     *  This method is an internal method that could be get invoked either
13357     *  to delete an installed package or to clean up a failed installation.
13358     *  After deleting an installed package, a broadcast is sent to notify any
13359     *  listeners that the package has been installed. For cleaning up a failed
13360     *  installation, the broadcast is not necessary since the package's
13361     *  installation wouldn't have sent the initial broadcast either
13362     *  The key steps in deleting a package are
13363     *  deleting the package information in internal structures like mPackages,
13364     *  deleting the packages base directories through installd
13365     *  updating mSettings to reflect current status
13366     *  persisting settings for later use
13367     *  sending a broadcast if necessary
13368     */
13369    private int deletePackageX(String packageName, int userId, int flags) {
13370        final PackageRemovedInfo info = new PackageRemovedInfo();
13371        final boolean res;
13372
13373        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
13374                ? UserHandle.ALL : new UserHandle(userId);
13375
13376        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
13377            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
13378            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
13379        }
13380
13381        boolean removedForAllUsers = false;
13382        boolean systemUpdate = false;
13383
13384        PackageParser.Package uninstalledPkg;
13385
13386        // for the uninstall-updates case and restricted profiles, remember the per-
13387        // userhandle installed state
13388        int[] allUsers;
13389        boolean[] perUserInstalled;
13390        synchronized (mPackages) {
13391            uninstalledPkg = mPackages.get(packageName);
13392            PackageSetting ps = mSettings.mPackages.get(packageName);
13393            allUsers = sUserManager.getUserIds();
13394            perUserInstalled = new boolean[allUsers.length];
13395            for (int i = 0; i < allUsers.length; i++) {
13396                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
13397            }
13398        }
13399
13400        synchronized (mInstallLock) {
13401            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
13402            res = deletePackageLI(packageName, removeForUser,
13403                    true, allUsers, perUserInstalled,
13404                    flags | REMOVE_CHATTY, info, true);
13405            systemUpdate = info.isRemovedPackageSystemUpdate;
13406            synchronized (mPackages) {
13407                if (res) {
13408                    if (!systemUpdate && mPackages.get(packageName) == null) {
13409                        removedForAllUsers = true;
13410                    }
13411                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPkg);
13412                }
13413            }
13414            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
13415                    + " removedForAllUsers=" + removedForAllUsers);
13416        }
13417
13418        if (res) {
13419            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
13420
13421            // If the removed package was a system update, the old system package
13422            // was re-enabled; we need to broadcast this information
13423            if (systemUpdate) {
13424                Bundle extras = new Bundle(1);
13425                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
13426                        ? info.removedAppId : info.uid);
13427                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13428
13429                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
13430                        extras, 0, null, null, null);
13431                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
13432                        extras, 0, null, null, null);
13433                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
13434                        null, 0, packageName, null, null);
13435            }
13436        }
13437        // Force a gc here.
13438        Runtime.getRuntime().gc();
13439        // Delete the resources here after sending the broadcast to let
13440        // other processes clean up before deleting resources.
13441        if (info.args != null) {
13442            synchronized (mInstallLock) {
13443                info.args.doPostDeleteLI(true);
13444            }
13445        }
13446
13447        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
13448    }
13449
13450    class PackageRemovedInfo {
13451        String removedPackage;
13452        int uid = -1;
13453        int removedAppId = -1;
13454        int[] removedUsers = null;
13455        boolean isRemovedPackageSystemUpdate = false;
13456        // Clean up resources deleted packages.
13457        InstallArgs args = null;
13458
13459        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
13460            Bundle extras = new Bundle(1);
13461            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
13462            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
13463            if (replacing) {
13464                extras.putBoolean(Intent.EXTRA_REPLACING, true);
13465            }
13466            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
13467            if (removedPackage != null) {
13468                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
13469                        extras, 0, null, null, removedUsers);
13470                if (fullRemove && !replacing) {
13471                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
13472                            extras, 0, null, null, removedUsers);
13473                }
13474            }
13475            if (removedAppId >= 0) {
13476                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
13477                        removedUsers);
13478            }
13479        }
13480    }
13481
13482    /*
13483     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
13484     * flag is not set, the data directory is removed as well.
13485     * make sure this flag is set for partially installed apps. If not its meaningless to
13486     * delete a partially installed application.
13487     */
13488    private void removePackageDataLI(PackageSetting ps,
13489            int[] allUserHandles, boolean[] perUserInstalled,
13490            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
13491        String packageName = ps.name;
13492        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
13493        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
13494        // Retrieve object to delete permissions for shared user later on
13495        final PackageSetting deletedPs;
13496        // reader
13497        synchronized (mPackages) {
13498            deletedPs = mSettings.mPackages.get(packageName);
13499            if (outInfo != null) {
13500                outInfo.removedPackage = packageName;
13501                outInfo.removedUsers = deletedPs != null
13502                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
13503                        : null;
13504            }
13505        }
13506        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13507            removeDataDirsLI(ps.volumeUuid, packageName);
13508            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
13509        }
13510        // writer
13511        synchronized (mPackages) {
13512            if (deletedPs != null) {
13513                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
13514                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
13515                    clearDefaultBrowserIfNeeded(packageName);
13516                    if (outInfo != null) {
13517                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
13518                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
13519                    }
13520                    updatePermissionsLPw(deletedPs.name, null, 0);
13521                    if (deletedPs.sharedUser != null) {
13522                        // Remove permissions associated with package. Since runtime
13523                        // permissions are per user we have to kill the removed package
13524                        // or packages running under the shared user of the removed
13525                        // package if revoking the permissions requested only by the removed
13526                        // package is successful and this causes a change in gids.
13527                        for (int userId : UserManagerService.getInstance().getUserIds()) {
13528                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
13529                                    userId);
13530                            if (userIdToKill == UserHandle.USER_ALL
13531                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
13532                                // If gids changed for this user, kill all affected packages.
13533                                mHandler.post(new Runnable() {
13534                                    @Override
13535                                    public void run() {
13536                                        // This has to happen with no lock held.
13537                                        killApplication(deletedPs.name, deletedPs.appId,
13538                                                KILL_APP_REASON_GIDS_CHANGED);
13539                                    }
13540                                });
13541                                break;
13542                            }
13543                        }
13544                    }
13545                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
13546                }
13547                // make sure to preserve per-user disabled state if this removal was just
13548                // a downgrade of a system app to the factory package
13549                if (allUserHandles != null && perUserInstalled != null) {
13550                    if (DEBUG_REMOVE) {
13551                        Slog.d(TAG, "Propagating install state across downgrade");
13552                    }
13553                    for (int i = 0; i < allUserHandles.length; i++) {
13554                        if (DEBUG_REMOVE) {
13555                            Slog.d(TAG, "    user " + allUserHandles[i]
13556                                    + " => " + perUserInstalled[i]);
13557                        }
13558                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13559                    }
13560                }
13561            }
13562            // can downgrade to reader
13563            if (writeSettings) {
13564                // Save settings now
13565                mSettings.writeLPr();
13566            }
13567        }
13568        if (outInfo != null) {
13569            // A user ID was deleted here. Go through all users and remove it
13570            // from KeyStore.
13571            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
13572        }
13573    }
13574
13575    static boolean locationIsPrivileged(File path) {
13576        try {
13577            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
13578                    .getCanonicalPath();
13579            return path.getCanonicalPath().startsWith(privilegedAppDir);
13580        } catch (IOException e) {
13581            Slog.e(TAG, "Unable to access code path " + path);
13582        }
13583        return false;
13584    }
13585
13586    /*
13587     * Tries to delete system package.
13588     */
13589    private boolean deleteSystemPackageLI(PackageSetting newPs,
13590            int[] allUserHandles, boolean[] perUserInstalled,
13591            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
13592        final boolean applyUserRestrictions
13593                = (allUserHandles != null) && (perUserInstalled != null);
13594        PackageSetting disabledPs = null;
13595        // Confirm if the system package has been updated
13596        // An updated system app can be deleted. This will also have to restore
13597        // the system pkg from system partition
13598        // reader
13599        synchronized (mPackages) {
13600            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
13601        }
13602        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
13603                + " disabledPs=" + disabledPs);
13604        if (disabledPs == null) {
13605            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
13606            return false;
13607        } else if (DEBUG_REMOVE) {
13608            Slog.d(TAG, "Deleting system pkg from data partition");
13609        }
13610        if (DEBUG_REMOVE) {
13611            if (applyUserRestrictions) {
13612                Slog.d(TAG, "Remembering install states:");
13613                for (int i = 0; i < allUserHandles.length; i++) {
13614                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
13615                }
13616            }
13617        }
13618        // Delete the updated package
13619        outInfo.isRemovedPackageSystemUpdate = true;
13620        if (disabledPs.versionCode < newPs.versionCode) {
13621            // Delete data for downgrades
13622            flags &= ~PackageManager.DELETE_KEEP_DATA;
13623        } else {
13624            // Preserve data by setting flag
13625            flags |= PackageManager.DELETE_KEEP_DATA;
13626        }
13627        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
13628                allUserHandles, perUserInstalled, outInfo, writeSettings);
13629        if (!ret) {
13630            return false;
13631        }
13632        // writer
13633        synchronized (mPackages) {
13634            // Reinstate the old system package
13635            mSettings.enableSystemPackageLPw(newPs.name);
13636            // Remove any native libraries from the upgraded package.
13637            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
13638        }
13639        // Install the system package
13640        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
13641        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
13642        if (locationIsPrivileged(disabledPs.codePath)) {
13643            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13644        }
13645
13646        final PackageParser.Package newPkg;
13647        try {
13648            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
13649        } catch (PackageManagerException e) {
13650            Slog.w(TAG, "Failed to restore system package " + newPs.name + ": " + e.getMessage());
13651            return false;
13652        }
13653
13654        // writer
13655        synchronized (mPackages) {
13656            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
13657
13658            // Propagate the permissions state as we do not want to drop on the floor
13659            // runtime permissions. The update permissions method below will take
13660            // care of removing obsolete permissions and grant install permissions.
13661            ps.getPermissionsState().copyFrom(newPs.getPermissionsState());
13662            updatePermissionsLPw(newPkg.packageName, newPkg,
13663                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
13664
13665            if (applyUserRestrictions) {
13666                if (DEBUG_REMOVE) {
13667                    Slog.d(TAG, "Propagating install state across reinstall");
13668                }
13669                for (int i = 0; i < allUserHandles.length; i++) {
13670                    if (DEBUG_REMOVE) {
13671                        Slog.d(TAG, "    user " + allUserHandles[i]
13672                                + " => " + perUserInstalled[i]);
13673                    }
13674                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
13675
13676                    mSettings.writeRuntimePermissionsForUserLPr(allUserHandles[i], false);
13677                }
13678                // Regardless of writeSettings we need to ensure that this restriction
13679                // state propagation is persisted
13680                mSettings.writeAllUsersPackageRestrictionsLPr();
13681            }
13682            // can downgrade to reader here
13683            if (writeSettings) {
13684                mSettings.writeLPr();
13685            }
13686        }
13687        return true;
13688    }
13689
13690    private boolean deleteInstalledPackageLI(PackageSetting ps,
13691            boolean deleteCodeAndResources, int flags,
13692            int[] allUserHandles, boolean[] perUserInstalled,
13693            PackageRemovedInfo outInfo, boolean writeSettings) {
13694        if (outInfo != null) {
13695            outInfo.uid = ps.appId;
13696        }
13697
13698        // Delete package data from internal structures and also remove data if flag is set
13699        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
13700
13701        // Delete application code and resources
13702        if (deleteCodeAndResources && (outInfo != null)) {
13703            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
13704                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
13705            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
13706        }
13707        return true;
13708    }
13709
13710    @Override
13711    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
13712            int userId) {
13713        mContext.enforceCallingOrSelfPermission(
13714                android.Manifest.permission.DELETE_PACKAGES, null);
13715        synchronized (mPackages) {
13716            PackageSetting ps = mSettings.mPackages.get(packageName);
13717            if (ps == null) {
13718                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
13719                return false;
13720            }
13721            if (!ps.getInstalled(userId)) {
13722                // Can't block uninstall for an app that is not installed or enabled.
13723                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
13724                return false;
13725            }
13726            ps.setBlockUninstall(blockUninstall, userId);
13727            mSettings.writePackageRestrictionsLPr(userId);
13728        }
13729        return true;
13730    }
13731
13732    @Override
13733    public boolean getBlockUninstallForUser(String packageName, int userId) {
13734        synchronized (mPackages) {
13735            PackageSetting ps = mSettings.mPackages.get(packageName);
13736            if (ps == null) {
13737                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
13738                return false;
13739            }
13740            return ps.getBlockUninstall(userId);
13741        }
13742    }
13743
13744    @Override
13745    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
13746        int callingUid = Binder.getCallingUid();
13747        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
13748            throw new SecurityException(
13749                    "setRequiredForSystemUser can only be run by the system or root");
13750        }
13751        synchronized (mPackages) {
13752            PackageSetting ps = mSettings.mPackages.get(packageName);
13753            if (ps == null) {
13754                Log.w(TAG, "Package doesn't exist: " + packageName);
13755                return false;
13756            }
13757            if (systemUserApp) {
13758                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13759            } else {
13760                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
13761            }
13762            mSettings.writeLPr();
13763        }
13764        return true;
13765    }
13766
13767    /*
13768     * This method handles package deletion in general
13769     */
13770    private boolean deletePackageLI(String packageName, UserHandle user,
13771            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
13772            int flags, PackageRemovedInfo outInfo,
13773            boolean writeSettings) {
13774        if (packageName == null) {
13775            Slog.w(TAG, "Attempt to delete null packageName.");
13776            return false;
13777        }
13778        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
13779        PackageSetting ps;
13780        boolean dataOnly = false;
13781        int removeUser = -1;
13782        int appId = -1;
13783        synchronized (mPackages) {
13784            ps = mSettings.mPackages.get(packageName);
13785            if (ps == null) {
13786                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
13787                return false;
13788            }
13789            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
13790                    && user.getIdentifier() != UserHandle.USER_ALL) {
13791                // The caller is asking that the package only be deleted for a single
13792                // user.  To do this, we just mark its uninstalled state and delete
13793                // its data.  If this is a system app, we only allow this to happen if
13794                // they have set the special DELETE_SYSTEM_APP which requests different
13795                // semantics than normal for uninstalling system apps.
13796                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
13797                final int userId = user.getIdentifier();
13798                ps.setUserState(userId,
13799                        COMPONENT_ENABLED_STATE_DEFAULT,
13800                        false, //installed
13801                        true,  //stopped
13802                        true,  //notLaunched
13803                        false, //hidden
13804                        false, //suspended
13805                        null, null, null,
13806                        false, // blockUninstall
13807                        ps.readUserState(userId).domainVerificationStatus, 0);
13808                if (!isSystemApp(ps)) {
13809                    // Do not uninstall the APK if an app should be cached
13810                    boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
13811                    if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
13812                        // Other user still have this package installed, so all
13813                        // we need to do is clear this user's data and save that
13814                        // it is uninstalled.
13815                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
13816                        removeUser = user.getIdentifier();
13817                        appId = ps.appId;
13818                        scheduleWritePackageRestrictionsLocked(removeUser);
13819                    } else {
13820                        // We need to set it back to 'installed' so the uninstall
13821                        // broadcasts will be sent correctly.
13822                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
13823                        ps.setInstalled(true, user.getIdentifier());
13824                    }
13825                } else {
13826                    // This is a system app, so we assume that the
13827                    // other users still have this package installed, so all
13828                    // we need to do is clear this user's data and save that
13829                    // it is uninstalled.
13830                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
13831                    removeUser = user.getIdentifier();
13832                    appId = ps.appId;
13833                    scheduleWritePackageRestrictionsLocked(removeUser);
13834                }
13835            }
13836        }
13837
13838        if (removeUser >= 0) {
13839            // From above, we determined that we are deleting this only
13840            // for a single user.  Continue the work here.
13841            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
13842            if (outInfo != null) {
13843                outInfo.removedPackage = packageName;
13844                outInfo.removedAppId = appId;
13845                outInfo.removedUsers = new int[] {removeUser};
13846            }
13847            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
13848            removeKeystoreDataIfNeeded(removeUser, appId);
13849            schedulePackageCleaning(packageName, removeUser, false);
13850            synchronized (mPackages) {
13851                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
13852                    scheduleWritePackageRestrictionsLocked(removeUser);
13853                }
13854                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, removeUser);
13855            }
13856            return true;
13857        }
13858
13859        if (dataOnly) {
13860            // Delete application data first
13861            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
13862            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
13863            return true;
13864        }
13865
13866        boolean ret = false;
13867        if (isSystemApp(ps)) {
13868            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
13869            // When an updated system application is deleted we delete the existing resources as well and
13870            // fall back to existing code in system partition
13871            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
13872                    flags, outInfo, writeSettings);
13873        } else {
13874            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
13875            // Kill application pre-emptively especially for apps on sd.
13876            killApplication(packageName, ps.appId, "uninstall pkg");
13877            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
13878                    allUserHandles, perUserInstalled,
13879                    outInfo, writeSettings);
13880        }
13881
13882        return ret;
13883    }
13884
13885    private final static class ClearStorageConnection implements ServiceConnection {
13886        IMediaContainerService mContainerService;
13887
13888        @Override
13889        public void onServiceConnected(ComponentName name, IBinder service) {
13890            synchronized (this) {
13891                mContainerService = IMediaContainerService.Stub.asInterface(service);
13892                notifyAll();
13893            }
13894        }
13895
13896        @Override
13897        public void onServiceDisconnected(ComponentName name) {
13898        }
13899    }
13900
13901    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
13902        final boolean mounted;
13903        if (Environment.isExternalStorageEmulated()) {
13904            mounted = true;
13905        } else {
13906            final String status = Environment.getExternalStorageState();
13907
13908            mounted = status.equals(Environment.MEDIA_MOUNTED)
13909                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
13910        }
13911
13912        if (!mounted) {
13913            return;
13914        }
13915
13916        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
13917        int[] users;
13918        if (userId == UserHandle.USER_ALL) {
13919            users = sUserManager.getUserIds();
13920        } else {
13921            users = new int[] { userId };
13922        }
13923        final ClearStorageConnection conn = new ClearStorageConnection();
13924        if (mContext.bindServiceAsUser(
13925                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
13926            try {
13927                for (int curUser : users) {
13928                    long timeout = SystemClock.uptimeMillis() + 5000;
13929                    synchronized (conn) {
13930                        long now = SystemClock.uptimeMillis();
13931                        while (conn.mContainerService == null && now < timeout) {
13932                            try {
13933                                conn.wait(timeout - now);
13934                            } catch (InterruptedException e) {
13935                            }
13936                        }
13937                    }
13938                    if (conn.mContainerService == null) {
13939                        return;
13940                    }
13941
13942                    final UserEnvironment userEnv = new UserEnvironment(curUser);
13943                    clearDirectory(conn.mContainerService,
13944                            userEnv.buildExternalStorageAppCacheDirs(packageName));
13945                    if (allData) {
13946                        clearDirectory(conn.mContainerService,
13947                                userEnv.buildExternalStorageAppDataDirs(packageName));
13948                        clearDirectory(conn.mContainerService,
13949                                userEnv.buildExternalStorageAppMediaDirs(packageName));
13950                    }
13951                }
13952            } finally {
13953                mContext.unbindService(conn);
13954            }
13955        }
13956    }
13957
13958    @Override
13959    public void clearApplicationUserData(final String packageName,
13960            final IPackageDataObserver observer, final int userId) {
13961        mContext.enforceCallingOrSelfPermission(
13962                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
13963        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
13964        // Queue up an async operation since the package deletion may take a little while.
13965        mHandler.post(new Runnable() {
13966            public void run() {
13967                mHandler.removeCallbacks(this);
13968                final boolean succeeded;
13969                synchronized (mInstallLock) {
13970                    succeeded = clearApplicationUserDataLI(packageName, userId);
13971                }
13972                clearExternalStorageDataSync(packageName, userId, true);
13973                if (succeeded) {
13974                    // invoke DeviceStorageMonitor's update method to clear any notifications
13975                    DeviceStorageMonitorInternal
13976                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13977                    if (dsm != null) {
13978                        dsm.checkMemory();
13979                    }
13980                }
13981                if(observer != null) {
13982                    try {
13983                        observer.onRemoveCompleted(packageName, succeeded);
13984                    } catch (RemoteException e) {
13985                        Log.i(TAG, "Observer no longer exists.");
13986                    }
13987                } //end if observer
13988            } //end run
13989        });
13990    }
13991
13992    private boolean clearApplicationUserDataLI(String packageName, int userId) {
13993        if (packageName == null) {
13994            Slog.w(TAG, "Attempt to delete null packageName.");
13995            return false;
13996        }
13997
13998        // Try finding details about the requested package
13999        PackageParser.Package pkg;
14000        synchronized (mPackages) {
14001            pkg = mPackages.get(packageName);
14002            if (pkg == null) {
14003                final PackageSetting ps = mSettings.mPackages.get(packageName);
14004                if (ps != null) {
14005                    pkg = ps.pkg;
14006                }
14007            }
14008
14009            if (pkg == null) {
14010                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14011                return false;
14012            }
14013
14014            PackageSetting ps = (PackageSetting) pkg.mExtras;
14015            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14016        }
14017
14018        // Always delete data directories for package, even if we found no other
14019        // record of app. This helps users recover from UID mismatches without
14020        // resorting to a full data wipe.
14021        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
14022        if (retCode < 0) {
14023            Slog.w(TAG, "Couldn't remove cache files for package " + packageName);
14024            return false;
14025        }
14026
14027        final int appId = pkg.applicationInfo.uid;
14028        removeKeystoreDataIfNeeded(userId, appId);
14029
14030        // Create a native library symlink only if we have native libraries
14031        // and if the native libraries are 32 bit libraries. We do not provide
14032        // this symlink for 64 bit libraries.
14033        if (pkg.applicationInfo.primaryCpuAbi != null &&
14034                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
14035            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
14036            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
14037                    nativeLibPath, userId) < 0) {
14038                Slog.w(TAG, "Failed linking native library dir");
14039                return false;
14040            }
14041        }
14042
14043        return true;
14044    }
14045
14046    /**
14047     * Reverts user permission state changes (permissions and flags) in
14048     * all packages for a given user.
14049     *
14050     * @param userId The device user for which to do a reset.
14051     */
14052    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
14053        final int packageCount = mPackages.size();
14054        for (int i = 0; i < packageCount; i++) {
14055            PackageParser.Package pkg = mPackages.valueAt(i);
14056            PackageSetting ps = (PackageSetting) pkg.mExtras;
14057            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
14058        }
14059    }
14060
14061    /**
14062     * Reverts user permission state changes (permissions and flags).
14063     *
14064     * @param ps The package for which to reset.
14065     * @param userId The device user for which to do a reset.
14066     */
14067    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
14068            final PackageSetting ps, final int userId) {
14069        if (ps.pkg == null) {
14070            return;
14071        }
14072
14073        // These are flags that can change base on user actions.
14074        final int userSettableMask = FLAG_PERMISSION_USER_SET
14075                | FLAG_PERMISSION_USER_FIXED
14076                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
14077                | FLAG_PERMISSION_REVIEW_REQUIRED;
14078
14079        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
14080                | FLAG_PERMISSION_POLICY_FIXED;
14081
14082        boolean writeInstallPermissions = false;
14083        boolean writeRuntimePermissions = false;
14084
14085        final int permissionCount = ps.pkg.requestedPermissions.size();
14086        for (int i = 0; i < permissionCount; i++) {
14087            String permission = ps.pkg.requestedPermissions.get(i);
14088
14089            BasePermission bp = mSettings.mPermissions.get(permission);
14090            if (bp == null) {
14091                continue;
14092            }
14093
14094            // If shared user we just reset the state to which only this app contributed.
14095            if (ps.sharedUser != null) {
14096                boolean used = false;
14097                final int packageCount = ps.sharedUser.packages.size();
14098                for (int j = 0; j < packageCount; j++) {
14099                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
14100                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
14101                            && pkg.pkg.requestedPermissions.contains(permission)) {
14102                        used = true;
14103                        break;
14104                    }
14105                }
14106                if (used) {
14107                    continue;
14108                }
14109            }
14110
14111            PermissionsState permissionsState = ps.getPermissionsState();
14112
14113            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
14114
14115            // Always clear the user settable flags.
14116            final boolean hasInstallState = permissionsState.getInstallPermissionState(
14117                    bp.name) != null;
14118            // If permission review is enabled and this is a legacy app, mark the
14119            // permission as requiring a review as this is the initial state.
14120            int flags = 0;
14121            if (Build.PERMISSIONS_REVIEW_REQUIRED
14122                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
14123                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
14124            }
14125            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
14126                if (hasInstallState) {
14127                    writeInstallPermissions = true;
14128                } else {
14129                    writeRuntimePermissions = true;
14130                }
14131            }
14132
14133            // Below is only runtime permission handling.
14134            if (!bp.isRuntime()) {
14135                continue;
14136            }
14137
14138            // Never clobber system or policy.
14139            if ((oldFlags & policyOrSystemFlags) != 0) {
14140                continue;
14141            }
14142
14143            // If this permission was granted by default, make sure it is.
14144            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
14145                if (permissionsState.grantRuntimePermission(bp, userId)
14146                        != PERMISSION_OPERATION_FAILURE) {
14147                    writeRuntimePermissions = true;
14148                }
14149            // If permission review is enabled the permissions for a legacy apps
14150            // are represented as constantly granted runtime ones, so don't revoke.
14151            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
14152                // Otherwise, reset the permission.
14153                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
14154                switch (revokeResult) {
14155                    case PERMISSION_OPERATION_SUCCESS: {
14156                        writeRuntimePermissions = true;
14157                    } break;
14158
14159                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
14160                        writeRuntimePermissions = true;
14161                        final int appId = ps.appId;
14162                        mHandler.post(new Runnable() {
14163                            @Override
14164                            public void run() {
14165                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
14166                            }
14167                        });
14168                    } break;
14169                }
14170            }
14171        }
14172
14173        // Synchronously write as we are taking permissions away.
14174        if (writeRuntimePermissions) {
14175            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
14176        }
14177
14178        // Synchronously write as we are taking permissions away.
14179        if (writeInstallPermissions) {
14180            mSettings.writeLPr();
14181        }
14182    }
14183
14184    /**
14185     * Remove entries from the keystore daemon. Will only remove it if the
14186     * {@code appId} is valid.
14187     */
14188    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
14189        if (appId < 0) {
14190            return;
14191        }
14192
14193        final KeyStore keyStore = KeyStore.getInstance();
14194        if (keyStore != null) {
14195            if (userId == UserHandle.USER_ALL) {
14196                for (final int individual : sUserManager.getUserIds()) {
14197                    keyStore.clearUid(UserHandle.getUid(individual, appId));
14198                }
14199            } else {
14200                keyStore.clearUid(UserHandle.getUid(userId, appId));
14201            }
14202        } else {
14203            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
14204        }
14205    }
14206
14207    @Override
14208    public void deleteApplicationCacheFiles(final String packageName,
14209            final IPackageDataObserver observer) {
14210        mContext.enforceCallingOrSelfPermission(
14211                android.Manifest.permission.DELETE_CACHE_FILES, null);
14212        // Queue up an async operation since the package deletion may take a little while.
14213        final int userId = UserHandle.getCallingUserId();
14214        mHandler.post(new Runnable() {
14215            public void run() {
14216                mHandler.removeCallbacks(this);
14217                final boolean succeded;
14218                synchronized (mInstallLock) {
14219                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
14220                }
14221                clearExternalStorageDataSync(packageName, userId, false);
14222                if (observer != null) {
14223                    try {
14224                        observer.onRemoveCompleted(packageName, succeded);
14225                    } catch (RemoteException e) {
14226                        Log.i(TAG, "Observer no longer exists.");
14227                    }
14228                } //end if observer
14229            } //end run
14230        });
14231    }
14232
14233    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
14234        if (packageName == null) {
14235            Slog.w(TAG, "Attempt to delete null packageName.");
14236            return false;
14237        }
14238        PackageParser.Package p;
14239        synchronized (mPackages) {
14240            p = mPackages.get(packageName);
14241        }
14242        if (p == null) {
14243            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14244            return false;
14245        }
14246        final ApplicationInfo applicationInfo = p.applicationInfo;
14247        if (applicationInfo == null) {
14248            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14249            return false;
14250        }
14251        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
14252        if (retCode < 0) {
14253            Slog.w(TAG, "Couldn't remove cache files for package "
14254                       + packageName + " u" + userId);
14255            return false;
14256        }
14257        return true;
14258    }
14259
14260    @Override
14261    public void getPackageSizeInfo(final String packageName, int userHandle,
14262            final IPackageStatsObserver observer) {
14263        mContext.enforceCallingOrSelfPermission(
14264                android.Manifest.permission.GET_PACKAGE_SIZE, null);
14265        if (packageName == null) {
14266            throw new IllegalArgumentException("Attempt to get size of null packageName");
14267        }
14268
14269        PackageStats stats = new PackageStats(packageName, userHandle);
14270
14271        /*
14272         * Queue up an async operation since the package measurement may take a
14273         * little while.
14274         */
14275        Message msg = mHandler.obtainMessage(INIT_COPY);
14276        msg.obj = new MeasureParams(stats, observer);
14277        mHandler.sendMessage(msg);
14278    }
14279
14280    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
14281            PackageStats pStats) {
14282        if (packageName == null) {
14283            Slog.w(TAG, "Attempt to get size of null packageName.");
14284            return false;
14285        }
14286        PackageParser.Package p;
14287        boolean dataOnly = false;
14288        String libDirRoot = null;
14289        String asecPath = null;
14290        PackageSetting ps = null;
14291        synchronized (mPackages) {
14292            p = mPackages.get(packageName);
14293            ps = mSettings.mPackages.get(packageName);
14294            if(p == null) {
14295                dataOnly = true;
14296                if((ps == null) || (ps.pkg == null)) {
14297                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
14298                    return false;
14299                }
14300                p = ps.pkg;
14301            }
14302            if (ps != null) {
14303                libDirRoot = ps.legacyNativeLibraryPathString;
14304            }
14305            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
14306                final long token = Binder.clearCallingIdentity();
14307                try {
14308                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
14309                    if (secureContainerId != null) {
14310                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
14311                    }
14312                } finally {
14313                    Binder.restoreCallingIdentity(token);
14314                }
14315            }
14316        }
14317        String publicSrcDir = null;
14318        if(!dataOnly) {
14319            final ApplicationInfo applicationInfo = p.applicationInfo;
14320            if (applicationInfo == null) {
14321                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
14322                return false;
14323            }
14324            if (p.isForwardLocked()) {
14325                publicSrcDir = applicationInfo.getBaseResourcePath();
14326            }
14327        }
14328        // TODO: extend to measure size of split APKs
14329        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
14330        // not just the first level.
14331        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
14332        // just the primary.
14333        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
14334
14335        String apkPath;
14336        File packageDir = new File(p.codePath);
14337
14338        if (packageDir.isDirectory() && p.canHaveOatDir()) {
14339            apkPath = packageDir.getAbsolutePath();
14340            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
14341            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
14342                libDirRoot = null;
14343            }
14344        } else {
14345            apkPath = p.baseCodePath;
14346        }
14347
14348        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, apkPath,
14349                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
14350        if (res < 0) {
14351            return false;
14352        }
14353
14354        // Fix-up for forward-locked applications in ASEC containers.
14355        if (!isExternal(p)) {
14356            pStats.codeSize += pStats.externalCodeSize;
14357            pStats.externalCodeSize = 0L;
14358        }
14359
14360        return true;
14361    }
14362
14363
14364    @Override
14365    public void addPackageToPreferred(String packageName) {
14366        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
14367    }
14368
14369    @Override
14370    public void removePackageFromPreferred(String packageName) {
14371        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
14372    }
14373
14374    @Override
14375    public List<PackageInfo> getPreferredPackages(int flags) {
14376        return new ArrayList<PackageInfo>();
14377    }
14378
14379    private int getUidTargetSdkVersionLockedLPr(int uid) {
14380        Object obj = mSettings.getUserIdLPr(uid);
14381        if (obj instanceof SharedUserSetting) {
14382            final SharedUserSetting sus = (SharedUserSetting) obj;
14383            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
14384            final Iterator<PackageSetting> it = sus.packages.iterator();
14385            while (it.hasNext()) {
14386                final PackageSetting ps = it.next();
14387                if (ps.pkg != null) {
14388                    int v = ps.pkg.applicationInfo.targetSdkVersion;
14389                    if (v < vers) vers = v;
14390                }
14391            }
14392            return vers;
14393        } else if (obj instanceof PackageSetting) {
14394            final PackageSetting ps = (PackageSetting) obj;
14395            if (ps.pkg != null) {
14396                return ps.pkg.applicationInfo.targetSdkVersion;
14397            }
14398        }
14399        return Build.VERSION_CODES.CUR_DEVELOPMENT;
14400    }
14401
14402    @Override
14403    public void addPreferredActivity(IntentFilter filter, int match,
14404            ComponentName[] set, ComponentName activity, int userId) {
14405        addPreferredActivityInternal(filter, match, set, activity, true, userId,
14406                "Adding preferred");
14407    }
14408
14409    private void addPreferredActivityInternal(IntentFilter filter, int match,
14410            ComponentName[] set, ComponentName activity, boolean always, int userId,
14411            String opname) {
14412        // writer
14413        int callingUid = Binder.getCallingUid();
14414        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
14415        if (filter.countActions() == 0) {
14416            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14417            return;
14418        }
14419        synchronized (mPackages) {
14420            if (mContext.checkCallingOrSelfPermission(
14421                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14422                    != PackageManager.PERMISSION_GRANTED) {
14423                if (getUidTargetSdkVersionLockedLPr(callingUid)
14424                        < Build.VERSION_CODES.FROYO) {
14425                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
14426                            + callingUid);
14427                    return;
14428                }
14429                mContext.enforceCallingOrSelfPermission(
14430                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14431            }
14432
14433            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
14434            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
14435                    + userId + ":");
14436            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14437            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
14438            scheduleWritePackageRestrictionsLocked(userId);
14439        }
14440    }
14441
14442    @Override
14443    public void replacePreferredActivity(IntentFilter filter, int match,
14444            ComponentName[] set, ComponentName activity, int userId) {
14445        if (filter.countActions() != 1) {
14446            throw new IllegalArgumentException(
14447                    "replacePreferredActivity expects filter to have only 1 action.");
14448        }
14449        if (filter.countDataAuthorities() != 0
14450                || filter.countDataPaths() != 0
14451                || filter.countDataSchemes() > 1
14452                || filter.countDataTypes() != 0) {
14453            throw new IllegalArgumentException(
14454                    "replacePreferredActivity expects filter to have no data authorities, " +
14455                    "paths, or types; and at most one scheme.");
14456        }
14457
14458        final int callingUid = Binder.getCallingUid();
14459        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
14460        synchronized (mPackages) {
14461            if (mContext.checkCallingOrSelfPermission(
14462                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14463                    != PackageManager.PERMISSION_GRANTED) {
14464                if (getUidTargetSdkVersionLockedLPr(callingUid)
14465                        < Build.VERSION_CODES.FROYO) {
14466                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
14467                            + Binder.getCallingUid());
14468                    return;
14469                }
14470                mContext.enforceCallingOrSelfPermission(
14471                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14472            }
14473
14474            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14475            if (pir != null) {
14476                // Get all of the existing entries that exactly match this filter.
14477                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
14478                if (existing != null && existing.size() == 1) {
14479                    PreferredActivity cur = existing.get(0);
14480                    if (DEBUG_PREFERRED) {
14481                        Slog.i(TAG, "Checking replace of preferred:");
14482                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14483                        if (!cur.mPref.mAlways) {
14484                            Slog.i(TAG, "  -- CUR; not mAlways!");
14485                        } else {
14486                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
14487                            Slog.i(TAG, "  -- CUR: mSet="
14488                                    + Arrays.toString(cur.mPref.mSetComponents));
14489                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
14490                            Slog.i(TAG, "  -- NEW: mMatch="
14491                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
14492                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
14493                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
14494                        }
14495                    }
14496                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
14497                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
14498                            && cur.mPref.sameSet(set)) {
14499                        // Setting the preferred activity to what it happens to be already
14500                        if (DEBUG_PREFERRED) {
14501                            Slog.i(TAG, "Replacing with same preferred activity "
14502                                    + cur.mPref.mShortComponent + " for user "
14503                                    + userId + ":");
14504                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14505                        }
14506                        return;
14507                    }
14508                }
14509
14510                if (existing != null) {
14511                    if (DEBUG_PREFERRED) {
14512                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
14513                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14514                    }
14515                    for (int i = 0; i < existing.size(); i++) {
14516                        PreferredActivity pa = existing.get(i);
14517                        if (DEBUG_PREFERRED) {
14518                            Slog.i(TAG, "Removing existing preferred activity "
14519                                    + pa.mPref.mComponent + ":");
14520                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
14521                        }
14522                        pir.removeFilter(pa);
14523                    }
14524                }
14525            }
14526            addPreferredActivityInternal(filter, match, set, activity, true, userId,
14527                    "Replacing preferred");
14528        }
14529    }
14530
14531    @Override
14532    public void clearPackagePreferredActivities(String packageName) {
14533        final int uid = Binder.getCallingUid();
14534        // writer
14535        synchronized (mPackages) {
14536            PackageParser.Package pkg = mPackages.get(packageName);
14537            if (pkg == null || pkg.applicationInfo.uid != uid) {
14538                if (mContext.checkCallingOrSelfPermission(
14539                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
14540                        != PackageManager.PERMISSION_GRANTED) {
14541                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
14542                            < Build.VERSION_CODES.FROYO) {
14543                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
14544                                + Binder.getCallingUid());
14545                        return;
14546                    }
14547                    mContext.enforceCallingOrSelfPermission(
14548                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14549                }
14550            }
14551
14552            int user = UserHandle.getCallingUserId();
14553            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
14554                scheduleWritePackageRestrictionsLocked(user);
14555            }
14556        }
14557    }
14558
14559    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14560    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
14561        ArrayList<PreferredActivity> removed = null;
14562        boolean changed = false;
14563        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
14564            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
14565            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
14566            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
14567                continue;
14568            }
14569            Iterator<PreferredActivity> it = pir.filterIterator();
14570            while (it.hasNext()) {
14571                PreferredActivity pa = it.next();
14572                // Mark entry for removal only if it matches the package name
14573                // and the entry is of type "always".
14574                if (packageName == null ||
14575                        (pa.mPref.mComponent.getPackageName().equals(packageName)
14576                                && pa.mPref.mAlways)) {
14577                    if (removed == null) {
14578                        removed = new ArrayList<PreferredActivity>();
14579                    }
14580                    removed.add(pa);
14581                }
14582            }
14583            if (removed != null) {
14584                for (int j=0; j<removed.size(); j++) {
14585                    PreferredActivity pa = removed.get(j);
14586                    pir.removeFilter(pa);
14587                }
14588                changed = true;
14589            }
14590        }
14591        return changed;
14592    }
14593
14594    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14595    private void clearIntentFilterVerificationsLPw(int userId) {
14596        final int packageCount = mPackages.size();
14597        for (int i = 0; i < packageCount; i++) {
14598            PackageParser.Package pkg = mPackages.valueAt(i);
14599            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
14600        }
14601    }
14602
14603    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
14604    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
14605        if (userId == UserHandle.USER_ALL) {
14606            if (mSettings.removeIntentFilterVerificationLPw(packageName,
14607                    sUserManager.getUserIds())) {
14608                for (int oneUserId : sUserManager.getUserIds()) {
14609                    scheduleWritePackageRestrictionsLocked(oneUserId);
14610                }
14611            }
14612        } else {
14613            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
14614                scheduleWritePackageRestrictionsLocked(userId);
14615            }
14616        }
14617    }
14618
14619    void clearDefaultBrowserIfNeeded(String packageName) {
14620        for (int oneUserId : sUserManager.getUserIds()) {
14621            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
14622            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
14623            if (packageName.equals(defaultBrowserPackageName)) {
14624                setDefaultBrowserPackageName(null, oneUserId);
14625            }
14626        }
14627    }
14628
14629    @Override
14630    public void resetApplicationPreferences(int userId) {
14631        mContext.enforceCallingOrSelfPermission(
14632                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14633        // writer
14634        synchronized (mPackages) {
14635            final long identity = Binder.clearCallingIdentity();
14636            try {
14637                clearPackagePreferredActivitiesLPw(null, userId);
14638                mSettings.applyDefaultPreferredAppsLPw(this, userId);
14639                // TODO: We have to reset the default SMS and Phone. This requires
14640                // significant refactoring to keep all default apps in the package
14641                // manager (cleaner but more work) or have the services provide
14642                // callbacks to the package manager to request a default app reset.
14643                applyFactoryDefaultBrowserLPw(userId);
14644                clearIntentFilterVerificationsLPw(userId);
14645                primeDomainVerificationsLPw(userId);
14646                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
14647                scheduleWritePackageRestrictionsLocked(userId);
14648            } finally {
14649                Binder.restoreCallingIdentity(identity);
14650            }
14651        }
14652    }
14653
14654    @Override
14655    public int getPreferredActivities(List<IntentFilter> outFilters,
14656            List<ComponentName> outActivities, String packageName) {
14657
14658        int num = 0;
14659        final int userId = UserHandle.getCallingUserId();
14660        // reader
14661        synchronized (mPackages) {
14662            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
14663            if (pir != null) {
14664                final Iterator<PreferredActivity> it = pir.filterIterator();
14665                while (it.hasNext()) {
14666                    final PreferredActivity pa = it.next();
14667                    if (packageName == null
14668                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
14669                                    && pa.mPref.mAlways)) {
14670                        if (outFilters != null) {
14671                            outFilters.add(new IntentFilter(pa));
14672                        }
14673                        if (outActivities != null) {
14674                            outActivities.add(pa.mPref.mComponent);
14675                        }
14676                    }
14677                }
14678            }
14679        }
14680
14681        return num;
14682    }
14683
14684    @Override
14685    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
14686            int userId) {
14687        int callingUid = Binder.getCallingUid();
14688        if (callingUid != Process.SYSTEM_UID) {
14689            throw new SecurityException(
14690                    "addPersistentPreferredActivity can only be run by the system");
14691        }
14692        if (filter.countActions() == 0) {
14693            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
14694            return;
14695        }
14696        synchronized (mPackages) {
14697            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
14698                    ":");
14699            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
14700            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
14701                    new PersistentPreferredActivity(filter, activity));
14702            scheduleWritePackageRestrictionsLocked(userId);
14703        }
14704    }
14705
14706    @Override
14707    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
14708        int callingUid = Binder.getCallingUid();
14709        if (callingUid != Process.SYSTEM_UID) {
14710            throw new SecurityException(
14711                    "clearPackagePersistentPreferredActivities can only be run by the system");
14712        }
14713        ArrayList<PersistentPreferredActivity> removed = null;
14714        boolean changed = false;
14715        synchronized (mPackages) {
14716            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
14717                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
14718                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
14719                        .valueAt(i);
14720                if (userId != thisUserId) {
14721                    continue;
14722                }
14723                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
14724                while (it.hasNext()) {
14725                    PersistentPreferredActivity ppa = it.next();
14726                    // Mark entry for removal only if it matches the package name.
14727                    if (ppa.mComponent.getPackageName().equals(packageName)) {
14728                        if (removed == null) {
14729                            removed = new ArrayList<PersistentPreferredActivity>();
14730                        }
14731                        removed.add(ppa);
14732                    }
14733                }
14734                if (removed != null) {
14735                    for (int j=0; j<removed.size(); j++) {
14736                        PersistentPreferredActivity ppa = removed.get(j);
14737                        ppir.removeFilter(ppa);
14738                    }
14739                    changed = true;
14740                }
14741            }
14742
14743            if (changed) {
14744                scheduleWritePackageRestrictionsLocked(userId);
14745            }
14746        }
14747    }
14748
14749    /**
14750     * Common machinery for picking apart a restored XML blob and passing
14751     * it to a caller-supplied functor to be applied to the running system.
14752     */
14753    private void restoreFromXml(XmlPullParser parser, int userId,
14754            String expectedStartTag, BlobXmlRestorer functor)
14755            throws IOException, XmlPullParserException {
14756        int type;
14757        while ((type = parser.next()) != XmlPullParser.START_TAG
14758                && type != XmlPullParser.END_DOCUMENT) {
14759        }
14760        if (type != XmlPullParser.START_TAG) {
14761            // oops didn't find a start tag?!
14762            if (DEBUG_BACKUP) {
14763                Slog.e(TAG, "Didn't find start tag during restore");
14764            }
14765            return;
14766        }
14767
14768        // this is supposed to be TAG_PREFERRED_BACKUP
14769        if (!expectedStartTag.equals(parser.getName())) {
14770            if (DEBUG_BACKUP) {
14771                Slog.e(TAG, "Found unexpected tag " + parser.getName());
14772            }
14773            return;
14774        }
14775
14776        // skip interfering stuff, then we're aligned with the backing implementation
14777        while ((type = parser.next()) == XmlPullParser.TEXT) { }
14778        functor.apply(parser, userId);
14779    }
14780
14781    private interface BlobXmlRestorer {
14782        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
14783    }
14784
14785    /**
14786     * Non-Binder method, support for the backup/restore mechanism: write the
14787     * full set of preferred activities in its canonical XML format.  Returns the
14788     * XML output as a byte array, or null if there is none.
14789     */
14790    @Override
14791    public byte[] getPreferredActivityBackup(int userId) {
14792        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14793            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
14794        }
14795
14796        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14797        try {
14798            final XmlSerializer serializer = new FastXmlSerializer();
14799            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14800            serializer.startDocument(null, true);
14801            serializer.startTag(null, TAG_PREFERRED_BACKUP);
14802
14803            synchronized (mPackages) {
14804                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
14805            }
14806
14807            serializer.endTag(null, TAG_PREFERRED_BACKUP);
14808            serializer.endDocument();
14809            serializer.flush();
14810        } catch (Exception e) {
14811            if (DEBUG_BACKUP) {
14812                Slog.e(TAG, "Unable to write preferred activities for backup", e);
14813            }
14814            return null;
14815        }
14816
14817        return dataStream.toByteArray();
14818    }
14819
14820    @Override
14821    public void restorePreferredActivities(byte[] backup, int userId) {
14822        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14823            throw new SecurityException("Only the system may call restorePreferredActivities()");
14824        }
14825
14826        try {
14827            final XmlPullParser parser = Xml.newPullParser();
14828            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14829            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
14830                    new BlobXmlRestorer() {
14831                        @Override
14832                        public void apply(XmlPullParser parser, int userId)
14833                                throws XmlPullParserException, IOException {
14834                            synchronized (mPackages) {
14835                                mSettings.readPreferredActivitiesLPw(parser, userId);
14836                            }
14837                        }
14838                    } );
14839        } catch (Exception e) {
14840            if (DEBUG_BACKUP) {
14841                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14842            }
14843        }
14844    }
14845
14846    /**
14847     * Non-Binder method, support for the backup/restore mechanism: write the
14848     * default browser (etc) settings in its canonical XML format.  Returns the default
14849     * browser XML representation as a byte array, or null if there is none.
14850     */
14851    @Override
14852    public byte[] getDefaultAppsBackup(int userId) {
14853        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14854            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
14855        }
14856
14857        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14858        try {
14859            final XmlSerializer serializer = new FastXmlSerializer();
14860            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14861            serializer.startDocument(null, true);
14862            serializer.startTag(null, TAG_DEFAULT_APPS);
14863
14864            synchronized (mPackages) {
14865                mSettings.writeDefaultAppsLPr(serializer, userId);
14866            }
14867
14868            serializer.endTag(null, TAG_DEFAULT_APPS);
14869            serializer.endDocument();
14870            serializer.flush();
14871        } catch (Exception e) {
14872            if (DEBUG_BACKUP) {
14873                Slog.e(TAG, "Unable to write default apps for backup", e);
14874            }
14875            return null;
14876        }
14877
14878        return dataStream.toByteArray();
14879    }
14880
14881    @Override
14882    public void restoreDefaultApps(byte[] backup, int userId) {
14883        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14884            throw new SecurityException("Only the system may call restoreDefaultApps()");
14885        }
14886
14887        try {
14888            final XmlPullParser parser = Xml.newPullParser();
14889            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14890            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
14891                    new BlobXmlRestorer() {
14892                        @Override
14893                        public void apply(XmlPullParser parser, int userId)
14894                                throws XmlPullParserException, IOException {
14895                            synchronized (mPackages) {
14896                                mSettings.readDefaultAppsLPw(parser, userId);
14897                            }
14898                        }
14899                    } );
14900        } catch (Exception e) {
14901            if (DEBUG_BACKUP) {
14902                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
14903            }
14904        }
14905    }
14906
14907    @Override
14908    public byte[] getIntentFilterVerificationBackup(int userId) {
14909        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14910            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
14911        }
14912
14913        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
14914        try {
14915            final XmlSerializer serializer = new FastXmlSerializer();
14916            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
14917            serializer.startDocument(null, true);
14918            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
14919
14920            synchronized (mPackages) {
14921                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
14922            }
14923
14924            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
14925            serializer.endDocument();
14926            serializer.flush();
14927        } catch (Exception e) {
14928            if (DEBUG_BACKUP) {
14929                Slog.e(TAG, "Unable to write default apps for backup", e);
14930            }
14931            return null;
14932        }
14933
14934        return dataStream.toByteArray();
14935    }
14936
14937    @Override
14938    public void restoreIntentFilterVerification(byte[] backup, int userId) {
14939        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
14940            throw new SecurityException("Only the system may call restorePreferredActivities()");
14941        }
14942
14943        try {
14944            final XmlPullParser parser = Xml.newPullParser();
14945            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
14946            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
14947                    new BlobXmlRestorer() {
14948                        @Override
14949                        public void apply(XmlPullParser parser, int userId)
14950                                throws XmlPullParserException, IOException {
14951                            synchronized (mPackages) {
14952                                mSettings.readAllDomainVerificationsLPr(parser, userId);
14953                                mSettings.writeLPr();
14954                            }
14955                        }
14956                    } );
14957        } catch (Exception e) {
14958            if (DEBUG_BACKUP) {
14959                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
14960            }
14961        }
14962    }
14963
14964    @Override
14965    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
14966            int sourceUserId, int targetUserId, int flags) {
14967        mContext.enforceCallingOrSelfPermission(
14968                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14969        int callingUid = Binder.getCallingUid();
14970        enforceOwnerRights(ownerPackage, callingUid);
14971        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
14972        if (intentFilter.countActions() == 0) {
14973            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
14974            return;
14975        }
14976        synchronized (mPackages) {
14977            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
14978                    ownerPackage, targetUserId, flags);
14979            CrossProfileIntentResolver resolver =
14980                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
14981            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
14982            // We have all those whose filter is equal. Now checking if the rest is equal as well.
14983            if (existing != null) {
14984                int size = existing.size();
14985                for (int i = 0; i < size; i++) {
14986                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
14987                        return;
14988                    }
14989                }
14990            }
14991            resolver.addFilter(newFilter);
14992            scheduleWritePackageRestrictionsLocked(sourceUserId);
14993        }
14994    }
14995
14996    @Override
14997    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
14998        mContext.enforceCallingOrSelfPermission(
14999                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
15000        int callingUid = Binder.getCallingUid();
15001        enforceOwnerRights(ownerPackage, callingUid);
15002        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
15003        synchronized (mPackages) {
15004            CrossProfileIntentResolver resolver =
15005                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
15006            ArraySet<CrossProfileIntentFilter> set =
15007                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
15008            for (CrossProfileIntentFilter filter : set) {
15009                if (filter.getOwnerPackage().equals(ownerPackage)) {
15010                    resolver.removeFilter(filter);
15011                }
15012            }
15013            scheduleWritePackageRestrictionsLocked(sourceUserId);
15014        }
15015    }
15016
15017    // Enforcing that callingUid is owning pkg on userId
15018    private void enforceOwnerRights(String pkg, int callingUid) {
15019        // The system owns everything.
15020        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
15021            return;
15022        }
15023        int callingUserId = UserHandle.getUserId(callingUid);
15024        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
15025        if (pi == null) {
15026            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
15027                    + callingUserId);
15028        }
15029        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
15030            throw new SecurityException("Calling uid " + callingUid
15031                    + " does not own package " + pkg);
15032        }
15033    }
15034
15035    @Override
15036    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
15037        Intent intent = new Intent(Intent.ACTION_MAIN);
15038        intent.addCategory(Intent.CATEGORY_HOME);
15039
15040        final int callingUserId = UserHandle.getCallingUserId();
15041        List<ResolveInfo> list = queryIntentActivities(intent, null,
15042                PackageManager.GET_META_DATA, callingUserId);
15043        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
15044                true, false, false, callingUserId);
15045
15046        allHomeCandidates.clear();
15047        if (list != null) {
15048            for (ResolveInfo ri : list) {
15049                allHomeCandidates.add(ri);
15050            }
15051        }
15052        return (preferred == null || preferred.activityInfo == null)
15053                ? null
15054                : new ComponentName(preferred.activityInfo.packageName,
15055                        preferred.activityInfo.name);
15056    }
15057
15058    @Override
15059    public void setApplicationEnabledSetting(String appPackageName,
15060            int newState, int flags, int userId, String callingPackage) {
15061        if (!sUserManager.exists(userId)) return;
15062        if (callingPackage == null) {
15063            callingPackage = Integer.toString(Binder.getCallingUid());
15064        }
15065        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
15066    }
15067
15068    @Override
15069    public void setComponentEnabledSetting(ComponentName componentName,
15070            int newState, int flags, int userId) {
15071        if (!sUserManager.exists(userId)) return;
15072        setEnabledSetting(componentName.getPackageName(),
15073                componentName.getClassName(), newState, flags, userId, null);
15074    }
15075
15076    private void setEnabledSetting(final String packageName, String className, int newState,
15077            final int flags, int userId, String callingPackage) {
15078        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
15079              || newState == COMPONENT_ENABLED_STATE_ENABLED
15080              || newState == COMPONENT_ENABLED_STATE_DISABLED
15081              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
15082              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
15083            throw new IllegalArgumentException("Invalid new component state: "
15084                    + newState);
15085        }
15086        PackageSetting pkgSetting;
15087        final int uid = Binder.getCallingUid();
15088        final int permission = mContext.checkCallingOrSelfPermission(
15089                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15090        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
15091        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15092        boolean sendNow = false;
15093        boolean isApp = (className == null);
15094        String componentName = isApp ? packageName : className;
15095        int packageUid = -1;
15096        ArrayList<String> components;
15097
15098        // writer
15099        synchronized (mPackages) {
15100            pkgSetting = mSettings.mPackages.get(packageName);
15101            if (pkgSetting == null) {
15102                if (className == null) {
15103                    throw new IllegalArgumentException("Unknown package: " + packageName);
15104                }
15105                throw new IllegalArgumentException(
15106                        "Unknown component: " + packageName + "/" + className);
15107            }
15108            // Allow root and verify that userId is not being specified by a different user
15109            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
15110                throw new SecurityException(
15111                        "Permission Denial: attempt to change component state from pid="
15112                        + Binder.getCallingPid()
15113                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
15114            }
15115            if (className == null) {
15116                // We're dealing with an application/package level state change
15117                if (pkgSetting.getEnabled(userId) == newState) {
15118                    // Nothing to do
15119                    return;
15120                }
15121                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
15122                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
15123                    // Don't care about who enables an app.
15124                    callingPackage = null;
15125                }
15126                pkgSetting.setEnabled(newState, userId, callingPackage);
15127                // pkgSetting.pkg.mSetEnabled = newState;
15128            } else {
15129                // We're dealing with a component level state change
15130                // First, verify that this is a valid class name.
15131                PackageParser.Package pkg = pkgSetting.pkg;
15132                if (pkg == null || !pkg.hasComponentClassName(className)) {
15133                    if (pkg != null &&
15134                            pkg.applicationInfo.targetSdkVersion >=
15135                                    Build.VERSION_CODES.JELLY_BEAN) {
15136                        throw new IllegalArgumentException("Component class " + className
15137                                + " does not exist in " + packageName);
15138                    } else {
15139                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
15140                                + className + " does not exist in " + packageName);
15141                    }
15142                }
15143                switch (newState) {
15144                case COMPONENT_ENABLED_STATE_ENABLED:
15145                    if (!pkgSetting.enableComponentLPw(className, userId)) {
15146                        return;
15147                    }
15148                    break;
15149                case COMPONENT_ENABLED_STATE_DISABLED:
15150                    if (!pkgSetting.disableComponentLPw(className, userId)) {
15151                        return;
15152                    }
15153                    break;
15154                case COMPONENT_ENABLED_STATE_DEFAULT:
15155                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
15156                        return;
15157                    }
15158                    break;
15159                default:
15160                    Slog.e(TAG, "Invalid new component state: " + newState);
15161                    return;
15162                }
15163            }
15164            scheduleWritePackageRestrictionsLocked(userId);
15165            components = mPendingBroadcasts.get(userId, packageName);
15166            final boolean newPackage = components == null;
15167            if (newPackage) {
15168                components = new ArrayList<String>();
15169            }
15170            if (!components.contains(componentName)) {
15171                components.add(componentName);
15172            }
15173            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
15174                sendNow = true;
15175                // Purge entry from pending broadcast list if another one exists already
15176                // since we are sending one right away.
15177                mPendingBroadcasts.remove(userId, packageName);
15178            } else {
15179                if (newPackage) {
15180                    mPendingBroadcasts.put(userId, packageName, components);
15181                }
15182                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
15183                    // Schedule a message
15184                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
15185                }
15186            }
15187        }
15188
15189        long callingId = Binder.clearCallingIdentity();
15190        try {
15191            if (sendNow) {
15192                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
15193                sendPackageChangedBroadcast(packageName,
15194                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
15195            }
15196        } finally {
15197            Binder.restoreCallingIdentity(callingId);
15198        }
15199    }
15200
15201    private void sendPackageChangedBroadcast(String packageName,
15202            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
15203        if (DEBUG_INSTALL)
15204            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
15205                    + componentNames);
15206        Bundle extras = new Bundle(4);
15207        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
15208        String nameList[] = new String[componentNames.size()];
15209        componentNames.toArray(nameList);
15210        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
15211        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
15212        extras.putInt(Intent.EXTRA_UID, packageUid);
15213        // If this is not reporting a change of the overall package, then only send it
15214        // to registered receivers.  We don't want to launch a swath of apps for every
15215        // little component state change.
15216        final int flags = !componentNames.contains(packageName)
15217                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
15218        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
15219                new int[] {UserHandle.getUserId(packageUid)});
15220    }
15221
15222    @Override
15223    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
15224        if (!sUserManager.exists(userId)) return;
15225        final int uid = Binder.getCallingUid();
15226        final int permission = mContext.checkCallingOrSelfPermission(
15227                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
15228        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
15229        enforceCrossUserPermission(uid, userId, true, true, "stop package");
15230        // writer
15231        synchronized (mPackages) {
15232            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
15233                    allowedByPermission, uid, userId)) {
15234                scheduleWritePackageRestrictionsLocked(userId);
15235            }
15236        }
15237    }
15238
15239    @Override
15240    public String getInstallerPackageName(String packageName) {
15241        // reader
15242        synchronized (mPackages) {
15243            return mSettings.getInstallerPackageNameLPr(packageName);
15244        }
15245    }
15246
15247    @Override
15248    public int getApplicationEnabledSetting(String packageName, int userId) {
15249        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15250        int uid = Binder.getCallingUid();
15251        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
15252        // reader
15253        synchronized (mPackages) {
15254            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
15255        }
15256    }
15257
15258    @Override
15259    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
15260        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
15261        int uid = Binder.getCallingUid();
15262        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
15263        // reader
15264        synchronized (mPackages) {
15265            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
15266        }
15267    }
15268
15269    @Override
15270    public void enterSafeMode() {
15271        enforceSystemOrRoot("Only the system can request entering safe mode");
15272
15273        if (!mSystemReady) {
15274            mSafeMode = true;
15275        }
15276    }
15277
15278    @Override
15279    public void systemReady() {
15280        mSystemReady = true;
15281
15282        // Read the compatibilty setting when the system is ready.
15283        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
15284                mContext.getContentResolver(),
15285                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
15286        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
15287        if (DEBUG_SETTINGS) {
15288            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
15289        }
15290
15291        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
15292
15293        synchronized (mPackages) {
15294            // Verify that all of the preferred activity components actually
15295            // exist.  It is possible for applications to be updated and at
15296            // that point remove a previously declared activity component that
15297            // had been set as a preferred activity.  We try to clean this up
15298            // the next time we encounter that preferred activity, but it is
15299            // possible for the user flow to never be able to return to that
15300            // situation so here we do a sanity check to make sure we haven't
15301            // left any junk around.
15302            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
15303            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15304                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15305                removed.clear();
15306                for (PreferredActivity pa : pir.filterSet()) {
15307                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
15308                        removed.add(pa);
15309                    }
15310                }
15311                if (removed.size() > 0) {
15312                    for (int r=0; r<removed.size(); r++) {
15313                        PreferredActivity pa = removed.get(r);
15314                        Slog.w(TAG, "Removing dangling preferred activity: "
15315                                + pa.mPref.mComponent);
15316                        pir.removeFilter(pa);
15317                    }
15318                    mSettings.writePackageRestrictionsLPr(
15319                            mSettings.mPreferredActivities.keyAt(i));
15320                }
15321            }
15322
15323            for (int userId : UserManagerService.getInstance().getUserIds()) {
15324                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
15325                    grantPermissionsUserIds = ArrayUtils.appendInt(
15326                            grantPermissionsUserIds, userId);
15327                }
15328            }
15329        }
15330        sUserManager.systemReady();
15331
15332        // If we upgraded grant all default permissions before kicking off.
15333        for (int userId : grantPermissionsUserIds) {
15334            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
15335        }
15336
15337        // Kick off any messages waiting for system ready
15338        if (mPostSystemReadyMessages != null) {
15339            for (Message msg : mPostSystemReadyMessages) {
15340                msg.sendToTarget();
15341            }
15342            mPostSystemReadyMessages = null;
15343        }
15344
15345        // Watch for external volumes that come and go over time
15346        final StorageManager storage = mContext.getSystemService(StorageManager.class);
15347        storage.registerListener(mStorageListener);
15348
15349        mInstallerService.systemReady();
15350        mPackageDexOptimizer.systemReady();
15351
15352        MountServiceInternal mountServiceInternal = LocalServices.getService(
15353                MountServiceInternal.class);
15354        mountServiceInternal.addExternalStoragePolicy(
15355                new MountServiceInternal.ExternalStorageMountPolicy() {
15356            @Override
15357            public int getMountMode(int uid, String packageName) {
15358                if (Process.isIsolated(uid)) {
15359                    return Zygote.MOUNT_EXTERNAL_NONE;
15360                }
15361                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
15362                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15363                }
15364                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15365                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
15366                }
15367                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
15368                    return Zygote.MOUNT_EXTERNAL_READ;
15369                }
15370                return Zygote.MOUNT_EXTERNAL_WRITE;
15371            }
15372
15373            @Override
15374            public boolean hasExternalStorage(int uid, String packageName) {
15375                return true;
15376            }
15377        });
15378    }
15379
15380    @Override
15381    public boolean isSafeMode() {
15382        return mSafeMode;
15383    }
15384
15385    @Override
15386    public boolean hasSystemUidErrors() {
15387        return mHasSystemUidErrors;
15388    }
15389
15390    static String arrayToString(int[] array) {
15391        StringBuffer buf = new StringBuffer(128);
15392        buf.append('[');
15393        if (array != null) {
15394            for (int i=0; i<array.length; i++) {
15395                if (i > 0) buf.append(", ");
15396                buf.append(array[i]);
15397            }
15398        }
15399        buf.append(']');
15400        return buf.toString();
15401    }
15402
15403    static class DumpState {
15404        public static final int DUMP_LIBS = 1 << 0;
15405        public static final int DUMP_FEATURES = 1 << 1;
15406        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
15407        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
15408        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
15409        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
15410        public static final int DUMP_PERMISSIONS = 1 << 6;
15411        public static final int DUMP_PACKAGES = 1 << 7;
15412        public static final int DUMP_SHARED_USERS = 1 << 8;
15413        public static final int DUMP_MESSAGES = 1 << 9;
15414        public static final int DUMP_PROVIDERS = 1 << 10;
15415        public static final int DUMP_VERIFIERS = 1 << 11;
15416        public static final int DUMP_PREFERRED = 1 << 12;
15417        public static final int DUMP_PREFERRED_XML = 1 << 13;
15418        public static final int DUMP_KEYSETS = 1 << 14;
15419        public static final int DUMP_VERSION = 1 << 15;
15420        public static final int DUMP_INSTALLS = 1 << 16;
15421        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
15422        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
15423
15424        public static final int OPTION_SHOW_FILTERS = 1 << 0;
15425
15426        private int mTypes;
15427
15428        private int mOptions;
15429
15430        private boolean mTitlePrinted;
15431
15432        private SharedUserSetting mSharedUser;
15433
15434        public boolean isDumping(int type) {
15435            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
15436                return true;
15437            }
15438
15439            return (mTypes & type) != 0;
15440        }
15441
15442        public void setDump(int type) {
15443            mTypes |= type;
15444        }
15445
15446        public boolean isOptionEnabled(int option) {
15447            return (mOptions & option) != 0;
15448        }
15449
15450        public void setOptionEnabled(int option) {
15451            mOptions |= option;
15452        }
15453
15454        public boolean onTitlePrinted() {
15455            final boolean printed = mTitlePrinted;
15456            mTitlePrinted = true;
15457            return printed;
15458        }
15459
15460        public boolean getTitlePrinted() {
15461            return mTitlePrinted;
15462        }
15463
15464        public void setTitlePrinted(boolean enabled) {
15465            mTitlePrinted = enabled;
15466        }
15467
15468        public SharedUserSetting getSharedUser() {
15469            return mSharedUser;
15470        }
15471
15472        public void setSharedUser(SharedUserSetting user) {
15473            mSharedUser = user;
15474        }
15475    }
15476
15477    @Override
15478    public void onShellCommand(FileDescriptor in, FileDescriptor out,
15479            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
15480        (new PackageManagerShellCommand(this)).exec(
15481                this, in, out, err, args, resultReceiver);
15482    }
15483
15484    @Override
15485    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
15486        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
15487                != PackageManager.PERMISSION_GRANTED) {
15488            pw.println("Permission Denial: can't dump ActivityManager from from pid="
15489                    + Binder.getCallingPid()
15490                    + ", uid=" + Binder.getCallingUid()
15491                    + " without permission "
15492                    + android.Manifest.permission.DUMP);
15493            return;
15494        }
15495
15496        DumpState dumpState = new DumpState();
15497        boolean fullPreferred = false;
15498        boolean checkin = false;
15499
15500        String packageName = null;
15501        ArraySet<String> permissionNames = null;
15502
15503        int opti = 0;
15504        while (opti < args.length) {
15505            String opt = args[opti];
15506            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
15507                break;
15508            }
15509            opti++;
15510
15511            if ("-a".equals(opt)) {
15512                // Right now we only know how to print all.
15513            } else if ("-h".equals(opt)) {
15514                pw.println("Package manager dump options:");
15515                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
15516                pw.println("    --checkin: dump for a checkin");
15517                pw.println("    -f: print details of intent filters");
15518                pw.println("    -h: print this help");
15519                pw.println("  cmd may be one of:");
15520                pw.println("    l[ibraries]: list known shared libraries");
15521                pw.println("    f[eatures]: list device features");
15522                pw.println("    k[eysets]: print known keysets");
15523                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
15524                pw.println("    perm[issions]: dump permissions");
15525                pw.println("    permission [name ...]: dump declaration and use of given permission");
15526                pw.println("    pref[erred]: print preferred package settings");
15527                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
15528                pw.println("    prov[iders]: dump content providers");
15529                pw.println("    p[ackages]: dump installed packages");
15530                pw.println("    s[hared-users]: dump shared user IDs");
15531                pw.println("    m[essages]: print collected runtime messages");
15532                pw.println("    v[erifiers]: print package verifier info");
15533                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
15534                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
15535                pw.println("    version: print database version info");
15536                pw.println("    write: write current settings now");
15537                pw.println("    installs: details about install sessions");
15538                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
15539                pw.println("    <package.name>: info about given package");
15540                return;
15541            } else if ("--checkin".equals(opt)) {
15542                checkin = true;
15543            } else if ("-f".equals(opt)) {
15544                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15545            } else {
15546                pw.println("Unknown argument: " + opt + "; use -h for help");
15547            }
15548        }
15549
15550        // Is the caller requesting to dump a particular piece of data?
15551        if (opti < args.length) {
15552            String cmd = args[opti];
15553            opti++;
15554            // Is this a package name?
15555            if ("android".equals(cmd) || cmd.contains(".")) {
15556                packageName = cmd;
15557                // When dumping a single package, we always dump all of its
15558                // filter information since the amount of data will be reasonable.
15559                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
15560            } else if ("check-permission".equals(cmd)) {
15561                if (opti >= args.length) {
15562                    pw.println("Error: check-permission missing permission argument");
15563                    return;
15564                }
15565                String perm = args[opti];
15566                opti++;
15567                if (opti >= args.length) {
15568                    pw.println("Error: check-permission missing package argument");
15569                    return;
15570                }
15571                String pkg = args[opti];
15572                opti++;
15573                int user = UserHandle.getUserId(Binder.getCallingUid());
15574                if (opti < args.length) {
15575                    try {
15576                        user = Integer.parseInt(args[opti]);
15577                    } catch (NumberFormatException e) {
15578                        pw.println("Error: check-permission user argument is not a number: "
15579                                + args[opti]);
15580                        return;
15581                    }
15582                }
15583                pw.println(checkPermission(perm, pkg, user));
15584                return;
15585            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
15586                dumpState.setDump(DumpState.DUMP_LIBS);
15587            } else if ("f".equals(cmd) || "features".equals(cmd)) {
15588                dumpState.setDump(DumpState.DUMP_FEATURES);
15589            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
15590                if (opti >= args.length) {
15591                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
15592                            | DumpState.DUMP_SERVICE_RESOLVERS
15593                            | DumpState.DUMP_RECEIVER_RESOLVERS
15594                            | DumpState.DUMP_CONTENT_RESOLVERS);
15595                } else {
15596                    while (opti < args.length) {
15597                        String name = args[opti];
15598                        if ("a".equals(name) || "activity".equals(name)) {
15599                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
15600                        } else if ("s".equals(name) || "service".equals(name)) {
15601                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
15602                        } else if ("r".equals(name) || "receiver".equals(name)) {
15603                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
15604                        } else if ("c".equals(name) || "content".equals(name)) {
15605                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
15606                        } else {
15607                            pw.println("Error: unknown resolver table type: " + name);
15608                            return;
15609                        }
15610                        opti++;
15611                    }
15612                }
15613            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
15614                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
15615            } else if ("permission".equals(cmd)) {
15616                if (opti >= args.length) {
15617                    pw.println("Error: permission requires permission name");
15618                    return;
15619                }
15620                permissionNames = new ArraySet<>();
15621                while (opti < args.length) {
15622                    permissionNames.add(args[opti]);
15623                    opti++;
15624                }
15625                dumpState.setDump(DumpState.DUMP_PERMISSIONS
15626                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
15627            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
15628                dumpState.setDump(DumpState.DUMP_PREFERRED);
15629            } else if ("preferred-xml".equals(cmd)) {
15630                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
15631                if (opti < args.length && "--full".equals(args[opti])) {
15632                    fullPreferred = true;
15633                    opti++;
15634                }
15635            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
15636                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
15637            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
15638                dumpState.setDump(DumpState.DUMP_PACKAGES);
15639            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
15640                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
15641            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
15642                dumpState.setDump(DumpState.DUMP_PROVIDERS);
15643            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
15644                dumpState.setDump(DumpState.DUMP_MESSAGES);
15645            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
15646                dumpState.setDump(DumpState.DUMP_VERIFIERS);
15647            } else if ("i".equals(cmd) || "ifv".equals(cmd)
15648                    || "intent-filter-verifiers".equals(cmd)) {
15649                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
15650            } else if ("version".equals(cmd)) {
15651                dumpState.setDump(DumpState.DUMP_VERSION);
15652            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
15653                dumpState.setDump(DumpState.DUMP_KEYSETS);
15654            } else if ("installs".equals(cmd)) {
15655                dumpState.setDump(DumpState.DUMP_INSTALLS);
15656            } else if ("write".equals(cmd)) {
15657                synchronized (mPackages) {
15658                    mSettings.writeLPr();
15659                    pw.println("Settings written.");
15660                    return;
15661                }
15662            }
15663        }
15664
15665        if (checkin) {
15666            pw.println("vers,1");
15667        }
15668
15669        // reader
15670        synchronized (mPackages) {
15671            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
15672                if (!checkin) {
15673                    if (dumpState.onTitlePrinted())
15674                        pw.println();
15675                    pw.println("Database versions:");
15676                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
15677                }
15678            }
15679
15680            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
15681                if (!checkin) {
15682                    if (dumpState.onTitlePrinted())
15683                        pw.println();
15684                    pw.println("Verifiers:");
15685                    pw.print("  Required: ");
15686                    pw.print(mRequiredVerifierPackage);
15687                    pw.print(" (uid=");
15688                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15689                            UserHandle.USER_SYSTEM));
15690                    pw.println(")");
15691                } else if (mRequiredVerifierPackage != null) {
15692                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
15693                    pw.print(",");
15694                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15695                            UserHandle.USER_SYSTEM));
15696                }
15697            }
15698
15699            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
15700                    packageName == null) {
15701                if (mIntentFilterVerifierComponent != null) {
15702                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
15703                    if (!checkin) {
15704                        if (dumpState.onTitlePrinted())
15705                            pw.println();
15706                        pw.println("Intent Filter Verifier:");
15707                        pw.print("  Using: ");
15708                        pw.print(verifierPackageName);
15709                        pw.print(" (uid=");
15710                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15711                                UserHandle.USER_SYSTEM));
15712                        pw.println(")");
15713                    } else if (verifierPackageName != null) {
15714                        pw.print("ifv,"); pw.print(verifierPackageName);
15715                        pw.print(",");
15716                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
15717                                UserHandle.USER_SYSTEM));
15718                    }
15719                } else {
15720                    pw.println();
15721                    pw.println("No Intent Filter Verifier available!");
15722                }
15723            }
15724
15725            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
15726                boolean printedHeader = false;
15727                final Iterator<String> it = mSharedLibraries.keySet().iterator();
15728                while (it.hasNext()) {
15729                    String name = it.next();
15730                    SharedLibraryEntry ent = mSharedLibraries.get(name);
15731                    if (!checkin) {
15732                        if (!printedHeader) {
15733                            if (dumpState.onTitlePrinted())
15734                                pw.println();
15735                            pw.println("Libraries:");
15736                            printedHeader = true;
15737                        }
15738                        pw.print("  ");
15739                    } else {
15740                        pw.print("lib,");
15741                    }
15742                    pw.print(name);
15743                    if (!checkin) {
15744                        pw.print(" -> ");
15745                    }
15746                    if (ent.path != null) {
15747                        if (!checkin) {
15748                            pw.print("(jar) ");
15749                            pw.print(ent.path);
15750                        } else {
15751                            pw.print(",jar,");
15752                            pw.print(ent.path);
15753                        }
15754                    } else {
15755                        if (!checkin) {
15756                            pw.print("(apk) ");
15757                            pw.print(ent.apk);
15758                        } else {
15759                            pw.print(",apk,");
15760                            pw.print(ent.apk);
15761                        }
15762                    }
15763                    pw.println();
15764                }
15765            }
15766
15767            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
15768                if (dumpState.onTitlePrinted())
15769                    pw.println();
15770                if (!checkin) {
15771                    pw.println("Features:");
15772                }
15773                Iterator<String> it = mAvailableFeatures.keySet().iterator();
15774                while (it.hasNext()) {
15775                    String name = it.next();
15776                    if (!checkin) {
15777                        pw.print("  ");
15778                    } else {
15779                        pw.print("feat,");
15780                    }
15781                    pw.println(name);
15782                }
15783            }
15784
15785            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
15786                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
15787                        : "Activity Resolver Table:", "  ", packageName,
15788                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15789                    dumpState.setTitlePrinted(true);
15790                }
15791            }
15792            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
15793                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
15794                        : "Receiver Resolver Table:", "  ", packageName,
15795                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15796                    dumpState.setTitlePrinted(true);
15797                }
15798            }
15799            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
15800                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
15801                        : "Service Resolver Table:", "  ", packageName,
15802                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15803                    dumpState.setTitlePrinted(true);
15804                }
15805            }
15806            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
15807                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
15808                        : "Provider Resolver Table:", "  ", packageName,
15809                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
15810                    dumpState.setTitlePrinted(true);
15811                }
15812            }
15813
15814            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
15815                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15816                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15817                    int user = mSettings.mPreferredActivities.keyAt(i);
15818                    if (pir.dump(pw,
15819                            dumpState.getTitlePrinted()
15820                                ? "\nPreferred Activities User " + user + ":"
15821                                : "Preferred Activities User " + user + ":", "  ",
15822                            packageName, true, false)) {
15823                        dumpState.setTitlePrinted(true);
15824                    }
15825                }
15826            }
15827
15828            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
15829                pw.flush();
15830                FileOutputStream fout = new FileOutputStream(fd);
15831                BufferedOutputStream str = new BufferedOutputStream(fout);
15832                XmlSerializer serializer = new FastXmlSerializer();
15833                try {
15834                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
15835                    serializer.startDocument(null, true);
15836                    serializer.setFeature(
15837                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
15838                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
15839                    serializer.endDocument();
15840                    serializer.flush();
15841                } catch (IllegalArgumentException e) {
15842                    pw.println("Failed writing: " + e);
15843                } catch (IllegalStateException e) {
15844                    pw.println("Failed writing: " + e);
15845                } catch (IOException e) {
15846                    pw.println("Failed writing: " + e);
15847                }
15848            }
15849
15850            if (!checkin
15851                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
15852                    && packageName == null) {
15853                pw.println();
15854                int count = mSettings.mPackages.size();
15855                if (count == 0) {
15856                    pw.println("No applications!");
15857                    pw.println();
15858                } else {
15859                    final String prefix = "  ";
15860                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
15861                    if (allPackageSettings.size() == 0) {
15862                        pw.println("No domain preferred apps!");
15863                        pw.println();
15864                    } else {
15865                        pw.println("App verification status:");
15866                        pw.println();
15867                        count = 0;
15868                        for (PackageSetting ps : allPackageSettings) {
15869                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
15870                            if (ivi == null || ivi.getPackageName() == null) continue;
15871                            pw.println(prefix + "Package: " + ivi.getPackageName());
15872                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
15873                            pw.println(prefix + "Status:  " + ivi.getStatusString());
15874                            pw.println();
15875                            count++;
15876                        }
15877                        if (count == 0) {
15878                            pw.println(prefix + "No app verification established.");
15879                            pw.println();
15880                        }
15881                        for (int userId : sUserManager.getUserIds()) {
15882                            pw.println("App linkages for user " + userId + ":");
15883                            pw.println();
15884                            count = 0;
15885                            for (PackageSetting ps : allPackageSettings) {
15886                                final long status = ps.getDomainVerificationStatusForUser(userId);
15887                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
15888                                    continue;
15889                                }
15890                                pw.println(prefix + "Package: " + ps.name);
15891                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
15892                                String statusStr = IntentFilterVerificationInfo.
15893                                        getStatusStringFromValue(status);
15894                                pw.println(prefix + "Status:  " + statusStr);
15895                                pw.println();
15896                                count++;
15897                            }
15898                            if (count == 0) {
15899                                pw.println(prefix + "No configured app linkages.");
15900                                pw.println();
15901                            }
15902                        }
15903                    }
15904                }
15905            }
15906
15907            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
15908                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
15909                if (packageName == null && permissionNames == null) {
15910                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
15911                        if (iperm == 0) {
15912                            if (dumpState.onTitlePrinted())
15913                                pw.println();
15914                            pw.println("AppOp Permissions:");
15915                        }
15916                        pw.print("  AppOp Permission ");
15917                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
15918                        pw.println(":");
15919                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
15920                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
15921                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
15922                        }
15923                    }
15924                }
15925            }
15926
15927            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
15928                boolean printedSomething = false;
15929                for (PackageParser.Provider p : mProviders.mProviders.values()) {
15930                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15931                        continue;
15932                    }
15933                    if (!printedSomething) {
15934                        if (dumpState.onTitlePrinted())
15935                            pw.println();
15936                        pw.println("Registered ContentProviders:");
15937                        printedSomething = true;
15938                    }
15939                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
15940                    pw.print("    "); pw.println(p.toString());
15941                }
15942                printedSomething = false;
15943                for (Map.Entry<String, PackageParser.Provider> entry :
15944                        mProvidersByAuthority.entrySet()) {
15945                    PackageParser.Provider p = entry.getValue();
15946                    if (packageName != null && !packageName.equals(p.info.packageName)) {
15947                        continue;
15948                    }
15949                    if (!printedSomething) {
15950                        if (dumpState.onTitlePrinted())
15951                            pw.println();
15952                        pw.println("ContentProvider Authorities:");
15953                        printedSomething = true;
15954                    }
15955                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
15956                    pw.print("    "); pw.println(p.toString());
15957                    if (p.info != null && p.info.applicationInfo != null) {
15958                        final String appInfo = p.info.applicationInfo.toString();
15959                        pw.print("      applicationInfo="); pw.println(appInfo);
15960                    }
15961                }
15962            }
15963
15964            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
15965                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
15966            }
15967
15968            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
15969                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
15970            }
15971
15972            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
15973                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
15974            }
15975
15976            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
15977                // XXX should handle packageName != null by dumping only install data that
15978                // the given package is involved with.
15979                if (dumpState.onTitlePrinted()) pw.println();
15980                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
15981            }
15982
15983            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
15984                if (dumpState.onTitlePrinted()) pw.println();
15985                mSettings.dumpReadMessagesLPr(pw, dumpState);
15986
15987                pw.println();
15988                pw.println("Package warning messages:");
15989                BufferedReader in = null;
15990                String line = null;
15991                try {
15992                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
15993                    while ((line = in.readLine()) != null) {
15994                        if (line.contains("ignored: updated version")) continue;
15995                        pw.println(line);
15996                    }
15997                } catch (IOException ignored) {
15998                } finally {
15999                    IoUtils.closeQuietly(in);
16000                }
16001            }
16002
16003            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
16004                BufferedReader in = null;
16005                String line = null;
16006                try {
16007                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
16008                    while ((line = in.readLine()) != null) {
16009                        if (line.contains("ignored: updated version")) continue;
16010                        pw.print("msg,");
16011                        pw.println(line);
16012                    }
16013                } catch (IOException ignored) {
16014                } finally {
16015                    IoUtils.closeQuietly(in);
16016                }
16017            }
16018        }
16019    }
16020
16021    private String dumpDomainString(String packageName) {
16022        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName);
16023        List<IntentFilter> filters = getAllIntentFilters(packageName);
16024
16025        ArraySet<String> result = new ArraySet<>();
16026        if (iviList.size() > 0) {
16027            for (IntentFilterVerificationInfo ivi : iviList) {
16028                for (String host : ivi.getDomains()) {
16029                    result.add(host);
16030                }
16031            }
16032        }
16033        if (filters != null && filters.size() > 0) {
16034            for (IntentFilter filter : filters) {
16035                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
16036                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
16037                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
16038                    result.addAll(filter.getHostsList());
16039                }
16040            }
16041        }
16042
16043        StringBuilder sb = new StringBuilder(result.size() * 16);
16044        for (String domain : result) {
16045            if (sb.length() > 0) sb.append(" ");
16046            sb.append(domain);
16047        }
16048        return sb.toString();
16049    }
16050
16051    // ------- apps on sdcard specific code -------
16052    static final boolean DEBUG_SD_INSTALL = false;
16053
16054    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
16055
16056    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
16057
16058    private boolean mMediaMounted = false;
16059
16060    static String getEncryptKey() {
16061        try {
16062            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
16063                    SD_ENCRYPTION_KEYSTORE_NAME);
16064            if (sdEncKey == null) {
16065                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
16066                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
16067                if (sdEncKey == null) {
16068                    Slog.e(TAG, "Failed to create encryption keys");
16069                    return null;
16070                }
16071            }
16072            return sdEncKey;
16073        } catch (NoSuchAlgorithmException nsae) {
16074            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
16075            return null;
16076        } catch (IOException ioe) {
16077            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
16078            return null;
16079        }
16080    }
16081
16082    /*
16083     * Update media status on PackageManager.
16084     */
16085    @Override
16086    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
16087        int callingUid = Binder.getCallingUid();
16088        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
16089            throw new SecurityException("Media status can only be updated by the system");
16090        }
16091        // reader; this apparently protects mMediaMounted, but should probably
16092        // be a different lock in that case.
16093        synchronized (mPackages) {
16094            Log.i(TAG, "Updating external media status from "
16095                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
16096                    + (mediaStatus ? "mounted" : "unmounted"));
16097            if (DEBUG_SD_INSTALL)
16098                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
16099                        + ", mMediaMounted=" + mMediaMounted);
16100            if (mediaStatus == mMediaMounted) {
16101                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
16102                        : 0, -1);
16103                mHandler.sendMessage(msg);
16104                return;
16105            }
16106            mMediaMounted = mediaStatus;
16107        }
16108        // Queue up an async operation since the package installation may take a
16109        // little while.
16110        mHandler.post(new Runnable() {
16111            public void run() {
16112                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
16113            }
16114        });
16115    }
16116
16117    /**
16118     * Called by MountService when the initial ASECs to scan are available.
16119     * Should block until all the ASEC containers are finished being scanned.
16120     */
16121    public void scanAvailableAsecs() {
16122        updateExternalMediaStatusInner(true, false, false);
16123        if (mShouldRestoreconData) {
16124            SELinuxMMAC.setRestoreconDone();
16125            mShouldRestoreconData = false;
16126        }
16127    }
16128
16129    /*
16130     * Collect information of applications on external media, map them against
16131     * existing containers and update information based on current mount status.
16132     * Please note that we always have to report status if reportStatus has been
16133     * set to true especially when unloading packages.
16134     */
16135    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
16136            boolean externalStorage) {
16137        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
16138        int[] uidArr = EmptyArray.INT;
16139
16140        final String[] list = PackageHelper.getSecureContainerList();
16141        if (ArrayUtils.isEmpty(list)) {
16142            Log.i(TAG, "No secure containers found");
16143        } else {
16144            // Process list of secure containers and categorize them
16145            // as active or stale based on their package internal state.
16146
16147            // reader
16148            synchronized (mPackages) {
16149                for (String cid : list) {
16150                    // Leave stages untouched for now; installer service owns them
16151                    if (PackageInstallerService.isStageName(cid)) continue;
16152
16153                    if (DEBUG_SD_INSTALL)
16154                        Log.i(TAG, "Processing container " + cid);
16155                    String pkgName = getAsecPackageName(cid);
16156                    if (pkgName == null) {
16157                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
16158                        continue;
16159                    }
16160                    if (DEBUG_SD_INSTALL)
16161                        Log.i(TAG, "Looking for pkg : " + pkgName);
16162
16163                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
16164                    if (ps == null) {
16165                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
16166                        continue;
16167                    }
16168
16169                    /*
16170                     * Skip packages that are not external if we're unmounting
16171                     * external storage.
16172                     */
16173                    if (externalStorage && !isMounted && !isExternal(ps)) {
16174                        continue;
16175                    }
16176
16177                    final AsecInstallArgs args = new AsecInstallArgs(cid,
16178                            getAppDexInstructionSets(ps), ps.isForwardLocked());
16179                    // The package status is changed only if the code path
16180                    // matches between settings and the container id.
16181                    if (ps.codePathString != null
16182                            && ps.codePathString.startsWith(args.getCodePath())) {
16183                        if (DEBUG_SD_INSTALL) {
16184                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
16185                                    + " at code path: " + ps.codePathString);
16186                        }
16187
16188                        // We do have a valid package installed on sdcard
16189                        processCids.put(args, ps.codePathString);
16190                        final int uid = ps.appId;
16191                        if (uid != -1) {
16192                            uidArr = ArrayUtils.appendInt(uidArr, uid);
16193                        }
16194                    } else {
16195                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
16196                                + ps.codePathString);
16197                    }
16198                }
16199            }
16200
16201            Arrays.sort(uidArr);
16202        }
16203
16204        // Process packages with valid entries.
16205        if (isMounted) {
16206            if (DEBUG_SD_INSTALL)
16207                Log.i(TAG, "Loading packages");
16208            loadMediaPackages(processCids, uidArr, externalStorage);
16209            startCleaningPackages();
16210            mInstallerService.onSecureContainersAvailable();
16211        } else {
16212            if (DEBUG_SD_INSTALL)
16213                Log.i(TAG, "Unloading packages");
16214            unloadMediaPackages(processCids, uidArr, reportStatus);
16215        }
16216    }
16217
16218    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16219            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
16220        final int size = infos.size();
16221        final String[] packageNames = new String[size];
16222        final int[] packageUids = new int[size];
16223        for (int i = 0; i < size; i++) {
16224            final ApplicationInfo info = infos.get(i);
16225            packageNames[i] = info.packageName;
16226            packageUids[i] = info.uid;
16227        }
16228        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
16229                finishedReceiver);
16230    }
16231
16232    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16233            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16234        sendResourcesChangedBroadcast(mediaStatus, replacing,
16235                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
16236    }
16237
16238    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
16239            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
16240        int size = pkgList.length;
16241        if (size > 0) {
16242            // Send broadcasts here
16243            Bundle extras = new Bundle();
16244            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
16245            if (uidArr != null) {
16246                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
16247            }
16248            if (replacing) {
16249                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
16250            }
16251            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
16252                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
16253            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
16254        }
16255    }
16256
16257   /*
16258     * Look at potentially valid container ids from processCids If package
16259     * information doesn't match the one on record or package scanning fails,
16260     * the cid is added to list of removeCids. We currently don't delete stale
16261     * containers.
16262     */
16263    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
16264            boolean externalStorage) {
16265        ArrayList<String> pkgList = new ArrayList<String>();
16266        Set<AsecInstallArgs> keys = processCids.keySet();
16267
16268        for (AsecInstallArgs args : keys) {
16269            String codePath = processCids.get(args);
16270            if (DEBUG_SD_INSTALL)
16271                Log.i(TAG, "Loading container : " + args.cid);
16272            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16273            try {
16274                // Make sure there are no container errors first.
16275                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
16276                    Slog.e(TAG, "Failed to mount cid : " + args.cid
16277                            + " when installing from sdcard");
16278                    continue;
16279                }
16280                // Check code path here.
16281                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
16282                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
16283                            + " does not match one in settings " + codePath);
16284                    continue;
16285                }
16286                // Parse package
16287                int parseFlags = mDefParseFlags;
16288                if (args.isExternalAsec()) {
16289                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
16290                }
16291                if (args.isFwdLocked()) {
16292                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
16293                }
16294
16295                synchronized (mInstallLock) {
16296                    PackageParser.Package pkg = null;
16297                    try {
16298                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
16299                    } catch (PackageManagerException e) {
16300                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
16301                    }
16302                    // Scan the package
16303                    if (pkg != null) {
16304                        /*
16305                         * TODO why is the lock being held? doPostInstall is
16306                         * called in other places without the lock. This needs
16307                         * to be straightened out.
16308                         */
16309                        // writer
16310                        synchronized (mPackages) {
16311                            retCode = PackageManager.INSTALL_SUCCEEDED;
16312                            pkgList.add(pkg.packageName);
16313                            // Post process args
16314                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
16315                                    pkg.applicationInfo.uid);
16316                        }
16317                    } else {
16318                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
16319                    }
16320                }
16321
16322            } finally {
16323                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
16324                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
16325                }
16326            }
16327        }
16328        // writer
16329        synchronized (mPackages) {
16330            // If the platform SDK has changed since the last time we booted,
16331            // we need to re-grant app permission to catch any new ones that
16332            // appear. This is really a hack, and means that apps can in some
16333            // cases get permissions that the user didn't initially explicitly
16334            // allow... it would be nice to have some better way to handle
16335            // this situation.
16336            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
16337                    : mSettings.getInternalVersion();
16338            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
16339                    : StorageManager.UUID_PRIVATE_INTERNAL;
16340
16341            int updateFlags = UPDATE_PERMISSIONS_ALL;
16342            if (ver.sdkVersion != mSdkVersion) {
16343                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16344                        + mSdkVersion + "; regranting permissions for external");
16345                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16346            }
16347            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
16348
16349            // Yay, everything is now upgraded
16350            ver.forceCurrent();
16351
16352            // can downgrade to reader
16353            // Persist settings
16354            mSettings.writeLPr();
16355        }
16356        // Send a broadcast to let everyone know we are done processing
16357        if (pkgList.size() > 0) {
16358            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
16359        }
16360    }
16361
16362   /*
16363     * Utility method to unload a list of specified containers
16364     */
16365    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
16366        // Just unmount all valid containers.
16367        for (AsecInstallArgs arg : cidArgs) {
16368            synchronized (mInstallLock) {
16369                arg.doPostDeleteLI(false);
16370           }
16371       }
16372   }
16373
16374    /*
16375     * Unload packages mounted on external media. This involves deleting package
16376     * data from internal structures, sending broadcasts about diabled packages,
16377     * gc'ing to free up references, unmounting all secure containers
16378     * corresponding to packages on external media, and posting a
16379     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
16380     * that we always have to post this message if status has been requested no
16381     * matter what.
16382     */
16383    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
16384            final boolean reportStatus) {
16385        if (DEBUG_SD_INSTALL)
16386            Log.i(TAG, "unloading media packages");
16387        ArrayList<String> pkgList = new ArrayList<String>();
16388        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
16389        final Set<AsecInstallArgs> keys = processCids.keySet();
16390        for (AsecInstallArgs args : keys) {
16391            String pkgName = args.getPackageName();
16392            if (DEBUG_SD_INSTALL)
16393                Log.i(TAG, "Trying to unload pkg : " + pkgName);
16394            // Delete package internally
16395            PackageRemovedInfo outInfo = new PackageRemovedInfo();
16396            synchronized (mInstallLock) {
16397                boolean res = deletePackageLI(pkgName, null, false, null, null,
16398                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
16399                if (res) {
16400                    pkgList.add(pkgName);
16401                } else {
16402                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
16403                    failedList.add(args);
16404                }
16405            }
16406        }
16407
16408        // reader
16409        synchronized (mPackages) {
16410            // We didn't update the settings after removing each package;
16411            // write them now for all packages.
16412            mSettings.writeLPr();
16413        }
16414
16415        // We have to absolutely send UPDATED_MEDIA_STATUS only
16416        // after confirming that all the receivers processed the ordered
16417        // broadcast when packages get disabled, force a gc to clean things up.
16418        // and unload all the containers.
16419        if (pkgList.size() > 0) {
16420            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
16421                    new IIntentReceiver.Stub() {
16422                public void performReceive(Intent intent, int resultCode, String data,
16423                        Bundle extras, boolean ordered, boolean sticky,
16424                        int sendingUser) throws RemoteException {
16425                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
16426                            reportStatus ? 1 : 0, 1, keys);
16427                    mHandler.sendMessage(msg);
16428                }
16429            });
16430        } else {
16431            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
16432                    keys);
16433            mHandler.sendMessage(msg);
16434        }
16435    }
16436
16437    private void loadPrivatePackages(final VolumeInfo vol) {
16438        mHandler.post(new Runnable() {
16439            @Override
16440            public void run() {
16441                loadPrivatePackagesInner(vol);
16442            }
16443        });
16444    }
16445
16446    private void loadPrivatePackagesInner(VolumeInfo vol) {
16447        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
16448        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
16449
16450        final VersionInfo ver;
16451        final List<PackageSetting> packages;
16452        synchronized (mPackages) {
16453            ver = mSettings.findOrCreateVersion(vol.fsUuid);
16454            packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16455        }
16456
16457        for (PackageSetting ps : packages) {
16458            synchronized (mInstallLock) {
16459                final PackageParser.Package pkg;
16460                try {
16461                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
16462                    loaded.add(pkg.applicationInfo);
16463                } catch (PackageManagerException e) {
16464                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
16465                }
16466
16467                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
16468                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
16469                }
16470            }
16471        }
16472
16473        synchronized (mPackages) {
16474            int updateFlags = UPDATE_PERMISSIONS_ALL;
16475            if (ver.sdkVersion != mSdkVersion) {
16476                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
16477                        + mSdkVersion + "; regranting permissions for " + vol.fsUuid);
16478                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
16479            }
16480            updatePermissionsLPw(null, null, vol.fsUuid, updateFlags);
16481
16482            // Yay, everything is now upgraded
16483            ver.forceCurrent();
16484
16485            mSettings.writeLPr();
16486        }
16487
16488        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
16489        sendResourcesChangedBroadcast(true, false, loaded, null);
16490    }
16491
16492    private void unloadPrivatePackages(final VolumeInfo vol) {
16493        mHandler.post(new Runnable() {
16494            @Override
16495            public void run() {
16496                unloadPrivatePackagesInner(vol);
16497            }
16498        });
16499    }
16500
16501    private void unloadPrivatePackagesInner(VolumeInfo vol) {
16502        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
16503        synchronized (mInstallLock) {
16504        synchronized (mPackages) {
16505            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
16506            for (PackageSetting ps : packages) {
16507                if (ps.pkg == null) continue;
16508
16509                final ApplicationInfo info = ps.pkg.applicationInfo;
16510                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
16511                if (deletePackageLI(ps.name, null, false, null, null,
16512                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
16513                    unloaded.add(info);
16514                } else {
16515                    Slog.w(TAG, "Failed to unload " + ps.codePath);
16516                }
16517            }
16518
16519            mSettings.writeLPr();
16520        }
16521        }
16522
16523        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
16524        sendResourcesChangedBroadcast(false, false, unloaded, null);
16525    }
16526
16527    /**
16528     * Examine all users present on given mounted volume, and destroy data
16529     * belonging to users that are no longer valid, or whose user ID has been
16530     * recycled.
16531     */
16532    private void reconcileUsers(String volumeUuid) {
16533        final File[] files = FileUtils
16534                .listFilesOrEmpty(Environment.getDataUserDirectory(volumeUuid));
16535        for (File file : files) {
16536            if (!file.isDirectory()) continue;
16537
16538            final int userId;
16539            final UserInfo info;
16540            try {
16541                userId = Integer.parseInt(file.getName());
16542                info = sUserManager.getUserInfo(userId);
16543            } catch (NumberFormatException e) {
16544                Slog.w(TAG, "Invalid user directory " + file);
16545                continue;
16546            }
16547
16548            boolean destroyUser = false;
16549            if (info == null) {
16550                logCriticalInfo(Log.WARN, "Destroying user directory " + file
16551                        + " because no matching user was found");
16552                destroyUser = true;
16553            } else {
16554                try {
16555                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
16556                } catch (IOException e) {
16557                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
16558                            + " because we failed to enforce serial number: " + e);
16559                    destroyUser = true;
16560                }
16561            }
16562
16563            if (destroyUser) {
16564                synchronized (mInstallLock) {
16565                    mInstaller.removeUserDataDirs(volumeUuid, userId);
16566                }
16567            }
16568        }
16569
16570        final StorageManager sm = mContext.getSystemService(StorageManager.class);
16571        final UserManager um = mContext.getSystemService(UserManager.class);
16572        for (UserInfo user : um.getUsers()) {
16573            final File userDir = Environment.getDataUserDirectory(volumeUuid, user.id);
16574            if (userDir.exists()) continue;
16575
16576            try {
16577                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, user.isEphemeral());
16578                UserManagerService.enforceSerialNumber(userDir, user.serialNumber);
16579            } catch (IOException e) {
16580                Log.wtf(TAG, "Failed to create user directory on " + volumeUuid, e);
16581            }
16582        }
16583    }
16584
16585    /**
16586     * Examine all apps present on given mounted volume, and destroy apps that
16587     * aren't expected, either due to uninstallation or reinstallation on
16588     * another volume.
16589     */
16590    private void reconcileApps(String volumeUuid) {
16591        final File[] files = FileUtils
16592                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
16593        for (File file : files) {
16594            final boolean isPackage = (isApkFile(file) || file.isDirectory())
16595                    && !PackageInstallerService.isStageName(file.getName());
16596            if (!isPackage) {
16597                // Ignore entries which are not packages
16598                continue;
16599            }
16600
16601            boolean destroyApp = false;
16602            String packageName = null;
16603            try {
16604                final PackageLite pkg = PackageParser.parsePackageLite(file,
16605                        PackageParser.PARSE_MUST_BE_APK);
16606                packageName = pkg.packageName;
16607
16608                synchronized (mPackages) {
16609                    final PackageSetting ps = mSettings.mPackages.get(packageName);
16610                    if (ps == null) {
16611                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on + "
16612                                + volumeUuid + " because we found no install record");
16613                        destroyApp = true;
16614                    } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
16615                        logCriticalInfo(Log.WARN, "Destroying " + packageName + " on "
16616                                + volumeUuid + " because we expected it on " + ps.volumeUuid);
16617                        destroyApp = true;
16618                    }
16619                }
16620
16621            } catch (PackageParserException e) {
16622                logCriticalInfo(Log.WARN, "Destroying " + file + " due to parse failure: " + e);
16623                destroyApp = true;
16624            }
16625
16626            if (destroyApp) {
16627                synchronized (mInstallLock) {
16628                    if (packageName != null) {
16629                        removeDataDirsLI(volumeUuid, packageName);
16630                    }
16631                    if (file.isDirectory()) {
16632                        mInstaller.rmPackageDir(file.getAbsolutePath());
16633                    } else {
16634                        file.delete();
16635                    }
16636                }
16637            }
16638        }
16639    }
16640
16641    private void unfreezePackage(String packageName) {
16642        synchronized (mPackages) {
16643            final PackageSetting ps = mSettings.mPackages.get(packageName);
16644            if (ps != null) {
16645                ps.frozen = false;
16646            }
16647        }
16648    }
16649
16650    @Override
16651    public int movePackage(final String packageName, final String volumeUuid) {
16652        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16653
16654        final int moveId = mNextMoveId.getAndIncrement();
16655        mHandler.post(new Runnable() {
16656            @Override
16657            public void run() {
16658                try {
16659                    movePackageInternal(packageName, volumeUuid, moveId);
16660                } catch (PackageManagerException e) {
16661                    Slog.w(TAG, "Failed to move " + packageName, e);
16662                    mMoveCallbacks.notifyStatusChanged(moveId,
16663                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16664                }
16665            }
16666        });
16667        return moveId;
16668    }
16669
16670    private void movePackageInternal(final String packageName, final String volumeUuid,
16671            final int moveId) throws PackageManagerException {
16672        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
16673        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16674        final PackageManager pm = mContext.getPackageManager();
16675
16676        final boolean currentAsec;
16677        final String currentVolumeUuid;
16678        final File codeFile;
16679        final String installerPackageName;
16680        final String packageAbiOverride;
16681        final int appId;
16682        final String seinfo;
16683        final String label;
16684
16685        // reader
16686        synchronized (mPackages) {
16687            final PackageParser.Package pkg = mPackages.get(packageName);
16688            final PackageSetting ps = mSettings.mPackages.get(packageName);
16689            if (pkg == null || ps == null) {
16690                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
16691            }
16692
16693            if (pkg.applicationInfo.isSystemApp()) {
16694                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
16695                        "Cannot move system application");
16696            }
16697
16698            if (pkg.applicationInfo.isExternalAsec()) {
16699                currentAsec = true;
16700                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
16701            } else if (pkg.applicationInfo.isForwardLocked()) {
16702                currentAsec = true;
16703                currentVolumeUuid = "forward_locked";
16704            } else {
16705                currentAsec = false;
16706                currentVolumeUuid = ps.volumeUuid;
16707
16708                final File probe = new File(pkg.codePath);
16709                final File probeOat = new File(probe, "oat");
16710                if (!probe.isDirectory() || !probeOat.isDirectory()) {
16711                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16712                            "Move only supported for modern cluster style installs");
16713                }
16714            }
16715
16716            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
16717                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16718                        "Package already moved to " + volumeUuid);
16719            }
16720
16721            if (ps.frozen) {
16722                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
16723                        "Failed to move already frozen package");
16724            }
16725            ps.frozen = true;
16726
16727            codeFile = new File(pkg.codePath);
16728            installerPackageName = ps.installerPackageName;
16729            packageAbiOverride = ps.cpuAbiOverrideString;
16730            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
16731            seinfo = pkg.applicationInfo.seinfo;
16732            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
16733        }
16734
16735        // Now that we're guarded by frozen state, kill app during move
16736        final long token = Binder.clearCallingIdentity();
16737        try {
16738            killApplication(packageName, appId, "move pkg");
16739        } finally {
16740            Binder.restoreCallingIdentity(token);
16741        }
16742
16743        final Bundle extras = new Bundle();
16744        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
16745        extras.putString(Intent.EXTRA_TITLE, label);
16746        mMoveCallbacks.notifyCreated(moveId, extras);
16747
16748        int installFlags;
16749        final boolean moveCompleteApp;
16750        final File measurePath;
16751
16752        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
16753            installFlags = INSTALL_INTERNAL;
16754            moveCompleteApp = !currentAsec;
16755            measurePath = Environment.getDataAppDirectory(volumeUuid);
16756        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
16757            installFlags = INSTALL_EXTERNAL;
16758            moveCompleteApp = false;
16759            measurePath = storage.getPrimaryPhysicalVolume().getPath();
16760        } else {
16761            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
16762            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
16763                    || !volume.isMountedWritable()) {
16764                unfreezePackage(packageName);
16765                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16766                        "Move location not mounted private volume");
16767            }
16768
16769            Preconditions.checkState(!currentAsec);
16770
16771            installFlags = INSTALL_INTERNAL;
16772            moveCompleteApp = true;
16773            measurePath = Environment.getDataAppDirectory(volumeUuid);
16774        }
16775
16776        final PackageStats stats = new PackageStats(null, -1);
16777        synchronized (mInstaller) {
16778            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
16779                unfreezePackage(packageName);
16780                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16781                        "Failed to measure package size");
16782            }
16783        }
16784
16785        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
16786                + stats.dataSize);
16787
16788        final long startFreeBytes = measurePath.getFreeSpace();
16789        final long sizeBytes;
16790        if (moveCompleteApp) {
16791            sizeBytes = stats.codeSize + stats.dataSize;
16792        } else {
16793            sizeBytes = stats.codeSize;
16794        }
16795
16796        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
16797            unfreezePackage(packageName);
16798            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
16799                    "Not enough free space to move");
16800        }
16801
16802        mMoveCallbacks.notifyStatusChanged(moveId, 10);
16803
16804        final CountDownLatch installedLatch = new CountDownLatch(1);
16805        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
16806            @Override
16807            public void onUserActionRequired(Intent intent) throws RemoteException {
16808                throw new IllegalStateException();
16809            }
16810
16811            @Override
16812            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
16813                    Bundle extras) throws RemoteException {
16814                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
16815                        + PackageManager.installStatusToString(returnCode, msg));
16816
16817                installedLatch.countDown();
16818
16819                // Regardless of success or failure of the move operation,
16820                // always unfreeze the package
16821                unfreezePackage(packageName);
16822
16823                final int status = PackageManager.installStatusToPublicStatus(returnCode);
16824                switch (status) {
16825                    case PackageInstaller.STATUS_SUCCESS:
16826                        mMoveCallbacks.notifyStatusChanged(moveId,
16827                                PackageManager.MOVE_SUCCEEDED);
16828                        break;
16829                    case PackageInstaller.STATUS_FAILURE_STORAGE:
16830                        mMoveCallbacks.notifyStatusChanged(moveId,
16831                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
16832                        break;
16833                    default:
16834                        mMoveCallbacks.notifyStatusChanged(moveId,
16835                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
16836                        break;
16837                }
16838            }
16839        };
16840
16841        final MoveInfo move;
16842        if (moveCompleteApp) {
16843            // Kick off a thread to report progress estimates
16844            new Thread() {
16845                @Override
16846                public void run() {
16847                    while (true) {
16848                        try {
16849                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
16850                                break;
16851                            }
16852                        } catch (InterruptedException ignored) {
16853                        }
16854
16855                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
16856                        final int progress = 10 + (int) MathUtils.constrain(
16857                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
16858                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
16859                    }
16860                }
16861            }.start();
16862
16863            final String dataAppName = codeFile.getName();
16864            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
16865                    dataAppName, appId, seinfo);
16866        } else {
16867            move = null;
16868        }
16869
16870        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
16871
16872        final Message msg = mHandler.obtainMessage(INIT_COPY);
16873        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
16874        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
16875                installerPackageName, volumeUuid, null, user, packageAbiOverride, null);
16876        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
16877        msg.obj = params;
16878
16879        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
16880                System.identityHashCode(msg.obj));
16881        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
16882                System.identityHashCode(msg.obj));
16883
16884        mHandler.sendMessage(msg);
16885    }
16886
16887    @Override
16888    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
16889        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
16890
16891        final int realMoveId = mNextMoveId.getAndIncrement();
16892        final Bundle extras = new Bundle();
16893        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
16894        mMoveCallbacks.notifyCreated(realMoveId, extras);
16895
16896        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
16897            @Override
16898            public void onCreated(int moveId, Bundle extras) {
16899                // Ignored
16900            }
16901
16902            @Override
16903            public void onStatusChanged(int moveId, int status, long estMillis) {
16904                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
16905            }
16906        };
16907
16908        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16909        storage.setPrimaryStorageUuid(volumeUuid, callback);
16910        return realMoveId;
16911    }
16912
16913    @Override
16914    public int getMoveStatus(int moveId) {
16915        mContext.enforceCallingOrSelfPermission(
16916                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16917        return mMoveCallbacks.mLastStatus.get(moveId);
16918    }
16919
16920    @Override
16921    public void registerMoveCallback(IPackageMoveObserver callback) {
16922        mContext.enforceCallingOrSelfPermission(
16923                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16924        mMoveCallbacks.register(callback);
16925    }
16926
16927    @Override
16928    public void unregisterMoveCallback(IPackageMoveObserver callback) {
16929        mContext.enforceCallingOrSelfPermission(
16930                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
16931        mMoveCallbacks.unregister(callback);
16932    }
16933
16934    @Override
16935    public boolean setInstallLocation(int loc) {
16936        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
16937                null);
16938        if (getInstallLocation() == loc) {
16939            return true;
16940        }
16941        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
16942                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
16943            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
16944                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
16945            return true;
16946        }
16947        return false;
16948   }
16949
16950    @Override
16951    public int getInstallLocation() {
16952        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
16953                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
16954                PackageHelper.APP_INSTALL_AUTO);
16955    }
16956
16957    /** Called by UserManagerService */
16958    void cleanUpUser(UserManagerService userManager, int userHandle) {
16959        synchronized (mPackages) {
16960            mDirtyUsers.remove(userHandle);
16961            mUserNeedsBadging.delete(userHandle);
16962            mSettings.removeUserLPw(userHandle);
16963            mPendingBroadcasts.remove(userHandle);
16964            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
16965        }
16966        synchronized (mInstallLock) {
16967            final StorageManager storage = mContext.getSystemService(StorageManager.class);
16968            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
16969                final String volumeUuid = vol.getFsUuid();
16970                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
16971                mInstaller.removeUserDataDirs(volumeUuid, userHandle);
16972            }
16973            synchronized (mPackages) {
16974                removeUnusedPackagesLILPw(userManager, userHandle);
16975            }
16976        }
16977    }
16978
16979    /**
16980     * We're removing userHandle and would like to remove any downloaded packages
16981     * that are no longer in use by any other user.
16982     * @param userHandle the user being removed
16983     */
16984    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
16985        final boolean DEBUG_CLEAN_APKS = false;
16986        int [] users = userManager.getUserIds();
16987        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
16988        while (psit.hasNext()) {
16989            PackageSetting ps = psit.next();
16990            if (ps.pkg == null) {
16991                continue;
16992            }
16993            final String packageName = ps.pkg.packageName;
16994            // Skip over if system app
16995            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
16996                continue;
16997            }
16998            if (DEBUG_CLEAN_APKS) {
16999                Slog.i(TAG, "Checking package " + packageName);
17000            }
17001            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
17002            if (keep) {
17003                if (DEBUG_CLEAN_APKS) {
17004                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
17005                }
17006            } else {
17007                for (int i = 0; i < users.length; i++) {
17008                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
17009                        keep = true;
17010                        if (DEBUG_CLEAN_APKS) {
17011                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
17012                                    + users[i]);
17013                        }
17014                        break;
17015                    }
17016                }
17017            }
17018            if (!keep) {
17019                if (DEBUG_CLEAN_APKS) {
17020                    Slog.i(TAG, "  Removing package " + packageName);
17021                }
17022                mHandler.post(new Runnable() {
17023                    public void run() {
17024                        deletePackageX(packageName, userHandle, 0);
17025                    } //end run
17026                });
17027            }
17028        }
17029    }
17030
17031    /** Called by UserManagerService */
17032    void createNewUser(int userHandle) {
17033        synchronized (mInstallLock) {
17034            mInstaller.createUserConfig(userHandle);
17035            mSettings.createNewUserLI(this, mInstaller, userHandle);
17036        }
17037        synchronized (mPackages) {
17038            applyFactoryDefaultBrowserLPw(userHandle);
17039            primeDomainVerificationsLPw(userHandle);
17040        }
17041    }
17042
17043    void newUserCreated(final int userHandle) {
17044        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
17045        // If permission review for legacy apps is required, we represent
17046        // dagerous permissions for such apps as always granted runtime
17047        // permissions to keep per user flag state whether review is needed.
17048        // Hence, if a new user is added we have to propagate dangerous
17049        // permission grants for these legacy apps.
17050        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
17051            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
17052                    | UPDATE_PERMISSIONS_REPLACE_ALL);
17053        }
17054    }
17055
17056    @Override
17057    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
17058        mContext.enforceCallingOrSelfPermission(
17059                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
17060                "Only package verification agents can read the verifier device identity");
17061
17062        synchronized (mPackages) {
17063            return mSettings.getVerifierDeviceIdentityLPw();
17064        }
17065    }
17066
17067    @Override
17068    public void setPermissionEnforced(String permission, boolean enforced) {
17069        // TODO: Now that we no longer change GID for storage, this should to away.
17070        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
17071                "setPermissionEnforced");
17072        if (READ_EXTERNAL_STORAGE.equals(permission)) {
17073            synchronized (mPackages) {
17074                if (mSettings.mReadExternalStorageEnforced == null
17075                        || mSettings.mReadExternalStorageEnforced != enforced) {
17076                    mSettings.mReadExternalStorageEnforced = enforced;
17077                    mSettings.writeLPr();
17078                }
17079            }
17080            // kill any non-foreground processes so we restart them and
17081            // grant/revoke the GID.
17082            final IActivityManager am = ActivityManagerNative.getDefault();
17083            if (am != null) {
17084                final long token = Binder.clearCallingIdentity();
17085                try {
17086                    am.killProcessesBelowForeground("setPermissionEnforcement");
17087                } catch (RemoteException e) {
17088                } finally {
17089                    Binder.restoreCallingIdentity(token);
17090                }
17091            }
17092        } else {
17093            throw new IllegalArgumentException("No selective enforcement for " + permission);
17094        }
17095    }
17096
17097    @Override
17098    @Deprecated
17099    public boolean isPermissionEnforced(String permission) {
17100        return true;
17101    }
17102
17103    @Override
17104    public boolean isStorageLow() {
17105        final long token = Binder.clearCallingIdentity();
17106        try {
17107            final DeviceStorageMonitorInternal
17108                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
17109            if (dsm != null) {
17110                return dsm.isMemoryLow();
17111            } else {
17112                return false;
17113            }
17114        } finally {
17115            Binder.restoreCallingIdentity(token);
17116        }
17117    }
17118
17119    @Override
17120    public IPackageInstaller getPackageInstaller() {
17121        return mInstallerService;
17122    }
17123
17124    private boolean userNeedsBadging(int userId) {
17125        int index = mUserNeedsBadging.indexOfKey(userId);
17126        if (index < 0) {
17127            final UserInfo userInfo;
17128            final long token = Binder.clearCallingIdentity();
17129            try {
17130                userInfo = sUserManager.getUserInfo(userId);
17131            } finally {
17132                Binder.restoreCallingIdentity(token);
17133            }
17134            final boolean b;
17135            if (userInfo != null && userInfo.isManagedProfile()) {
17136                b = true;
17137            } else {
17138                b = false;
17139            }
17140            mUserNeedsBadging.put(userId, b);
17141            return b;
17142        }
17143        return mUserNeedsBadging.valueAt(index);
17144    }
17145
17146    @Override
17147    public KeySet getKeySetByAlias(String packageName, String alias) {
17148        if (packageName == null || alias == null) {
17149            return null;
17150        }
17151        synchronized(mPackages) {
17152            final PackageParser.Package pkg = mPackages.get(packageName);
17153            if (pkg == null) {
17154                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17155                throw new IllegalArgumentException("Unknown package: " + packageName);
17156            }
17157            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17158            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
17159        }
17160    }
17161
17162    @Override
17163    public KeySet getSigningKeySet(String packageName) {
17164        if (packageName == null) {
17165            return null;
17166        }
17167        synchronized(mPackages) {
17168            final PackageParser.Package pkg = mPackages.get(packageName);
17169            if (pkg == null) {
17170                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17171                throw new IllegalArgumentException("Unknown package: " + packageName);
17172            }
17173            if (pkg.applicationInfo.uid != Binder.getCallingUid()
17174                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
17175                throw new SecurityException("May not access signing KeySet of other apps.");
17176            }
17177            KeySetManagerService ksms = mSettings.mKeySetManagerService;
17178            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
17179        }
17180    }
17181
17182    @Override
17183    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
17184        if (packageName == null || ks == null) {
17185            return false;
17186        }
17187        synchronized(mPackages) {
17188            final PackageParser.Package pkg = mPackages.get(packageName);
17189            if (pkg == null) {
17190                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17191                throw new IllegalArgumentException("Unknown package: " + packageName);
17192            }
17193            IBinder ksh = ks.getToken();
17194            if (ksh instanceof KeySetHandle) {
17195                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17196                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
17197            }
17198            return false;
17199        }
17200    }
17201
17202    @Override
17203    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
17204        if (packageName == null || ks == null) {
17205            return false;
17206        }
17207        synchronized(mPackages) {
17208            final PackageParser.Package pkg = mPackages.get(packageName);
17209            if (pkg == null) {
17210                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
17211                throw new IllegalArgumentException("Unknown package: " + packageName);
17212            }
17213            IBinder ksh = ks.getToken();
17214            if (ksh instanceof KeySetHandle) {
17215                KeySetManagerService ksms = mSettings.mKeySetManagerService;
17216                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
17217            }
17218            return false;
17219        }
17220    }
17221
17222    private void deletePackageIfUnusedLPr(final String packageName) {
17223        PackageSetting ps = mSettings.mPackages.get(packageName);
17224        if (ps == null) {
17225            return;
17226        }
17227        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
17228            // TODO Implement atomic delete if package is unused
17229            // It is currently possible that the package will be deleted even if it is installed
17230            // after this method returns.
17231            mHandler.post(new Runnable() {
17232                public void run() {
17233                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
17234                }
17235            });
17236        }
17237    }
17238
17239    /**
17240     * Check and throw if the given before/after packages would be considered a
17241     * downgrade.
17242     */
17243    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
17244            throws PackageManagerException {
17245        if (after.versionCode < before.mVersionCode) {
17246            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17247                    "Update version code " + after.versionCode + " is older than current "
17248                    + before.mVersionCode);
17249        } else if (after.versionCode == before.mVersionCode) {
17250            if (after.baseRevisionCode < before.baseRevisionCode) {
17251                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17252                        "Update base revision code " + after.baseRevisionCode
17253                        + " is older than current " + before.baseRevisionCode);
17254            }
17255
17256            if (!ArrayUtils.isEmpty(after.splitNames)) {
17257                for (int i = 0; i < after.splitNames.length; i++) {
17258                    final String splitName = after.splitNames[i];
17259                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
17260                    if (j != -1) {
17261                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
17262                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
17263                                    "Update split " + splitName + " revision code "
17264                                    + after.splitRevisionCodes[i] + " is older than current "
17265                                    + before.splitRevisionCodes[j]);
17266                        }
17267                    }
17268                }
17269            }
17270        }
17271    }
17272
17273    private static class MoveCallbacks extends Handler {
17274        private static final int MSG_CREATED = 1;
17275        private static final int MSG_STATUS_CHANGED = 2;
17276
17277        private final RemoteCallbackList<IPackageMoveObserver>
17278                mCallbacks = new RemoteCallbackList<>();
17279
17280        private final SparseIntArray mLastStatus = new SparseIntArray();
17281
17282        public MoveCallbacks(Looper looper) {
17283            super(looper);
17284        }
17285
17286        public void register(IPackageMoveObserver callback) {
17287            mCallbacks.register(callback);
17288        }
17289
17290        public void unregister(IPackageMoveObserver callback) {
17291            mCallbacks.unregister(callback);
17292        }
17293
17294        @Override
17295        public void handleMessage(Message msg) {
17296            final SomeArgs args = (SomeArgs) msg.obj;
17297            final int n = mCallbacks.beginBroadcast();
17298            for (int i = 0; i < n; i++) {
17299                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
17300                try {
17301                    invokeCallback(callback, msg.what, args);
17302                } catch (RemoteException ignored) {
17303                }
17304            }
17305            mCallbacks.finishBroadcast();
17306            args.recycle();
17307        }
17308
17309        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
17310                throws RemoteException {
17311            switch (what) {
17312                case MSG_CREATED: {
17313                    callback.onCreated(args.argi1, (Bundle) args.arg2);
17314                    break;
17315                }
17316                case MSG_STATUS_CHANGED: {
17317                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
17318                    break;
17319                }
17320            }
17321        }
17322
17323        private void notifyCreated(int moveId, Bundle extras) {
17324            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
17325
17326            final SomeArgs args = SomeArgs.obtain();
17327            args.argi1 = moveId;
17328            args.arg2 = extras;
17329            obtainMessage(MSG_CREATED, args).sendToTarget();
17330        }
17331
17332        private void notifyStatusChanged(int moveId, int status) {
17333            notifyStatusChanged(moveId, status, -1);
17334        }
17335
17336        private void notifyStatusChanged(int moveId, int status, long estMillis) {
17337            Slog.v(TAG, "Move " + moveId + " status " + status);
17338
17339            final SomeArgs args = SomeArgs.obtain();
17340            args.argi1 = moveId;
17341            args.argi2 = status;
17342            args.arg3 = estMillis;
17343            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
17344
17345            synchronized (mLastStatus) {
17346                mLastStatus.put(moveId, status);
17347            }
17348        }
17349    }
17350
17351    private final static class OnPermissionChangeListeners extends Handler {
17352        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
17353
17354        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
17355                new RemoteCallbackList<>();
17356
17357        public OnPermissionChangeListeners(Looper looper) {
17358            super(looper);
17359        }
17360
17361        @Override
17362        public void handleMessage(Message msg) {
17363            switch (msg.what) {
17364                case MSG_ON_PERMISSIONS_CHANGED: {
17365                    final int uid = msg.arg1;
17366                    handleOnPermissionsChanged(uid);
17367                } break;
17368            }
17369        }
17370
17371        public void addListenerLocked(IOnPermissionsChangeListener listener) {
17372            mPermissionListeners.register(listener);
17373
17374        }
17375
17376        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
17377            mPermissionListeners.unregister(listener);
17378        }
17379
17380        public void onPermissionsChanged(int uid) {
17381            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
17382                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
17383            }
17384        }
17385
17386        private void handleOnPermissionsChanged(int uid) {
17387            final int count = mPermissionListeners.beginBroadcast();
17388            try {
17389                for (int i = 0; i < count; i++) {
17390                    IOnPermissionsChangeListener callback = mPermissionListeners
17391                            .getBroadcastItem(i);
17392                    try {
17393                        callback.onPermissionsChanged(uid);
17394                    } catch (RemoteException e) {
17395                        Log.e(TAG, "Permission listener is dead", e);
17396                    }
17397                }
17398            } finally {
17399                mPermissionListeners.finishBroadcast();
17400            }
17401        }
17402    }
17403
17404    private class PackageManagerInternalImpl extends PackageManagerInternal {
17405        @Override
17406        public void setLocationPackagesProvider(PackagesProvider provider) {
17407            synchronized (mPackages) {
17408                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
17409            }
17410        }
17411
17412        @Override
17413        public void setImePackagesProvider(PackagesProvider provider) {
17414            synchronized (mPackages) {
17415                mDefaultPermissionPolicy.setImePackagesProviderLPr(provider);
17416            }
17417        }
17418
17419        @Override
17420        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
17421            synchronized (mPackages) {
17422                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
17423            }
17424        }
17425
17426        @Override
17427        public void setSmsAppPackagesProvider(PackagesProvider provider) {
17428            synchronized (mPackages) {
17429                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
17430            }
17431        }
17432
17433        @Override
17434        public void setDialerAppPackagesProvider(PackagesProvider provider) {
17435            synchronized (mPackages) {
17436                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
17437            }
17438        }
17439
17440        @Override
17441        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
17442            synchronized (mPackages) {
17443                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
17444            }
17445        }
17446
17447        @Override
17448        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
17449            synchronized (mPackages) {
17450                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
17451            }
17452        }
17453
17454        @Override
17455        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
17456            synchronized (mPackages) {
17457                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
17458                        packageName, userId);
17459            }
17460        }
17461
17462        @Override
17463        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
17464            synchronized (mPackages) {
17465                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
17466                        packageName, userId);
17467            }
17468        }
17469
17470        @Override
17471        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
17472            synchronized (mPackages) {
17473                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
17474                        packageName, userId);
17475            }
17476        }
17477
17478        @Override
17479        public void setKeepUninstalledPackages(final List<String> packageList) {
17480            Preconditions.checkNotNull(packageList);
17481            List<String> removedFromList = null;
17482            synchronized (mPackages) {
17483                if (mKeepUninstalledPackages != null) {
17484                    final int packagesCount = mKeepUninstalledPackages.size();
17485                    for (int i = 0; i < packagesCount; i++) {
17486                        String oldPackage = mKeepUninstalledPackages.get(i);
17487                        if (packageList != null && packageList.contains(oldPackage)) {
17488                            continue;
17489                        }
17490                        if (removedFromList == null) {
17491                            removedFromList = new ArrayList<>();
17492                        }
17493                        removedFromList.add(oldPackage);
17494                    }
17495                }
17496                mKeepUninstalledPackages = new ArrayList<>(packageList);
17497                if (removedFromList != null) {
17498                    final int removedCount = removedFromList.size();
17499                    for (int i = 0; i < removedCount; i++) {
17500                        deletePackageIfUnusedLPr(removedFromList.get(i));
17501                    }
17502                }
17503            }
17504        }
17505
17506        @Override
17507        public boolean isPermissionsReviewRequired(String packageName, int userId) {
17508            synchronized (mPackages) {
17509                // If we do not support permission review, done.
17510                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
17511                    return false;
17512                }
17513
17514                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
17515                if (packageSetting == null) {
17516                    return false;
17517                }
17518
17519                // Permission review applies only to apps not supporting the new permission model.
17520                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
17521                    return false;
17522                }
17523
17524                // Legacy apps have the permission and get user consent on launch.
17525                PermissionsState permissionsState = packageSetting.getPermissionsState();
17526                return permissionsState.isPermissionReviewRequired(userId);
17527            }
17528        }
17529    }
17530
17531    @Override
17532    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
17533        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
17534        synchronized (mPackages) {
17535            final long identity = Binder.clearCallingIdentity();
17536            try {
17537                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
17538                        packageNames, userId);
17539            } finally {
17540                Binder.restoreCallingIdentity(identity);
17541            }
17542        }
17543    }
17544
17545    private static void enforceSystemOrPhoneCaller(String tag) {
17546        int callingUid = Binder.getCallingUid();
17547        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
17548            throw new SecurityException(
17549                    "Cannot call " + tag + " from UID " + callingUid);
17550        }
17551    }
17552}
17553