PackageManagerService.java revision 8a8e68ce3b2b84174661dda1eb089db80c853b65
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.DELETE_KEEP_DATA;
28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
35import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID;
42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
55import static android.content.pm.PackageManager.INSTALL_INTERNAL;
56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
62import static android.content.pm.PackageManager.MATCH_ALL;
63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
67import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
68import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
69import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
70import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
71import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
72import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
73import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
74import static android.content.pm.PackageManager.PERMISSION_DENIED;
75import static android.content.pm.PackageManager.PERMISSION_GRANTED;
76import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
77import static android.content.pm.PackageParser.isApkFile;
78import static android.os.Process.PACKAGE_INFO_GID;
79import static android.os.Process.SYSTEM_UID;
80import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
81import static android.system.OsConstants.O_CREAT;
82import static android.system.OsConstants.O_RDWR;
83
84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
86import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
87import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
88import static com.android.internal.util.ArrayUtils.appendInt;
89import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
90import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
93import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
94import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
95import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
96import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
98
99import android.Manifest;
100import android.annotation.NonNull;
101import android.annotation.Nullable;
102import android.app.ActivityManager;
103import android.app.ActivityManagerNative;
104import android.app.IActivityManager;
105import android.app.admin.DevicePolicyManagerInternal;
106import android.app.admin.IDevicePolicyManager;
107import android.app.backup.IBackupManager;
108import android.content.BroadcastReceiver;
109import android.content.ComponentName;
110import android.content.Context;
111import android.content.IIntentReceiver;
112import android.content.Intent;
113import android.content.IntentFilter;
114import android.content.IntentSender;
115import android.content.IntentSender.SendIntentException;
116import android.content.ServiceConnection;
117import android.content.pm.ActivityInfo;
118import android.content.pm.ApplicationInfo;
119import android.content.pm.AppsQueryHelper;
120import android.content.pm.ComponentInfo;
121import android.content.pm.EphemeralApplicationInfo;
122import android.content.pm.EphemeralResolveInfo;
123import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
124import android.content.pm.FeatureInfo;
125import android.content.pm.IOnPermissionsChangeListener;
126import android.content.pm.IPackageDataObserver;
127import android.content.pm.IPackageDeleteObserver;
128import android.content.pm.IPackageDeleteObserver2;
129import android.content.pm.IPackageInstallObserver2;
130import android.content.pm.IPackageInstaller;
131import android.content.pm.IPackageManager;
132import android.content.pm.IPackageMoveObserver;
133import android.content.pm.IPackageStatsObserver;
134import android.content.pm.InstrumentationInfo;
135import android.content.pm.IntentFilterVerificationInfo;
136import android.content.pm.KeySet;
137import android.content.pm.PackageCleanItem;
138import android.content.pm.PackageInfo;
139import android.content.pm.PackageInfoLite;
140import android.content.pm.PackageInstaller;
141import android.content.pm.PackageManager;
142import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
143import android.content.pm.PackageManagerInternal;
144import android.content.pm.PackageParser;
145import android.content.pm.PackageParser.ActivityIntentInfo;
146import android.content.pm.PackageParser.PackageLite;
147import android.content.pm.PackageParser.PackageParserException;
148import android.content.pm.PackageStats;
149import android.content.pm.PackageUserState;
150import android.content.pm.ParceledListSlice;
151import android.content.pm.PermissionGroupInfo;
152import android.content.pm.PermissionInfo;
153import android.content.pm.ProviderInfo;
154import android.content.pm.ResolveInfo;
155import android.content.pm.ServiceInfo;
156import android.content.pm.Signature;
157import android.content.pm.UserInfo;
158import android.content.pm.VerifierDeviceIdentity;
159import android.content.pm.VerifierInfo;
160import android.content.res.Resources;
161import android.graphics.Bitmap;
162import android.hardware.display.DisplayManager;
163import android.net.Uri;
164import android.os.Binder;
165import android.os.Build;
166import android.os.Bundle;
167import android.os.Debug;
168import android.os.Environment;
169import android.os.Environment.UserEnvironment;
170import android.os.FileUtils;
171import android.os.Handler;
172import android.os.IBinder;
173import android.os.Looper;
174import android.os.Message;
175import android.os.Parcel;
176import android.os.ParcelFileDescriptor;
177import android.os.Process;
178import android.os.RemoteCallbackList;
179import android.os.RemoteException;
180import android.os.ResultReceiver;
181import android.os.SELinux;
182import android.os.ServiceManager;
183import android.os.SystemClock;
184import android.os.SystemProperties;
185import android.os.Trace;
186import android.os.UserHandle;
187import android.os.UserManager;
188import android.os.storage.IMountService;
189import android.os.storage.MountServiceInternal;
190import android.os.storage.StorageEventListener;
191import android.os.storage.StorageManager;
192import android.os.storage.VolumeInfo;
193import android.os.storage.VolumeRecord;
194import android.security.KeyStore;
195import android.security.SystemKeyStore;
196import android.system.ErrnoException;
197import android.system.Os;
198import android.text.TextUtils;
199import android.text.format.DateUtils;
200import android.util.ArrayMap;
201import android.util.ArraySet;
202import android.util.AtomicFile;
203import android.util.DisplayMetrics;
204import android.util.EventLog;
205import android.util.ExceptionUtils;
206import android.util.Log;
207import android.util.LogPrinter;
208import android.util.MathUtils;
209import android.util.PrintStreamPrinter;
210import android.util.Slog;
211import android.util.SparseArray;
212import android.util.SparseBooleanArray;
213import android.util.SparseIntArray;
214import android.util.Xml;
215import android.view.Display;
216
217import com.android.internal.R;
218import com.android.internal.annotations.GuardedBy;
219import com.android.internal.app.IMediaContainerService;
220import com.android.internal.app.ResolverActivity;
221import com.android.internal.content.NativeLibraryHelper;
222import com.android.internal.content.PackageHelper;
223import com.android.internal.os.IParcelFileDescriptorFactory;
224import com.android.internal.os.InstallerConnection.InstallerException;
225import com.android.internal.os.SomeArgs;
226import com.android.internal.os.Zygote;
227import com.android.internal.util.ArrayUtils;
228import com.android.internal.util.FastPrintWriter;
229import com.android.internal.util.FastXmlSerializer;
230import com.android.internal.util.IndentingPrintWriter;
231import com.android.internal.util.Preconditions;
232import com.android.internal.util.XmlUtils;
233import com.android.server.EventLogTags;
234import com.android.server.FgThread;
235import com.android.server.IntentResolver;
236import com.android.server.LocalServices;
237import com.android.server.ServiceThread;
238import com.android.server.SystemConfig;
239import com.android.server.Watchdog;
240import com.android.server.pm.PermissionsState.PermissionState;
241import com.android.server.pm.Settings.DatabaseVersion;
242import com.android.server.pm.Settings.VersionInfo;
243import com.android.server.storage.DeviceStorageMonitorInternal;
244
245import dalvik.system.DexFile;
246import dalvik.system.VMRuntime;
247
248import libcore.io.IoUtils;
249import libcore.util.EmptyArray;
250
251import org.xmlpull.v1.XmlPullParser;
252import org.xmlpull.v1.XmlPullParserException;
253import org.xmlpull.v1.XmlSerializer;
254
255import java.io.BufferedInputStream;
256import java.io.BufferedOutputStream;
257import java.io.BufferedReader;
258import java.io.ByteArrayInputStream;
259import java.io.ByteArrayOutputStream;
260import java.io.File;
261import java.io.FileDescriptor;
262import java.io.FileNotFoundException;
263import java.io.FileOutputStream;
264import java.io.FileReader;
265import java.io.FilenameFilter;
266import java.io.IOException;
267import java.io.InputStream;
268import java.io.PrintWriter;
269import java.nio.charset.StandardCharsets;
270import java.security.MessageDigest;
271import java.security.NoSuchAlgorithmException;
272import java.security.PublicKey;
273import java.security.cert.CertificateEncodingException;
274import java.security.cert.CertificateException;
275import java.text.SimpleDateFormat;
276import java.util.ArrayList;
277import java.util.Arrays;
278import java.util.Collection;
279import java.util.Collections;
280import java.util.Comparator;
281import java.util.Date;
282import java.util.HashSet;
283import java.util.Iterator;
284import java.util.List;
285import java.util.Map;
286import java.util.Objects;
287import java.util.Set;
288import java.util.concurrent.CountDownLatch;
289import java.util.concurrent.TimeUnit;
290import java.util.concurrent.atomic.AtomicBoolean;
291import java.util.concurrent.atomic.AtomicInteger;
292import java.util.concurrent.atomic.AtomicLong;
293
294/**
295 * Keep track of all those .apks everywhere.
296 *
297 * This is very central to the platform's security; please run the unit
298 * tests whenever making modifications here:
299 *
300runtest -c android.content.pm.PackageManagerTests frameworks-core
301 *
302 * {@hide}
303 */
304public class PackageManagerService extends IPackageManager.Stub {
305    static final String TAG = "PackageManager";
306    static final boolean DEBUG_SETTINGS = false;
307    static final boolean DEBUG_PREFERRED = false;
308    static final boolean DEBUG_UPGRADE = false;
309    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
310    private static final boolean DEBUG_BACKUP = false;
311    private static final boolean DEBUG_INSTALL = false;
312    private static final boolean DEBUG_REMOVE = false;
313    private static final boolean DEBUG_BROADCASTS = false;
314    private static final boolean DEBUG_SHOW_INFO = false;
315    private static final boolean DEBUG_PACKAGE_INFO = false;
316    private static final boolean DEBUG_INTENT_MATCHING = false;
317    private static final boolean DEBUG_PACKAGE_SCANNING = false;
318    private static final boolean DEBUG_VERIFY = false;
319
320    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
321    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
322    // user, but by default initialize to this.
323    static final boolean DEBUG_DEXOPT = false;
324
325    private static final boolean DEBUG_ABI_SELECTION = false;
326    private static final boolean DEBUG_EPHEMERAL = false;
327    private static final boolean DEBUG_TRIAGED_MISSING = false;
328    private static final boolean DEBUG_APP_DATA = false;
329
330    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
331
332    private static final boolean DISABLE_EPHEMERAL_APPS = true;
333
334    private static final int RADIO_UID = Process.PHONE_UID;
335    private static final int LOG_UID = Process.LOG_UID;
336    private static final int NFC_UID = Process.NFC_UID;
337    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
338    private static final int SHELL_UID = Process.SHELL_UID;
339
340    // Cap the size of permission trees that 3rd party apps can define
341    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
342
343    // Suffix used during package installation when copying/moving
344    // package apks to install directory.
345    private static final String INSTALL_PACKAGE_SUFFIX = "-";
346
347    static final int SCAN_NO_DEX = 1<<1;
348    static final int SCAN_FORCE_DEX = 1<<2;
349    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
350    static final int SCAN_NEW_INSTALL = 1<<4;
351    static final int SCAN_NO_PATHS = 1<<5;
352    static final int SCAN_UPDATE_TIME = 1<<6;
353    static final int SCAN_DEFER_DEX = 1<<7;
354    static final int SCAN_BOOTING = 1<<8;
355    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
356    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
357    static final int SCAN_REPLACING = 1<<11;
358    static final int SCAN_REQUIRE_KNOWN = 1<<12;
359    static final int SCAN_MOVE = 1<<13;
360    static final int SCAN_INITIAL = 1<<14;
361    static final int SCAN_CHECK_ONLY = 1<<15;
362    static final int SCAN_DONT_KILL_APP = 1<<17;
363
364    static final int REMOVE_CHATTY = 1<<16;
365
366    private static final int[] EMPTY_INT_ARRAY = new int[0];
367
368    /**
369     * Timeout (in milliseconds) after which the watchdog should declare that
370     * our handler thread is wedged.  The usual default for such things is one
371     * minute but we sometimes do very lengthy I/O operations on this thread,
372     * such as installing multi-gigabyte applications, so ours needs to be longer.
373     */
374    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
375
376    /**
377     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
378     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
379     * settings entry if available, otherwise we use the hardcoded default.  If it's been
380     * more than this long since the last fstrim, we force one during the boot sequence.
381     *
382     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
383     * one gets run at the next available charging+idle time.  This final mandatory
384     * no-fstrim check kicks in only of the other scheduling criteria is never met.
385     */
386    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
387
388    /**
389     * Whether verification is enabled by default.
390     */
391    private static final boolean DEFAULT_VERIFY_ENABLE = true;
392
393    /**
394     * The default maximum time to wait for the verification agent to return in
395     * milliseconds.
396     */
397    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
398
399    /**
400     * The default response for package verification timeout.
401     *
402     * This can be either PackageManager.VERIFICATION_ALLOW or
403     * PackageManager.VERIFICATION_REJECT.
404     */
405    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
406
407    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
408
409    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
410            DEFAULT_CONTAINER_PACKAGE,
411            "com.android.defcontainer.DefaultContainerService");
412
413    private static final String KILL_APP_REASON_GIDS_CHANGED =
414            "permission grant or revoke changed gids";
415
416    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
417            "permissions revoked";
418
419    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
420
421    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
422
423    /** Permission grant: not grant the permission. */
424    private static final int GRANT_DENIED = 1;
425
426    /** Permission grant: grant the permission as an install permission. */
427    private static final int GRANT_INSTALL = 2;
428
429    /** Permission grant: grant the permission as a runtime one. */
430    private static final int GRANT_RUNTIME = 3;
431
432    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
433    private static final int GRANT_UPGRADE = 4;
434
435    /** Canonical intent used to identify what counts as a "web browser" app */
436    private static final Intent sBrowserIntent;
437    static {
438        sBrowserIntent = new Intent();
439        sBrowserIntent.setAction(Intent.ACTION_VIEW);
440        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
441        sBrowserIntent.setData(Uri.parse("http:"));
442    }
443
444    final ServiceThread mHandlerThread;
445
446    final PackageHandler mHandler;
447
448    /**
449     * Messages for {@link #mHandler} that need to wait for system ready before
450     * being dispatched.
451     */
452    private ArrayList<Message> mPostSystemReadyMessages;
453
454    final int mSdkVersion = Build.VERSION.SDK_INT;
455
456    final Context mContext;
457    final boolean mFactoryTest;
458    final boolean mOnlyCore;
459    final DisplayMetrics mMetrics;
460    final int mDefParseFlags;
461    final String[] mSeparateProcesses;
462    final boolean mIsUpgrade;
463
464    /** The location for ASEC container files on internal storage. */
465    final String mAsecInternalPath;
466
467    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
468    // LOCK HELD.  Can be called with mInstallLock held.
469    @GuardedBy("mInstallLock")
470    final Installer mInstaller;
471
472    /** Directory where installed third-party apps stored */
473    final File mAppInstallDir;
474    final File mEphemeralInstallDir;
475
476    /**
477     * Directory to which applications installed internally have their
478     * 32 bit native libraries copied.
479     */
480    private File mAppLib32InstallDir;
481
482    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
483    // apps.
484    final File mDrmAppPrivateInstallDir;
485
486    // ----------------------------------------------------------------
487
488    // Lock for state used when installing and doing other long running
489    // operations.  Methods that must be called with this lock held have
490    // the suffix "LI".
491    final Object mInstallLock = new Object();
492
493    // ----------------------------------------------------------------
494
495    // Keys are String (package name), values are Package.  This also serves
496    // as the lock for the global state.  Methods that must be called with
497    // this lock held have the prefix "LP".
498    @GuardedBy("mPackages")
499    final ArrayMap<String, PackageParser.Package> mPackages =
500            new ArrayMap<String, PackageParser.Package>();
501
502    final ArrayMap<String, Set<String>> mKnownCodebase =
503            new ArrayMap<String, Set<String>>();
504
505    // Tracks available target package names -> overlay package paths.
506    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
507        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
508
509    /**
510     * Tracks new system packages [received in an OTA] that we expect to
511     * find updated user-installed versions. Keys are package name, values
512     * are package location.
513     */
514    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
515
516    /**
517     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
518     */
519    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
520    /**
521     * Whether or not system app permissions should be promoted from install to runtime.
522     */
523    boolean mPromoteSystemApps;
524
525    final Settings mSettings;
526    boolean mRestoredSettings;
527
528    // System configuration read by SystemConfig.
529    final int[] mGlobalGids;
530    final SparseArray<ArraySet<String>> mSystemPermissions;
531    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
532
533    // If mac_permissions.xml was found for seinfo labeling.
534    boolean mFoundPolicyFile;
535
536    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
537
538    public static final class SharedLibraryEntry {
539        public final String path;
540        public final String apk;
541
542        SharedLibraryEntry(String _path, String _apk) {
543            path = _path;
544            apk = _apk;
545        }
546    }
547
548    // Currently known shared libraries.
549    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
550            new ArrayMap<String, SharedLibraryEntry>();
551
552    // All available activities, for your resolving pleasure.
553    final ActivityIntentResolver mActivities =
554            new ActivityIntentResolver();
555
556    // All available receivers, for your resolving pleasure.
557    final ActivityIntentResolver mReceivers =
558            new ActivityIntentResolver();
559
560    // All available services, for your resolving pleasure.
561    final ServiceIntentResolver mServices = new ServiceIntentResolver();
562
563    // All available providers, for your resolving pleasure.
564    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
565
566    // Mapping from provider base names (first directory in content URI codePath)
567    // to the provider information.
568    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
569            new ArrayMap<String, PackageParser.Provider>();
570
571    // Mapping from instrumentation class names to info about them.
572    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
573            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
574
575    // Mapping from permission names to info about them.
576    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
577            new ArrayMap<String, PackageParser.PermissionGroup>();
578
579    // Packages whose data we have transfered into another package, thus
580    // should no longer exist.
581    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
582
583    // Broadcast actions that are only available to the system.
584    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
585
586    /** List of packages waiting for verification. */
587    final SparseArray<PackageVerificationState> mPendingVerification
588            = new SparseArray<PackageVerificationState>();
589
590    /** Set of packages associated with each app op permission. */
591    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
592
593    final PackageInstallerService mInstallerService;
594
595    private final PackageDexOptimizer mPackageDexOptimizer;
596
597    private AtomicInteger mNextMoveId = new AtomicInteger();
598    private final MoveCallbacks mMoveCallbacks;
599
600    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
601
602    // Cache of users who need badging.
603    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
604
605    /** Token for keys in mPendingVerification. */
606    private int mPendingVerificationToken = 0;
607
608    volatile boolean mSystemReady;
609    volatile boolean mSafeMode;
610    volatile boolean mHasSystemUidErrors;
611
612    ApplicationInfo mAndroidApplication;
613    final ActivityInfo mResolveActivity = new ActivityInfo();
614    final ResolveInfo mResolveInfo = new ResolveInfo();
615    ComponentName mResolveComponentName;
616    PackageParser.Package mPlatformPackage;
617    ComponentName mCustomResolverComponentName;
618
619    boolean mResolverReplaced = false;
620
621    private final @Nullable ComponentName mIntentFilterVerifierComponent;
622    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
623
624    private int mIntentFilterVerificationToken = 0;
625
626    /** Component that knows whether or not an ephemeral application exists */
627    final ComponentName mEphemeralResolverComponent;
628    /** The service connection to the ephemeral resolver */
629    final EphemeralResolverConnection mEphemeralResolverConnection;
630
631    /** Component used to install ephemeral applications */
632    final ComponentName mEphemeralInstallerComponent;
633    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
634    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
635
636    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
637            = new SparseArray<IntentFilterVerificationState>();
638
639    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
640            new DefaultPermissionGrantPolicy(this);
641
642    // List of packages names to keep cached, even if they are uninstalled for all users
643    private List<String> mKeepUninstalledPackages;
644
645    private static class IFVerificationParams {
646        PackageParser.Package pkg;
647        boolean replacing;
648        int userId;
649        int verifierUid;
650
651        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
652                int _userId, int _verifierUid) {
653            pkg = _pkg;
654            replacing = _replacing;
655            userId = _userId;
656            replacing = _replacing;
657            verifierUid = _verifierUid;
658        }
659    }
660
661    private interface IntentFilterVerifier<T extends IntentFilter> {
662        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
663                                               T filter, String packageName);
664        void startVerifications(int userId);
665        void receiveVerificationResponse(int verificationId);
666    }
667
668    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
669        private Context mContext;
670        private ComponentName mIntentFilterVerifierComponent;
671        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
672
673        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
674            mContext = context;
675            mIntentFilterVerifierComponent = verifierComponent;
676        }
677
678        private String getDefaultScheme() {
679            return IntentFilter.SCHEME_HTTPS;
680        }
681
682        @Override
683        public void startVerifications(int userId) {
684            // Launch verifications requests
685            int count = mCurrentIntentFilterVerifications.size();
686            for (int n=0; n<count; n++) {
687                int verificationId = mCurrentIntentFilterVerifications.get(n);
688                final IntentFilterVerificationState ivs =
689                        mIntentFilterVerificationStates.get(verificationId);
690
691                String packageName = ivs.getPackageName();
692
693                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
694                final int filterCount = filters.size();
695                ArraySet<String> domainsSet = new ArraySet<>();
696                for (int m=0; m<filterCount; m++) {
697                    PackageParser.ActivityIntentInfo filter = filters.get(m);
698                    domainsSet.addAll(filter.getHostsList());
699                }
700                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
701                synchronized (mPackages) {
702                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
703                            packageName, domainsList) != null) {
704                        scheduleWriteSettingsLocked();
705                    }
706                }
707                sendVerificationRequest(userId, verificationId, ivs);
708            }
709            mCurrentIntentFilterVerifications.clear();
710        }
711
712        private void sendVerificationRequest(int userId, int verificationId,
713                IntentFilterVerificationState ivs) {
714
715            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
716            verificationIntent.putExtra(
717                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
718                    verificationId);
719            verificationIntent.putExtra(
720                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
721                    getDefaultScheme());
722            verificationIntent.putExtra(
723                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
724                    ivs.getHostsString());
725            verificationIntent.putExtra(
726                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
727                    ivs.getPackageName());
728            verificationIntent.setComponent(mIntentFilterVerifierComponent);
729            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
730
731            UserHandle user = new UserHandle(userId);
732            mContext.sendBroadcastAsUser(verificationIntent, user);
733            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
734                    "Sending IntentFilter verification broadcast");
735        }
736
737        public void receiveVerificationResponse(int verificationId) {
738            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
739
740            final boolean verified = ivs.isVerified();
741
742            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
743            final int count = filters.size();
744            if (DEBUG_DOMAIN_VERIFICATION) {
745                Slog.i(TAG, "Received verification response " + verificationId
746                        + " for " + count + " filters, verified=" + verified);
747            }
748            for (int n=0; n<count; n++) {
749                PackageParser.ActivityIntentInfo filter = filters.get(n);
750                filter.setVerified(verified);
751
752                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
753                        + " verified with result:" + verified + " and hosts:"
754                        + ivs.getHostsString());
755            }
756
757            mIntentFilterVerificationStates.remove(verificationId);
758
759            final String packageName = ivs.getPackageName();
760            IntentFilterVerificationInfo ivi = null;
761
762            synchronized (mPackages) {
763                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
764            }
765            if (ivi == null) {
766                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
767                        + verificationId + " packageName:" + packageName);
768                return;
769            }
770            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
771                    "Updating IntentFilterVerificationInfo for package " + packageName
772                            +" verificationId:" + verificationId);
773
774            synchronized (mPackages) {
775                if (verified) {
776                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
777                } else {
778                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
779                }
780                scheduleWriteSettingsLocked();
781
782                final int userId = ivs.getUserId();
783                if (userId != UserHandle.USER_ALL) {
784                    final int userStatus =
785                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
786
787                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
788                    boolean needUpdate = false;
789
790                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
791                    // already been set by the User thru the Disambiguation dialog
792                    switch (userStatus) {
793                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
794                            if (verified) {
795                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
796                            } else {
797                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
798                            }
799                            needUpdate = true;
800                            break;
801
802                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
803                            if (verified) {
804                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
805                                needUpdate = true;
806                            }
807                            break;
808
809                        default:
810                            // Nothing to do
811                    }
812
813                    if (needUpdate) {
814                        mSettings.updateIntentFilterVerificationStatusLPw(
815                                packageName, updatedStatus, userId);
816                        scheduleWritePackageRestrictionsLocked(userId);
817                    }
818                }
819            }
820        }
821
822        @Override
823        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
824                    ActivityIntentInfo filter, String packageName) {
825            if (!hasValidDomains(filter)) {
826                return false;
827            }
828            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
829            if (ivs == null) {
830                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
831                        packageName);
832            }
833            if (DEBUG_DOMAIN_VERIFICATION) {
834                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
835            }
836            ivs.addFilter(filter);
837            return true;
838        }
839
840        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
841                int userId, int verificationId, String packageName) {
842            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
843                    verifierUid, userId, packageName);
844            ivs.setPendingState();
845            synchronized (mPackages) {
846                mIntentFilterVerificationStates.append(verificationId, ivs);
847                mCurrentIntentFilterVerifications.add(verificationId);
848            }
849            return ivs;
850        }
851    }
852
853    private static boolean hasValidDomains(ActivityIntentInfo filter) {
854        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
855                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
856                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
857    }
858
859    // Set of pending broadcasts for aggregating enable/disable of components.
860    static class PendingPackageBroadcasts {
861        // for each user id, a map of <package name -> components within that package>
862        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
863
864        public PendingPackageBroadcasts() {
865            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
866        }
867
868        public ArrayList<String> get(int userId, String packageName) {
869            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
870            return packages.get(packageName);
871        }
872
873        public void put(int userId, String packageName, ArrayList<String> components) {
874            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
875            packages.put(packageName, components);
876        }
877
878        public void remove(int userId, String packageName) {
879            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
880            if (packages != null) {
881                packages.remove(packageName);
882            }
883        }
884
885        public void remove(int userId) {
886            mUidMap.remove(userId);
887        }
888
889        public int userIdCount() {
890            return mUidMap.size();
891        }
892
893        public int userIdAt(int n) {
894            return mUidMap.keyAt(n);
895        }
896
897        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
898            return mUidMap.get(userId);
899        }
900
901        public int size() {
902            // total number of pending broadcast entries across all userIds
903            int num = 0;
904            for (int i = 0; i< mUidMap.size(); i++) {
905                num += mUidMap.valueAt(i).size();
906            }
907            return num;
908        }
909
910        public void clear() {
911            mUidMap.clear();
912        }
913
914        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
915            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
916            if (map == null) {
917                map = new ArrayMap<String, ArrayList<String>>();
918                mUidMap.put(userId, map);
919            }
920            return map;
921        }
922    }
923    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
924
925    // Service Connection to remote media container service to copy
926    // package uri's from external media onto secure containers
927    // or internal storage.
928    private IMediaContainerService mContainerService = null;
929
930    static final int SEND_PENDING_BROADCAST = 1;
931    static final int MCS_BOUND = 3;
932    static final int END_COPY = 4;
933    static final int INIT_COPY = 5;
934    static final int MCS_UNBIND = 6;
935    static final int START_CLEANING_PACKAGE = 7;
936    static final int FIND_INSTALL_LOC = 8;
937    static final int POST_INSTALL = 9;
938    static final int MCS_RECONNECT = 10;
939    static final int MCS_GIVE_UP = 11;
940    static final int UPDATED_MEDIA_STATUS = 12;
941    static final int WRITE_SETTINGS = 13;
942    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
943    static final int PACKAGE_VERIFIED = 15;
944    static final int CHECK_PENDING_VERIFICATION = 16;
945    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
946    static final int INTENT_FILTER_VERIFIED = 18;
947
948    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
949
950    // Delay time in millisecs
951    static final int BROADCAST_DELAY = 10 * 1000;
952
953    static UserManagerService sUserManager;
954
955    // Stores a list of users whose package restrictions file needs to be updated
956    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
957
958    final private DefaultContainerConnection mDefContainerConn =
959            new DefaultContainerConnection();
960    class DefaultContainerConnection implements ServiceConnection {
961        public void onServiceConnected(ComponentName name, IBinder service) {
962            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
963            IMediaContainerService imcs =
964                IMediaContainerService.Stub.asInterface(service);
965            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
966        }
967
968        public void onServiceDisconnected(ComponentName name) {
969            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
970        }
971    }
972
973    // Recordkeeping of restore-after-install operations that are currently in flight
974    // between the Package Manager and the Backup Manager
975    static class PostInstallData {
976        public InstallArgs args;
977        public PackageInstalledInfo res;
978
979        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
980            args = _a;
981            res = _r;
982        }
983    }
984
985    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
986    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
987
988    // XML tags for backup/restore of various bits of state
989    private static final String TAG_PREFERRED_BACKUP = "pa";
990    private static final String TAG_DEFAULT_APPS = "da";
991    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
992
993    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
994    private static final String TAG_ALL_GRANTS = "rt-grants";
995    private static final String TAG_GRANT = "grant";
996    private static final String ATTR_PACKAGE_NAME = "pkg";
997
998    private static final String TAG_PERMISSION = "perm";
999    private static final String ATTR_PERMISSION_NAME = "name";
1000    private static final String ATTR_IS_GRANTED = "g";
1001    private static final String ATTR_USER_SET = "set";
1002    private static final String ATTR_USER_FIXED = "fixed";
1003    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1004
1005    // System/policy permission grants are not backed up
1006    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1007            FLAG_PERMISSION_POLICY_FIXED
1008            | FLAG_PERMISSION_SYSTEM_FIXED
1009            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1010
1011    // And we back up these user-adjusted states
1012    private static final int USER_RUNTIME_GRANT_MASK =
1013            FLAG_PERMISSION_USER_SET
1014            | FLAG_PERMISSION_USER_FIXED
1015            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1016
1017    final @Nullable String mRequiredVerifierPackage;
1018    final @Nullable String mRequiredInstallerPackage;
1019
1020    private final PackageUsage mPackageUsage = new PackageUsage();
1021
1022    private class PackageUsage {
1023        private static final int WRITE_INTERVAL
1024            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1025
1026        private final Object mFileLock = new Object();
1027        private final AtomicLong mLastWritten = new AtomicLong(0);
1028        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1029
1030        private boolean mIsHistoricalPackageUsageAvailable = true;
1031
1032        boolean isHistoricalPackageUsageAvailable() {
1033            return mIsHistoricalPackageUsageAvailable;
1034        }
1035
1036        void write(boolean force) {
1037            if (force) {
1038                writeInternal();
1039                return;
1040            }
1041            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1042                && !DEBUG_DEXOPT) {
1043                return;
1044            }
1045            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1046                new Thread("PackageUsage_DiskWriter") {
1047                    @Override
1048                    public void run() {
1049                        try {
1050                            writeInternal();
1051                        } finally {
1052                            mBackgroundWriteRunning.set(false);
1053                        }
1054                    }
1055                }.start();
1056            }
1057        }
1058
1059        private void writeInternal() {
1060            synchronized (mPackages) {
1061                synchronized (mFileLock) {
1062                    AtomicFile file = getFile();
1063                    FileOutputStream f = null;
1064                    try {
1065                        f = file.startWrite();
1066                        BufferedOutputStream out = new BufferedOutputStream(f);
1067                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1068                        StringBuilder sb = new StringBuilder();
1069                        for (PackageParser.Package pkg : mPackages.values()) {
1070                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1071                                continue;
1072                            }
1073                            sb.setLength(0);
1074                            sb.append(pkg.packageName);
1075                            sb.append(' ');
1076                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1077                            sb.append('\n');
1078                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1079                        }
1080                        out.flush();
1081                        file.finishWrite(f);
1082                    } catch (IOException e) {
1083                        if (f != null) {
1084                            file.failWrite(f);
1085                        }
1086                        Log.e(TAG, "Failed to write package usage times", e);
1087                    }
1088                }
1089            }
1090            mLastWritten.set(SystemClock.elapsedRealtime());
1091        }
1092
1093        void readLP() {
1094            synchronized (mFileLock) {
1095                AtomicFile file = getFile();
1096                BufferedInputStream in = null;
1097                try {
1098                    in = new BufferedInputStream(file.openRead());
1099                    StringBuffer sb = new StringBuffer();
1100                    while (true) {
1101                        String packageName = readToken(in, sb, ' ');
1102                        if (packageName == null) {
1103                            break;
1104                        }
1105                        String timeInMillisString = readToken(in, sb, '\n');
1106                        if (timeInMillisString == null) {
1107                            throw new IOException("Failed to find last usage time for package "
1108                                                  + packageName);
1109                        }
1110                        PackageParser.Package pkg = mPackages.get(packageName);
1111                        if (pkg == null) {
1112                            continue;
1113                        }
1114                        long timeInMillis;
1115                        try {
1116                            timeInMillis = Long.parseLong(timeInMillisString);
1117                        } catch (NumberFormatException e) {
1118                            throw new IOException("Failed to parse " + timeInMillisString
1119                                                  + " as a long.", e);
1120                        }
1121                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1122                    }
1123                } catch (FileNotFoundException expected) {
1124                    mIsHistoricalPackageUsageAvailable = false;
1125                } catch (IOException e) {
1126                    Log.w(TAG, "Failed to read package usage times", e);
1127                } finally {
1128                    IoUtils.closeQuietly(in);
1129                }
1130            }
1131            mLastWritten.set(SystemClock.elapsedRealtime());
1132        }
1133
1134        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1135                throws IOException {
1136            sb.setLength(0);
1137            while (true) {
1138                int ch = in.read();
1139                if (ch == -1) {
1140                    if (sb.length() == 0) {
1141                        return null;
1142                    }
1143                    throw new IOException("Unexpected EOF");
1144                }
1145                if (ch == endOfToken) {
1146                    return sb.toString();
1147                }
1148                sb.append((char)ch);
1149            }
1150        }
1151
1152        private AtomicFile getFile() {
1153            File dataDir = Environment.getDataDirectory();
1154            File systemDir = new File(dataDir, "system");
1155            File fname = new File(systemDir, "package-usage.list");
1156            return new AtomicFile(fname);
1157        }
1158    }
1159
1160    class PackageHandler extends Handler {
1161        private boolean mBound = false;
1162        final ArrayList<HandlerParams> mPendingInstalls =
1163            new ArrayList<HandlerParams>();
1164
1165        private boolean connectToService() {
1166            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1167                    " DefaultContainerService");
1168            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1169            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1170            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1171                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1172                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1173                mBound = true;
1174                return true;
1175            }
1176            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1177            return false;
1178        }
1179
1180        private void disconnectService() {
1181            mContainerService = null;
1182            mBound = false;
1183            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1184            mContext.unbindService(mDefContainerConn);
1185            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1186        }
1187
1188        PackageHandler(Looper looper) {
1189            super(looper);
1190        }
1191
1192        public void handleMessage(Message msg) {
1193            try {
1194                doHandleMessage(msg);
1195            } finally {
1196                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1197            }
1198        }
1199
1200        void doHandleMessage(Message msg) {
1201            switch (msg.what) {
1202                case INIT_COPY: {
1203                    HandlerParams params = (HandlerParams) msg.obj;
1204                    int idx = mPendingInstalls.size();
1205                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1206                    // If a bind was already initiated we dont really
1207                    // need to do anything. The pending install
1208                    // will be processed later on.
1209                    if (!mBound) {
1210                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1211                                System.identityHashCode(mHandler));
1212                        // If this is the only one pending we might
1213                        // have to bind to the service again.
1214                        if (!connectToService()) {
1215                            Slog.e(TAG, "Failed to bind to media container service");
1216                            params.serviceError();
1217                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1218                                    System.identityHashCode(mHandler));
1219                            if (params.traceMethod != null) {
1220                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1221                                        params.traceCookie);
1222                            }
1223                            return;
1224                        } else {
1225                            // Once we bind to the service, the first
1226                            // pending request will be processed.
1227                            mPendingInstalls.add(idx, params);
1228                        }
1229                    } else {
1230                        mPendingInstalls.add(idx, params);
1231                        // Already bound to the service. Just make
1232                        // sure we trigger off processing the first request.
1233                        if (idx == 0) {
1234                            mHandler.sendEmptyMessage(MCS_BOUND);
1235                        }
1236                    }
1237                    break;
1238                }
1239                case MCS_BOUND: {
1240                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1241                    if (msg.obj != null) {
1242                        mContainerService = (IMediaContainerService) msg.obj;
1243                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1244                                System.identityHashCode(mHandler));
1245                    }
1246                    if (mContainerService == null) {
1247                        if (!mBound) {
1248                            // Something seriously wrong since we are not bound and we are not
1249                            // waiting for connection. Bail out.
1250                            Slog.e(TAG, "Cannot bind to media container service");
1251                            for (HandlerParams params : mPendingInstalls) {
1252                                // Indicate service bind error
1253                                params.serviceError();
1254                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1255                                        System.identityHashCode(params));
1256                                if (params.traceMethod != null) {
1257                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1258                                            params.traceMethod, params.traceCookie);
1259                                }
1260                                return;
1261                            }
1262                            mPendingInstalls.clear();
1263                        } else {
1264                            Slog.w(TAG, "Waiting to connect to media container service");
1265                        }
1266                    } else if (mPendingInstalls.size() > 0) {
1267                        HandlerParams params = mPendingInstalls.get(0);
1268                        if (params != null) {
1269                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1270                                    System.identityHashCode(params));
1271                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1272                            if (params.startCopy()) {
1273                                // We are done...  look for more work or to
1274                                // go idle.
1275                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1276                                        "Checking for more work or unbind...");
1277                                // Delete pending install
1278                                if (mPendingInstalls.size() > 0) {
1279                                    mPendingInstalls.remove(0);
1280                                }
1281                                if (mPendingInstalls.size() == 0) {
1282                                    if (mBound) {
1283                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1284                                                "Posting delayed MCS_UNBIND");
1285                                        removeMessages(MCS_UNBIND);
1286                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1287                                        // Unbind after a little delay, to avoid
1288                                        // continual thrashing.
1289                                        sendMessageDelayed(ubmsg, 10000);
1290                                    }
1291                                } else {
1292                                    // There are more pending requests in queue.
1293                                    // Just post MCS_BOUND message to trigger processing
1294                                    // of next pending install.
1295                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1296                                            "Posting MCS_BOUND for next work");
1297                                    mHandler.sendEmptyMessage(MCS_BOUND);
1298                                }
1299                            }
1300                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1301                        }
1302                    } else {
1303                        // Should never happen ideally.
1304                        Slog.w(TAG, "Empty queue");
1305                    }
1306                    break;
1307                }
1308                case MCS_RECONNECT: {
1309                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1310                    if (mPendingInstalls.size() > 0) {
1311                        if (mBound) {
1312                            disconnectService();
1313                        }
1314                        if (!connectToService()) {
1315                            Slog.e(TAG, "Failed to bind to media container service");
1316                            for (HandlerParams params : mPendingInstalls) {
1317                                // Indicate service bind error
1318                                params.serviceError();
1319                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1320                                        System.identityHashCode(params));
1321                            }
1322                            mPendingInstalls.clear();
1323                        }
1324                    }
1325                    break;
1326                }
1327                case MCS_UNBIND: {
1328                    // If there is no actual work left, then time to unbind.
1329                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1330
1331                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1332                        if (mBound) {
1333                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1334
1335                            disconnectService();
1336                        }
1337                    } else if (mPendingInstalls.size() > 0) {
1338                        // There are more pending requests in queue.
1339                        // Just post MCS_BOUND message to trigger processing
1340                        // of next pending install.
1341                        mHandler.sendEmptyMessage(MCS_BOUND);
1342                    }
1343
1344                    break;
1345                }
1346                case MCS_GIVE_UP: {
1347                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1348                    HandlerParams params = mPendingInstalls.remove(0);
1349                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1350                            System.identityHashCode(params));
1351                    break;
1352                }
1353                case SEND_PENDING_BROADCAST: {
1354                    String packages[];
1355                    ArrayList<String> components[];
1356                    int size = 0;
1357                    int uids[];
1358                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1359                    synchronized (mPackages) {
1360                        if (mPendingBroadcasts == null) {
1361                            return;
1362                        }
1363                        size = mPendingBroadcasts.size();
1364                        if (size <= 0) {
1365                            // Nothing to be done. Just return
1366                            return;
1367                        }
1368                        packages = new String[size];
1369                        components = new ArrayList[size];
1370                        uids = new int[size];
1371                        int i = 0;  // filling out the above arrays
1372
1373                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1374                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1375                            Iterator<Map.Entry<String, ArrayList<String>>> it
1376                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1377                                            .entrySet().iterator();
1378                            while (it.hasNext() && i < size) {
1379                                Map.Entry<String, ArrayList<String>> ent = it.next();
1380                                packages[i] = ent.getKey();
1381                                components[i] = ent.getValue();
1382                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1383                                uids[i] = (ps != null)
1384                                        ? UserHandle.getUid(packageUserId, ps.appId)
1385                                        : -1;
1386                                i++;
1387                            }
1388                        }
1389                        size = i;
1390                        mPendingBroadcasts.clear();
1391                    }
1392                    // Send broadcasts
1393                    for (int i = 0; i < size; i++) {
1394                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1395                    }
1396                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1397                    break;
1398                }
1399                case START_CLEANING_PACKAGE: {
1400                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1401                    final String packageName = (String)msg.obj;
1402                    final int userId = msg.arg1;
1403                    final boolean andCode = msg.arg2 != 0;
1404                    synchronized (mPackages) {
1405                        if (userId == UserHandle.USER_ALL) {
1406                            int[] users = sUserManager.getUserIds();
1407                            for (int user : users) {
1408                                mSettings.addPackageToCleanLPw(
1409                                        new PackageCleanItem(user, packageName, andCode));
1410                            }
1411                        } else {
1412                            mSettings.addPackageToCleanLPw(
1413                                    new PackageCleanItem(userId, packageName, andCode));
1414                        }
1415                    }
1416                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1417                    startCleaningPackages();
1418                } break;
1419                case POST_INSTALL: {
1420                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1421
1422                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1423                    mRunningInstalls.delete(msg.arg1);
1424
1425                    if (data != null) {
1426                        InstallArgs args = data.args;
1427                        PackageInstalledInfo parentRes = data.res;
1428
1429                        final boolean grantPermissions = (args.installFlags
1430                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1431                        final boolean killApp = (args.installFlags
1432                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1433                        final String[] grantedPermissions = args.installGrantPermissions;
1434
1435                        // Handle the parent package
1436                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1437                                grantedPermissions, args.observer);
1438
1439                        // Handle the child packages
1440                        final int childCount = (parentRes.addedChildPackages != null)
1441                                ? parentRes.addedChildPackages.size() : 0;
1442                        for (int i = 0; i < childCount; i++) {
1443                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1444                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1445                                    grantedPermissions, args.observer);
1446                        }
1447
1448                        // Log tracing if needed
1449                        if (args.traceMethod != null) {
1450                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1451                                    args.traceCookie);
1452                        }
1453                    } else {
1454                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1455                    }
1456
1457                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1458                } break;
1459                case UPDATED_MEDIA_STATUS: {
1460                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1461                    boolean reportStatus = msg.arg1 == 1;
1462                    boolean doGc = msg.arg2 == 1;
1463                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1464                    if (doGc) {
1465                        // Force a gc to clear up stale containers.
1466                        Runtime.getRuntime().gc();
1467                    }
1468                    if (msg.obj != null) {
1469                        @SuppressWarnings("unchecked")
1470                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1471                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1472                        // Unload containers
1473                        unloadAllContainers(args);
1474                    }
1475                    if (reportStatus) {
1476                        try {
1477                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1478                            PackageHelper.getMountService().finishMediaUpdate();
1479                        } catch (RemoteException e) {
1480                            Log.e(TAG, "MountService not running?");
1481                        }
1482                    }
1483                } break;
1484                case WRITE_SETTINGS: {
1485                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1486                    synchronized (mPackages) {
1487                        removeMessages(WRITE_SETTINGS);
1488                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1489                        mSettings.writeLPr();
1490                        mDirtyUsers.clear();
1491                    }
1492                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1493                } break;
1494                case WRITE_PACKAGE_RESTRICTIONS: {
1495                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1496                    synchronized (mPackages) {
1497                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1498                        for (int userId : mDirtyUsers) {
1499                            mSettings.writePackageRestrictionsLPr(userId);
1500                        }
1501                        mDirtyUsers.clear();
1502                    }
1503                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1504                } break;
1505                case CHECK_PENDING_VERIFICATION: {
1506                    final int verificationId = msg.arg1;
1507                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1508
1509                    if ((state != null) && !state.timeoutExtended()) {
1510                        final InstallArgs args = state.getInstallArgs();
1511                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1512
1513                        Slog.i(TAG, "Verification timed out for " + originUri);
1514                        mPendingVerification.remove(verificationId);
1515
1516                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1517
1518                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1519                            Slog.i(TAG, "Continuing with installation of " + originUri);
1520                            state.setVerifierResponse(Binder.getCallingUid(),
1521                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1522                            broadcastPackageVerified(verificationId, originUri,
1523                                    PackageManager.VERIFICATION_ALLOW,
1524                                    state.getInstallArgs().getUser());
1525                            try {
1526                                ret = args.copyApk(mContainerService, true);
1527                            } catch (RemoteException e) {
1528                                Slog.e(TAG, "Could not contact the ContainerService");
1529                            }
1530                        } else {
1531                            broadcastPackageVerified(verificationId, originUri,
1532                                    PackageManager.VERIFICATION_REJECT,
1533                                    state.getInstallArgs().getUser());
1534                        }
1535
1536                        Trace.asyncTraceEnd(
1537                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1538
1539                        processPendingInstall(args, ret);
1540                        mHandler.sendEmptyMessage(MCS_UNBIND);
1541                    }
1542                    break;
1543                }
1544                case PACKAGE_VERIFIED: {
1545                    final int verificationId = msg.arg1;
1546
1547                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1548                    if (state == null) {
1549                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1550                        break;
1551                    }
1552
1553                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1554
1555                    state.setVerifierResponse(response.callerUid, response.code);
1556
1557                    if (state.isVerificationComplete()) {
1558                        mPendingVerification.remove(verificationId);
1559
1560                        final InstallArgs args = state.getInstallArgs();
1561                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1562
1563                        int ret;
1564                        if (state.isInstallAllowed()) {
1565                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1566                            broadcastPackageVerified(verificationId, originUri,
1567                                    response.code, state.getInstallArgs().getUser());
1568                            try {
1569                                ret = args.copyApk(mContainerService, true);
1570                            } catch (RemoteException e) {
1571                                Slog.e(TAG, "Could not contact the ContainerService");
1572                            }
1573                        } else {
1574                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1575                        }
1576
1577                        Trace.asyncTraceEnd(
1578                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1579
1580                        processPendingInstall(args, ret);
1581                        mHandler.sendEmptyMessage(MCS_UNBIND);
1582                    }
1583
1584                    break;
1585                }
1586                case START_INTENT_FILTER_VERIFICATIONS: {
1587                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1588                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1589                            params.replacing, params.pkg);
1590                    break;
1591                }
1592                case INTENT_FILTER_VERIFIED: {
1593                    final int verificationId = msg.arg1;
1594
1595                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1596                            verificationId);
1597                    if (state == null) {
1598                        Slog.w(TAG, "Invalid IntentFilter verification token "
1599                                + verificationId + " received");
1600                        break;
1601                    }
1602
1603                    final int userId = state.getUserId();
1604
1605                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1606                            "Processing IntentFilter verification with token:"
1607                            + verificationId + " and userId:" + userId);
1608
1609                    final IntentFilterVerificationResponse response =
1610                            (IntentFilterVerificationResponse) msg.obj;
1611
1612                    state.setVerifierResponse(response.callerUid, response.code);
1613
1614                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1615                            "IntentFilter verification with token:" + verificationId
1616                            + " and userId:" + userId
1617                            + " is settings verifier response with response code:"
1618                            + response.code);
1619
1620                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1621                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1622                                + response.getFailedDomainsString());
1623                    }
1624
1625                    if (state.isVerificationComplete()) {
1626                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1627                    } else {
1628                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1629                                "IntentFilter verification with token:" + verificationId
1630                                + " was not said to be complete");
1631                    }
1632
1633                    break;
1634                }
1635            }
1636        }
1637    }
1638
1639    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1640            boolean killApp, String[] grantedPermissions,
1641            IPackageInstallObserver2 installObserver) {
1642        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1643            // Send the removed broadcasts
1644            if (res.removedInfo != null) {
1645                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1646            }
1647
1648            // Now that we successfully installed the package, grant runtime
1649            // permissions if requested before broadcasting the install.
1650            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1651                    >= Build.VERSION_CODES.M) {
1652                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1653            }
1654
1655            final boolean update = res.removedInfo != null
1656                    && res.removedInfo.removedPackage != null;
1657
1658            // If this is the first time we have child packages for a disabled privileged
1659            // app that had no children, we grant requested runtime permissions to the new
1660            // children if the parent on the system image had them already granted.
1661            if (res.pkg.parentPackage != null) {
1662                synchronized (mPackages) {
1663                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1664                }
1665            }
1666
1667            synchronized (mPackages) {
1668                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1669            }
1670
1671            final String packageName = res.pkg.applicationInfo.packageName;
1672            Bundle extras = new Bundle(1);
1673            extras.putInt(Intent.EXTRA_UID, res.uid);
1674
1675            // Determine the set of users who are adding this package for
1676            // the first time vs. those who are seeing an update.
1677            int[] firstUsers = EMPTY_INT_ARRAY;
1678            int[] updateUsers = EMPTY_INT_ARRAY;
1679            if (res.origUsers == null || res.origUsers.length == 0) {
1680                firstUsers = res.newUsers;
1681            } else {
1682                for (int newUser : res.newUsers) {
1683                    boolean isNew = true;
1684                    for (int origUser : res.origUsers) {
1685                        if (origUser == newUser) {
1686                            isNew = false;
1687                            break;
1688                        }
1689                    }
1690                    if (isNew) {
1691                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1692                    } else {
1693                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1694                    }
1695                }
1696            }
1697
1698            // Send installed broadcasts if the install/update is not ephemeral
1699            if (!isEphemeral(res.pkg)) {
1700                // Send added for users that see the package for the first time
1701                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1702                        extras, 0 /*flags*/, null /*targetPackage*/,
1703                        null /*finishedReceiver*/, firstUsers);
1704
1705                // Send added for users that don't see the package for the first time
1706                if (update) {
1707                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1708                }
1709                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1710                        extras, 0 /*flags*/, null /*targetPackage*/,
1711                        null /*finishedReceiver*/, updateUsers);
1712
1713                // Send replaced for users that don't see the package for the first time
1714                if (update) {
1715                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1716                            packageName, extras, 0 /*flags*/,
1717                            null /*targetPackage*/, null /*finishedReceiver*/,
1718                            updateUsers);
1719                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1720                            null /*package*/, null /*extras*/, 0 /*flags*/,
1721                            packageName /*targetPackage*/,
1722                            null /*finishedReceiver*/, updateUsers);
1723                }
1724
1725                // Send broadcast package appeared if forward locked/external for all users
1726                // treat asec-hosted packages like removable media on upgrade
1727                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1728                    if (DEBUG_INSTALL) {
1729                        Slog.i(TAG, "upgrading pkg " + res.pkg
1730                                + " is ASEC-hosted -> AVAILABLE");
1731                    }
1732                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1733                    ArrayList<String> pkgList = new ArrayList<>(1);
1734                    pkgList.add(packageName);
1735                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1736                }
1737            }
1738
1739            // Work that needs to happen on first install within each user
1740            if (firstUsers != null && firstUsers.length > 0) {
1741                synchronized (mPackages) {
1742                    for (int userId : firstUsers) {
1743                        // If this app is a browser and it's newly-installed for some
1744                        // users, clear any default-browser state in those users. The
1745                        // app's nature doesn't depend on the user, so we can just check
1746                        // its browser nature in any user and generalize.
1747                        if (packageIsBrowser(packageName, userId)) {
1748                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1749                        }
1750
1751                        // We may also need to apply pending (restored) runtime
1752                        // permission grants within these users.
1753                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1754                    }
1755                }
1756            }
1757
1758            // Log current value of "unknown sources" setting
1759            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1760                    getUnknownSourcesSettings());
1761
1762            // Force a gc to clear up things
1763            Runtime.getRuntime().gc();
1764
1765            // Remove the replaced package's older resources safely now
1766            // We delete after a gc for applications  on sdcard.
1767            if (res.removedInfo != null && res.removedInfo.args != null) {
1768                synchronized (mInstallLock) {
1769                    res.removedInfo.args.doPostDeleteLI(true);
1770                }
1771            }
1772        }
1773
1774        // If someone is watching installs - notify them
1775        if (installObserver != null) {
1776            try {
1777                Bundle extras = extrasForInstallResult(res);
1778                installObserver.onPackageInstalled(res.name, res.returnCode,
1779                        res.returnMsg, extras);
1780            } catch (RemoteException e) {
1781                Slog.i(TAG, "Observer no longer exists.");
1782            }
1783        }
1784    }
1785
1786    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1787            PackageParser.Package pkg) {
1788        if (pkg.parentPackage == null) {
1789            return;
1790        }
1791        if (pkg.requestedPermissions == null) {
1792            return;
1793        }
1794        final PackageSetting disabledSysParentPs = mSettings
1795                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1796        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1797                || !disabledSysParentPs.isPrivileged()
1798                || (disabledSysParentPs.childPackageNames != null
1799                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1800            return;
1801        }
1802        final int[] allUserIds = sUserManager.getUserIds();
1803        final int permCount = pkg.requestedPermissions.size();
1804        for (int i = 0; i < permCount; i++) {
1805            String permission = pkg.requestedPermissions.get(i);
1806            BasePermission bp = mSettings.mPermissions.get(permission);
1807            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1808                continue;
1809            }
1810            for (int userId : allUserIds) {
1811                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1812                        permission, userId)) {
1813                    grantRuntimePermission(pkg.packageName, permission, userId);
1814                }
1815            }
1816        }
1817    }
1818
1819    private StorageEventListener mStorageListener = new StorageEventListener() {
1820        @Override
1821        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1822            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1823                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1824                    final String volumeUuid = vol.getFsUuid();
1825
1826                    // Clean up any users or apps that were removed or recreated
1827                    // while this volume was missing
1828                    reconcileUsers(volumeUuid);
1829                    reconcileApps(volumeUuid);
1830
1831                    // Clean up any install sessions that expired or were
1832                    // cancelled while this volume was missing
1833                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1834
1835                    loadPrivatePackages(vol);
1836
1837                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1838                    unloadPrivatePackages(vol);
1839                }
1840            }
1841
1842            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1843                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1844                    updateExternalMediaStatus(true, false);
1845                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1846                    updateExternalMediaStatus(false, false);
1847                }
1848            }
1849        }
1850
1851        @Override
1852        public void onVolumeForgotten(String fsUuid) {
1853            if (TextUtils.isEmpty(fsUuid)) {
1854                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1855                return;
1856            }
1857
1858            // Remove any apps installed on the forgotten volume
1859            synchronized (mPackages) {
1860                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1861                for (PackageSetting ps : packages) {
1862                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1863                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1864                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1865                }
1866
1867                mSettings.onVolumeForgotten(fsUuid);
1868                mSettings.writeLPr();
1869            }
1870        }
1871    };
1872
1873    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1874            String[] grantedPermissions) {
1875        for (int userId : userIds) {
1876            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1877        }
1878
1879        // We could have touched GID membership, so flush out packages.list
1880        synchronized (mPackages) {
1881            mSettings.writePackageListLPr();
1882        }
1883    }
1884
1885    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1886            String[] grantedPermissions) {
1887        SettingBase sb = (SettingBase) pkg.mExtras;
1888        if (sb == null) {
1889            return;
1890        }
1891
1892        PermissionsState permissionsState = sb.getPermissionsState();
1893
1894        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1895                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1896
1897        synchronized (mPackages) {
1898            for (String permission : pkg.requestedPermissions) {
1899                BasePermission bp = mSettings.mPermissions.get(permission);
1900                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1901                        && (grantedPermissions == null
1902                               || ArrayUtils.contains(grantedPermissions, permission))) {
1903                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1904                    // Installer cannot change immutable permissions.
1905                    if ((flags & immutableFlags) == 0) {
1906                        grantRuntimePermission(pkg.packageName, permission, userId);
1907                    }
1908                }
1909            }
1910        }
1911    }
1912
1913    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1914        Bundle extras = null;
1915        switch (res.returnCode) {
1916            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1917                extras = new Bundle();
1918                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1919                        res.origPermission);
1920                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1921                        res.origPackage);
1922                break;
1923            }
1924            case PackageManager.INSTALL_SUCCEEDED: {
1925                extras = new Bundle();
1926                extras.putBoolean(Intent.EXTRA_REPLACING,
1927                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1928                break;
1929            }
1930        }
1931        return extras;
1932    }
1933
1934    void scheduleWriteSettingsLocked() {
1935        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1936            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1937        }
1938    }
1939
1940    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1941        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1942        scheduleWritePackageRestrictionsLocked(userId);
1943    }
1944
1945    void scheduleWritePackageRestrictionsLocked(int userId) {
1946        final int[] userIds = (userId == UserHandle.USER_ALL)
1947                ? sUserManager.getUserIds() : new int[]{userId};
1948        for (int nextUserId : userIds) {
1949            if (!sUserManager.exists(nextUserId)) return;
1950            mDirtyUsers.add(nextUserId);
1951            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1952                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1953            }
1954        }
1955    }
1956
1957    public static PackageManagerService main(Context context, Installer installer,
1958            boolean factoryTest, boolean onlyCore) {
1959        PackageManagerService m = new PackageManagerService(context, installer,
1960                factoryTest, onlyCore);
1961        m.enableSystemUserPackages();
1962        ServiceManager.addService("package", m);
1963        return m;
1964    }
1965
1966    private void enableSystemUserPackages() {
1967        if (!UserManager.isSplitSystemUser()) {
1968            return;
1969        }
1970        // For system user, enable apps based on the following conditions:
1971        // - app is whitelisted or belong to one of these groups:
1972        //   -- system app which has no launcher icons
1973        //   -- system app which has INTERACT_ACROSS_USERS permission
1974        //   -- system IME app
1975        // - app is not in the blacklist
1976        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
1977        Set<String> enableApps = new ArraySet<>();
1978        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
1979                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
1980                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
1981        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
1982        enableApps.addAll(wlApps);
1983        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
1984                /* systemAppsOnly */ false, UserHandle.SYSTEM));
1985        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
1986        enableApps.removeAll(blApps);
1987        Log.i(TAG, "Applications installed for system user: " + enableApps);
1988        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
1989                UserHandle.SYSTEM);
1990        final int allAppsSize = allAps.size();
1991        synchronized (mPackages) {
1992            for (int i = 0; i < allAppsSize; i++) {
1993                String pName = allAps.get(i);
1994                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
1995                // Should not happen, but we shouldn't be failing if it does
1996                if (pkgSetting == null) {
1997                    continue;
1998                }
1999                boolean install = enableApps.contains(pName);
2000                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2001                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2002                            + " for system user");
2003                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2004                }
2005            }
2006        }
2007    }
2008
2009    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2010        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2011                Context.DISPLAY_SERVICE);
2012        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2013    }
2014
2015    public PackageManagerService(Context context, Installer installer,
2016            boolean factoryTest, boolean onlyCore) {
2017        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2018                SystemClock.uptimeMillis());
2019
2020        if (mSdkVersion <= 0) {
2021            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2022        }
2023
2024        mContext = context;
2025        mFactoryTest = factoryTest;
2026        mOnlyCore = onlyCore;
2027        mMetrics = new DisplayMetrics();
2028        mSettings = new Settings(mPackages);
2029        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2030                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2031        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2032                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2033        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2034                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2035        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2036                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2037        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2038                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2039        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2040                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2041
2042        String separateProcesses = SystemProperties.get("debug.separate_processes");
2043        if (separateProcesses != null && separateProcesses.length() > 0) {
2044            if ("*".equals(separateProcesses)) {
2045                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2046                mSeparateProcesses = null;
2047                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2048            } else {
2049                mDefParseFlags = 0;
2050                mSeparateProcesses = separateProcesses.split(",");
2051                Slog.w(TAG, "Running with debug.separate_processes: "
2052                        + separateProcesses);
2053            }
2054        } else {
2055            mDefParseFlags = 0;
2056            mSeparateProcesses = null;
2057        }
2058
2059        mInstaller = installer;
2060        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2061                "*dexopt*");
2062        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2063
2064        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2065                FgThread.get().getLooper());
2066
2067        getDefaultDisplayMetrics(context, mMetrics);
2068
2069        SystemConfig systemConfig = SystemConfig.getInstance();
2070        mGlobalGids = systemConfig.getGlobalGids();
2071        mSystemPermissions = systemConfig.getSystemPermissions();
2072        mAvailableFeatures = systemConfig.getAvailableFeatures();
2073
2074        synchronized (mInstallLock) {
2075        // writer
2076        synchronized (mPackages) {
2077            mHandlerThread = new ServiceThread(TAG,
2078                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2079            mHandlerThread.start();
2080            mHandler = new PackageHandler(mHandlerThread.getLooper());
2081            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2082
2083            File dataDir = Environment.getDataDirectory();
2084            mAppInstallDir = new File(dataDir, "app");
2085            mAppLib32InstallDir = new File(dataDir, "app-lib");
2086            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2087            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2088            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2089
2090            sUserManager = new UserManagerService(context, this, mPackages);
2091
2092            // Propagate permission configuration in to package manager.
2093            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2094                    = systemConfig.getPermissions();
2095            for (int i=0; i<permConfig.size(); i++) {
2096                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2097                BasePermission bp = mSettings.mPermissions.get(perm.name);
2098                if (bp == null) {
2099                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2100                    mSettings.mPermissions.put(perm.name, bp);
2101                }
2102                if (perm.gids != null) {
2103                    bp.setGids(perm.gids, perm.perUser);
2104                }
2105            }
2106
2107            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2108            for (int i=0; i<libConfig.size(); i++) {
2109                mSharedLibraries.put(libConfig.keyAt(i),
2110                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2111            }
2112
2113            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2114
2115            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2116
2117            String customResolverActivity = Resources.getSystem().getString(
2118                    R.string.config_customResolverActivity);
2119            if (TextUtils.isEmpty(customResolverActivity)) {
2120                customResolverActivity = null;
2121            } else {
2122                mCustomResolverComponentName = ComponentName.unflattenFromString(
2123                        customResolverActivity);
2124            }
2125
2126            long startTime = SystemClock.uptimeMillis();
2127
2128            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2129                    startTime);
2130
2131            // Set flag to monitor and not change apk file paths when
2132            // scanning install directories.
2133            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2134
2135            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2136            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2137
2138            if (bootClassPath == null) {
2139                Slog.w(TAG, "No BOOTCLASSPATH found!");
2140            }
2141
2142            if (systemServerClassPath == null) {
2143                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2144            }
2145
2146            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2147            final String[] dexCodeInstructionSets =
2148                    getDexCodeInstructionSets(
2149                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2150
2151            /**
2152             * Ensure all external libraries have had dexopt run on them.
2153             */
2154            if (mSharedLibraries.size() > 0) {
2155                // NOTE: For now, we're compiling these system "shared libraries"
2156                // (and framework jars) into all available architectures. It's possible
2157                // to compile them only when we come across an app that uses them (there's
2158                // already logic for that in scanPackageLI) but that adds some complexity.
2159                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2160                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2161                        final String lib = libEntry.path;
2162                        if (lib == null) {
2163                            continue;
2164                        }
2165
2166                        try {
2167                            // Shared libraries do not have profiles so we perform a full
2168                            // AOT compilation (if needed).
2169                            int dexoptNeeded = DexFile.getDexOptNeeded(
2170                                    lib, dexCodeInstructionSet,
2171                                    DexFile.COMPILATION_TYPE_FULL);
2172                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2173                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2174                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2175                                        StorageManager.UUID_PRIVATE_INTERNAL,
2176                                        false /*useProfiles*/);
2177                            }
2178                        } catch (FileNotFoundException e) {
2179                            Slog.w(TAG, "Library not found: " + lib);
2180                        } catch (IOException | InstallerException e) {
2181                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2182                                    + e.getMessage());
2183                        }
2184                    }
2185                }
2186            }
2187
2188            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2189
2190            final VersionInfo ver = mSettings.getInternalVersion();
2191            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2192            // when upgrading from pre-M, promote system app permissions from install to runtime
2193            mPromoteSystemApps =
2194                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2195
2196            // save off the names of pre-existing system packages prior to scanning; we don't
2197            // want to automatically grant runtime permissions for new system apps
2198            if (mPromoteSystemApps) {
2199                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2200                while (pkgSettingIter.hasNext()) {
2201                    PackageSetting ps = pkgSettingIter.next();
2202                    if (isSystemApp(ps)) {
2203                        mExistingSystemPackages.add(ps.name);
2204                    }
2205                }
2206            }
2207
2208            // Collect vendor overlay packages.
2209            // (Do this before scanning any apps.)
2210            // For security and version matching reason, only consider
2211            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2212            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2213            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2214                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2215
2216            // Find base frameworks (resource packages without code).
2217            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2218                    | PackageParser.PARSE_IS_SYSTEM_DIR
2219                    | PackageParser.PARSE_IS_PRIVILEGED,
2220                    scanFlags | SCAN_NO_DEX, 0);
2221
2222            // Collected privileged system packages.
2223            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2224            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2225                    | PackageParser.PARSE_IS_SYSTEM_DIR
2226                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2227
2228            // Collect ordinary system packages.
2229            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2230            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2231                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2232
2233            // Collect all vendor packages.
2234            File vendorAppDir = new File("/vendor/app");
2235            try {
2236                vendorAppDir = vendorAppDir.getCanonicalFile();
2237            } catch (IOException e) {
2238                // failed to look up canonical path, continue with original one
2239            }
2240            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2241                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2242
2243            // Collect all OEM packages.
2244            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2245            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2246                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2247
2248            // Prune any system packages that no longer exist.
2249            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2250            if (!mOnlyCore) {
2251                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2252                while (psit.hasNext()) {
2253                    PackageSetting ps = psit.next();
2254
2255                    /*
2256                     * If this is not a system app, it can't be a
2257                     * disable system app.
2258                     */
2259                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2260                        continue;
2261                    }
2262
2263                    /*
2264                     * If the package is scanned, it's not erased.
2265                     */
2266                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2267                    if (scannedPkg != null) {
2268                        /*
2269                         * If the system app is both scanned and in the
2270                         * disabled packages list, then it must have been
2271                         * added via OTA. Remove it from the currently
2272                         * scanned package so the previously user-installed
2273                         * application can be scanned.
2274                         */
2275                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2276                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2277                                    + ps.name + "; removing system app.  Last known codePath="
2278                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2279                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2280                                    + scannedPkg.mVersionCode);
2281                            removePackageLI(scannedPkg, true);
2282                            mExpectingBetter.put(ps.name, ps.codePath);
2283                        }
2284
2285                        continue;
2286                    }
2287
2288                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2289                        psit.remove();
2290                        logCriticalInfo(Log.WARN, "System package " + ps.name
2291                                + " no longer exists; wiping its data");
2292                        removeDataDirsLI(null, ps.name);
2293                    } else {
2294                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2295                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2296                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2297                        }
2298                    }
2299                }
2300            }
2301
2302            //look for any incomplete package installations
2303            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2304            //clean up list
2305            for(int i = 0; i < deletePkgsList.size(); i++) {
2306                //clean up here
2307                cleanupInstallFailedPackage(deletePkgsList.get(i));
2308            }
2309            //delete tmp files
2310            deleteTempPackageFiles();
2311
2312            // Remove any shared userIDs that have no associated packages
2313            mSettings.pruneSharedUsersLPw();
2314
2315            if (!mOnlyCore) {
2316                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2317                        SystemClock.uptimeMillis());
2318                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2319
2320                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2321                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2322
2323                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2324                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2325
2326                /**
2327                 * Remove disable package settings for any updated system
2328                 * apps that were removed via an OTA. If they're not a
2329                 * previously-updated app, remove them completely.
2330                 * Otherwise, just revoke their system-level permissions.
2331                 */
2332                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2333                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2334                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2335
2336                    String msg;
2337                    if (deletedPkg == null) {
2338                        msg = "Updated system package " + deletedAppName
2339                                + " no longer exists; wiping its data";
2340                        removeDataDirsLI(null, deletedAppName);
2341                    } else {
2342                        msg = "Updated system app + " + deletedAppName
2343                                + " no longer present; removing system privileges for "
2344                                + deletedAppName;
2345
2346                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2347
2348                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2349                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2350                    }
2351                    logCriticalInfo(Log.WARN, msg);
2352                }
2353
2354                /**
2355                 * Make sure all system apps that we expected to appear on
2356                 * the userdata partition actually showed up. If they never
2357                 * appeared, crawl back and revive the system version.
2358                 */
2359                for (int i = 0; i < mExpectingBetter.size(); i++) {
2360                    final String packageName = mExpectingBetter.keyAt(i);
2361                    if (!mPackages.containsKey(packageName)) {
2362                        final File scanFile = mExpectingBetter.valueAt(i);
2363
2364                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2365                                + " but never showed up; reverting to system");
2366
2367                        final int reparseFlags;
2368                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2369                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2370                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2371                                    | PackageParser.PARSE_IS_PRIVILEGED;
2372                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2373                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2374                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2375                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2376                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2377                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2378                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2379                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2380                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2381                        } else {
2382                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2383                            continue;
2384                        }
2385
2386                        mSettings.enableSystemPackageLPw(packageName);
2387
2388                        try {
2389                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2390                        } catch (PackageManagerException e) {
2391                            Slog.e(TAG, "Failed to parse original system package: "
2392                                    + e.getMessage());
2393                        }
2394                    }
2395                }
2396            }
2397            mExpectingBetter.clear();
2398
2399            // Now that we know all of the shared libraries, update all clients to have
2400            // the correct library paths.
2401            updateAllSharedLibrariesLPw();
2402
2403            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2404                // NOTE: We ignore potential failures here during a system scan (like
2405                // the rest of the commands above) because there's precious little we
2406                // can do about it. A settings error is reported, though.
2407                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2408                        false /* boot complete */);
2409            }
2410
2411            // Now that we know all the packages we are keeping,
2412            // read and update their last usage times.
2413            mPackageUsage.readLP();
2414
2415            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2416                    SystemClock.uptimeMillis());
2417            Slog.i(TAG, "Time to scan packages: "
2418                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2419                    + " seconds");
2420
2421            // If the platform SDK has changed since the last time we booted,
2422            // we need to re-grant app permission to catch any new ones that
2423            // appear.  This is really a hack, and means that apps can in some
2424            // cases get permissions that the user didn't initially explicitly
2425            // allow...  it would be nice to have some better way to handle
2426            // this situation.
2427            int updateFlags = UPDATE_PERMISSIONS_ALL;
2428            if (ver.sdkVersion != mSdkVersion) {
2429                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2430                        + mSdkVersion + "; regranting permissions for internal storage");
2431                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2432            }
2433            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2434            ver.sdkVersion = mSdkVersion;
2435
2436            // If this is the first boot or an update from pre-M, and it is a normal
2437            // boot, then we need to initialize the default preferred apps across
2438            // all defined users.
2439            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2440                for (UserInfo user : sUserManager.getUsers(true)) {
2441                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2442                    applyFactoryDefaultBrowserLPw(user.id);
2443                    primeDomainVerificationsLPw(user.id);
2444                }
2445            }
2446
2447            // Prepare storage for system user really early during boot,
2448            // since core system apps like SettingsProvider and SystemUI
2449            // can't wait for user to start
2450            final int storageFlags;
2451            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2452                storageFlags = StorageManager.FLAG_STORAGE_DE;
2453            } else {
2454                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2455            }
2456            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2457                    storageFlags);
2458
2459            // If this is first boot after an OTA, and a normal boot, then
2460            // we need to clear code cache directories.
2461            if (mIsUpgrade && !onlyCore) {
2462                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2463                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2464                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2465                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2466                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2467                    }
2468                }
2469                ver.fingerprint = Build.FINGERPRINT;
2470            }
2471
2472            checkDefaultBrowser();
2473
2474            // clear only after permissions and other defaults have been updated
2475            mExistingSystemPackages.clear();
2476            mPromoteSystemApps = false;
2477
2478            // All the changes are done during package scanning.
2479            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2480
2481            // can downgrade to reader
2482            mSettings.writeLPr();
2483
2484            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2485                    SystemClock.uptimeMillis());
2486
2487            if (!mOnlyCore) {
2488                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2489                mRequiredInstallerPackage = getRequiredInstallerLPr();
2490                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2491                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2492                        mIntentFilterVerifierComponent);
2493            } else {
2494                mRequiredVerifierPackage = null;
2495                mRequiredInstallerPackage = null;
2496                mIntentFilterVerifierComponent = null;
2497                mIntentFilterVerifier = null;
2498            }
2499
2500            mInstallerService = new PackageInstallerService(context, this);
2501
2502            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2503            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2504            // both the installer and resolver must be present to enable ephemeral
2505            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2506                if (DEBUG_EPHEMERAL) {
2507                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2508                            + " installer:" + ephemeralInstallerComponent);
2509                }
2510                mEphemeralResolverComponent = ephemeralResolverComponent;
2511                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2512                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2513                mEphemeralResolverConnection =
2514                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2515            } else {
2516                if (DEBUG_EPHEMERAL) {
2517                    final String missingComponent =
2518                            (ephemeralResolverComponent == null)
2519                            ? (ephemeralInstallerComponent == null)
2520                                    ? "resolver and installer"
2521                                    : "resolver"
2522                            : "installer";
2523                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2524                }
2525                mEphemeralResolverComponent = null;
2526                mEphemeralInstallerComponent = null;
2527                mEphemeralResolverConnection = null;
2528            }
2529
2530            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2531        } // synchronized (mPackages)
2532        } // synchronized (mInstallLock)
2533
2534        // Now after opening every single application zip, make sure they
2535        // are all flushed.  Not really needed, but keeps things nice and
2536        // tidy.
2537        Runtime.getRuntime().gc();
2538
2539        // The initial scanning above does many calls into installd while
2540        // holding the mPackages lock, but we're mostly interested in yelling
2541        // once we have a booted system.
2542        mInstaller.setWarnIfHeld(mPackages);
2543
2544        // Expose private service for system components to use.
2545        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2546    }
2547
2548    @Override
2549    public boolean isFirstBoot() {
2550        return !mRestoredSettings;
2551    }
2552
2553    @Override
2554    public boolean isOnlyCoreApps() {
2555        return mOnlyCore;
2556    }
2557
2558    @Override
2559    public boolean isUpgrade() {
2560        return mIsUpgrade;
2561    }
2562
2563    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2564        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2565
2566        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2567                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2568                UserHandle.USER_SYSTEM);
2569        if (matches.size() == 1) {
2570            return matches.get(0).getComponentInfo().packageName;
2571        } else {
2572            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2573            return null;
2574        }
2575    }
2576
2577    private @NonNull String getRequiredInstallerLPr() {
2578        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2579        intent.addCategory(Intent.CATEGORY_DEFAULT);
2580        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2581
2582        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2583                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2584                UserHandle.USER_SYSTEM);
2585        if (matches.size() == 1) {
2586            return matches.get(0).getComponentInfo().packageName;
2587        } else {
2588            throw new RuntimeException("There must be exactly one installer; found " + matches);
2589        }
2590    }
2591
2592    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2593        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2594
2595        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2596                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2597                UserHandle.USER_SYSTEM);
2598        ResolveInfo best = null;
2599        final int N = matches.size();
2600        for (int i = 0; i < N; i++) {
2601            final ResolveInfo cur = matches.get(i);
2602            final String packageName = cur.getComponentInfo().packageName;
2603            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2604                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2605                continue;
2606            }
2607
2608            if (best == null || cur.priority > best.priority) {
2609                best = cur;
2610            }
2611        }
2612
2613        if (best != null) {
2614            return best.getComponentInfo().getComponentName();
2615        } else {
2616            throw new RuntimeException("There must be at least one intent filter verifier");
2617        }
2618    }
2619
2620    private @Nullable ComponentName getEphemeralResolverLPr() {
2621        final String[] packageArray =
2622                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2623        if (packageArray.length == 0) {
2624            if (DEBUG_EPHEMERAL) {
2625                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2626            }
2627            return null;
2628        }
2629
2630        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2631        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2632                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2633                UserHandle.USER_SYSTEM);
2634
2635        final int N = resolvers.size();
2636        if (N == 0) {
2637            if (DEBUG_EPHEMERAL) {
2638                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2639            }
2640            return null;
2641        }
2642
2643        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2644        for (int i = 0; i < N; i++) {
2645            final ResolveInfo info = resolvers.get(i);
2646
2647            if (info.serviceInfo == null) {
2648                continue;
2649            }
2650
2651            final String packageName = info.serviceInfo.packageName;
2652            if (!possiblePackages.contains(packageName)) {
2653                if (DEBUG_EPHEMERAL) {
2654                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2655                            + " pkg: " + packageName + ", info:" + info);
2656                }
2657                continue;
2658            }
2659
2660            if (DEBUG_EPHEMERAL) {
2661                Slog.v(TAG, "Ephemeral resolver found;"
2662                        + " pkg: " + packageName + ", info:" + info);
2663            }
2664            return new ComponentName(packageName, info.serviceInfo.name);
2665        }
2666        if (DEBUG_EPHEMERAL) {
2667            Slog.v(TAG, "Ephemeral resolver NOT found");
2668        }
2669        return null;
2670    }
2671
2672    private @Nullable ComponentName getEphemeralInstallerLPr() {
2673        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2674        intent.addCategory(Intent.CATEGORY_DEFAULT);
2675        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2676
2677        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2678                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2679                UserHandle.USER_SYSTEM);
2680        if (matches.size() == 0) {
2681            return null;
2682        } else if (matches.size() == 1) {
2683            return matches.get(0).getComponentInfo().getComponentName();
2684        } else {
2685            throw new RuntimeException(
2686                    "There must be at most one ephemeral installer; found " + matches);
2687        }
2688    }
2689
2690    private void primeDomainVerificationsLPw(int userId) {
2691        if (DEBUG_DOMAIN_VERIFICATION) {
2692            Slog.d(TAG, "Priming domain verifications in user " + userId);
2693        }
2694
2695        SystemConfig systemConfig = SystemConfig.getInstance();
2696        ArraySet<String> packages = systemConfig.getLinkedApps();
2697        ArraySet<String> domains = new ArraySet<String>();
2698
2699        for (String packageName : packages) {
2700            PackageParser.Package pkg = mPackages.get(packageName);
2701            if (pkg != null) {
2702                if (!pkg.isSystemApp()) {
2703                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2704                    continue;
2705                }
2706
2707                domains.clear();
2708                for (PackageParser.Activity a : pkg.activities) {
2709                    for (ActivityIntentInfo filter : a.intents) {
2710                        if (hasValidDomains(filter)) {
2711                            domains.addAll(filter.getHostsList());
2712                        }
2713                    }
2714                }
2715
2716                if (domains.size() > 0) {
2717                    if (DEBUG_DOMAIN_VERIFICATION) {
2718                        Slog.v(TAG, "      + " + packageName);
2719                    }
2720                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2721                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2722                    // and then 'always' in the per-user state actually used for intent resolution.
2723                    final IntentFilterVerificationInfo ivi;
2724                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2725                            new ArrayList<String>(domains));
2726                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2727                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2728                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2729                } else {
2730                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2731                            + "' does not handle web links");
2732                }
2733            } else {
2734                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2735            }
2736        }
2737
2738        scheduleWritePackageRestrictionsLocked(userId);
2739        scheduleWriteSettingsLocked();
2740    }
2741
2742    private void applyFactoryDefaultBrowserLPw(int userId) {
2743        // The default browser app's package name is stored in a string resource,
2744        // with a product-specific overlay used for vendor customization.
2745        String browserPkg = mContext.getResources().getString(
2746                com.android.internal.R.string.default_browser);
2747        if (!TextUtils.isEmpty(browserPkg)) {
2748            // non-empty string => required to be a known package
2749            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2750            if (ps == null) {
2751                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2752                browserPkg = null;
2753            } else {
2754                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2755            }
2756        }
2757
2758        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2759        // default.  If there's more than one, just leave everything alone.
2760        if (browserPkg == null) {
2761            calculateDefaultBrowserLPw(userId);
2762        }
2763    }
2764
2765    private void calculateDefaultBrowserLPw(int userId) {
2766        List<String> allBrowsers = resolveAllBrowserApps(userId);
2767        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2768        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2769    }
2770
2771    private List<String> resolveAllBrowserApps(int userId) {
2772        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2773        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2774                PackageManager.MATCH_ALL, userId);
2775
2776        final int count = list.size();
2777        List<String> result = new ArrayList<String>(count);
2778        for (int i=0; i<count; i++) {
2779            ResolveInfo info = list.get(i);
2780            if (info.activityInfo == null
2781                    || !info.handleAllWebDataURI
2782                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2783                    || result.contains(info.activityInfo.packageName)) {
2784                continue;
2785            }
2786            result.add(info.activityInfo.packageName);
2787        }
2788
2789        return result;
2790    }
2791
2792    private boolean packageIsBrowser(String packageName, int userId) {
2793        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2794                PackageManager.MATCH_ALL, userId);
2795        final int N = list.size();
2796        for (int i = 0; i < N; i++) {
2797            ResolveInfo info = list.get(i);
2798            if (packageName.equals(info.activityInfo.packageName)) {
2799                return true;
2800            }
2801        }
2802        return false;
2803    }
2804
2805    private void checkDefaultBrowser() {
2806        final int myUserId = UserHandle.myUserId();
2807        final String packageName = getDefaultBrowserPackageName(myUserId);
2808        if (packageName != null) {
2809            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2810            if (info == null) {
2811                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2812                synchronized (mPackages) {
2813                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2814                }
2815            }
2816        }
2817    }
2818
2819    @Override
2820    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2821            throws RemoteException {
2822        try {
2823            return super.onTransact(code, data, reply, flags);
2824        } catch (RuntimeException e) {
2825            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2826                Slog.wtf(TAG, "Package Manager Crash", e);
2827            }
2828            throw e;
2829        }
2830    }
2831
2832    void cleanupInstallFailedPackage(PackageSetting ps) {
2833        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2834
2835        removeDataDirsLI(ps.volumeUuid, ps.name);
2836        if (ps.codePath != null) {
2837            removeCodePathLI(ps.codePath);
2838        }
2839        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2840            if (ps.resourcePath.isDirectory()) {
2841                FileUtils.deleteContents(ps.resourcePath);
2842            }
2843            ps.resourcePath.delete();
2844        }
2845        mSettings.removePackageLPw(ps.name);
2846    }
2847
2848    static int[] appendInts(int[] cur, int[] add) {
2849        if (add == null) return cur;
2850        if (cur == null) return add;
2851        final int N = add.length;
2852        for (int i=0; i<N; i++) {
2853            cur = appendInt(cur, add[i]);
2854        }
2855        return cur;
2856    }
2857
2858    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2859        if (!sUserManager.exists(userId)) return null;
2860        final PackageSetting ps = (PackageSetting) p.mExtras;
2861        if (ps == null) {
2862            return null;
2863        }
2864
2865        final PermissionsState permissionsState = ps.getPermissionsState();
2866
2867        final int[] gids = permissionsState.computeGids(userId);
2868        final Set<String> permissions = permissionsState.getPermissions(userId);
2869        final PackageUserState state = ps.readUserState(userId);
2870
2871        return PackageParser.generatePackageInfo(p, gids, flags,
2872                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2873    }
2874
2875    @Override
2876    public void checkPackageStartable(String packageName, int userId) {
2877        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2878
2879        synchronized (mPackages) {
2880            final PackageSetting ps = mSettings.mPackages.get(packageName);
2881            if (ps == null) {
2882                throw new SecurityException("Package " + packageName + " was not found!");
2883            }
2884
2885            if (mSafeMode && !ps.isSystem()) {
2886                throw new SecurityException("Package " + packageName + " not a system app!");
2887            }
2888
2889            if (ps.frozen) {
2890                throw new SecurityException("Package " + packageName + " is currently frozen!");
2891            }
2892
2893            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
2894                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
2895                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2896            }
2897        }
2898    }
2899
2900    @Override
2901    public boolean isPackageAvailable(String packageName, int userId) {
2902        if (!sUserManager.exists(userId)) return false;
2903        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2904                false /* requireFullPermission */, false /* checkShell */, "is package available");
2905        synchronized (mPackages) {
2906            PackageParser.Package p = mPackages.get(packageName);
2907            if (p != null) {
2908                final PackageSetting ps = (PackageSetting) p.mExtras;
2909                if (ps != null) {
2910                    final PackageUserState state = ps.readUserState(userId);
2911                    if (state != null) {
2912                        return PackageParser.isAvailable(state);
2913                    }
2914                }
2915            }
2916        }
2917        return false;
2918    }
2919
2920    @Override
2921    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2922        if (!sUserManager.exists(userId)) return null;
2923        flags = updateFlagsForPackage(flags, userId, packageName);
2924        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2925                false /* requireFullPermission */, false /* checkShell */, "get package info");
2926        // reader
2927        synchronized (mPackages) {
2928            PackageParser.Package p = mPackages.get(packageName);
2929            if (DEBUG_PACKAGE_INFO)
2930                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2931            if (p != null) {
2932                return generatePackageInfo(p, flags, userId);
2933            }
2934            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2935                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2936            }
2937        }
2938        return null;
2939    }
2940
2941    @Override
2942    public String[] currentToCanonicalPackageNames(String[] names) {
2943        String[] out = new String[names.length];
2944        // reader
2945        synchronized (mPackages) {
2946            for (int i=names.length-1; i>=0; i--) {
2947                PackageSetting ps = mSettings.mPackages.get(names[i]);
2948                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2949            }
2950        }
2951        return out;
2952    }
2953
2954    @Override
2955    public String[] canonicalToCurrentPackageNames(String[] names) {
2956        String[] out = new String[names.length];
2957        // reader
2958        synchronized (mPackages) {
2959            for (int i=names.length-1; i>=0; i--) {
2960                String cur = mSettings.mRenamedPackages.get(names[i]);
2961                out[i] = cur != null ? cur : names[i];
2962            }
2963        }
2964        return out;
2965    }
2966
2967    @Override
2968    public int getPackageUid(String packageName, int flags, int userId) {
2969        if (!sUserManager.exists(userId)) return -1;
2970        flags = updateFlagsForPackage(flags, userId, packageName);
2971        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2972                false /* requireFullPermission */, false /* checkShell */, "get package uid");
2973
2974        // reader
2975        synchronized (mPackages) {
2976            final PackageParser.Package p = mPackages.get(packageName);
2977            if (p != null && p.isMatch(flags)) {
2978                return UserHandle.getUid(userId, p.applicationInfo.uid);
2979            }
2980            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
2981                final PackageSetting ps = mSettings.mPackages.get(packageName);
2982                if (ps != null && ps.isMatch(flags)) {
2983                    return UserHandle.getUid(userId, ps.appId);
2984                }
2985            }
2986        }
2987
2988        return -1;
2989    }
2990
2991    @Override
2992    public int[] getPackageGids(String packageName, int flags, int userId) {
2993        if (!sUserManager.exists(userId)) return null;
2994        flags = updateFlagsForPackage(flags, userId, packageName);
2995        enforceCrossUserPermission(Binder.getCallingUid(), userId,
2996                false /* requireFullPermission */, false /* checkShell */,
2997                "getPackageGids");
2998
2999        // reader
3000        synchronized (mPackages) {
3001            final PackageParser.Package p = mPackages.get(packageName);
3002            if (p != null && p.isMatch(flags)) {
3003                PackageSetting ps = (PackageSetting) p.mExtras;
3004                return ps.getPermissionsState().computeGids(userId);
3005            }
3006            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3007                final PackageSetting ps = mSettings.mPackages.get(packageName);
3008                if (ps != null && ps.isMatch(flags)) {
3009                    return ps.getPermissionsState().computeGids(userId);
3010                }
3011            }
3012        }
3013
3014        return null;
3015    }
3016
3017    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3018        if (bp.perm != null) {
3019            return PackageParser.generatePermissionInfo(bp.perm, flags);
3020        }
3021        PermissionInfo pi = new PermissionInfo();
3022        pi.name = bp.name;
3023        pi.packageName = bp.sourcePackage;
3024        pi.nonLocalizedLabel = bp.name;
3025        pi.protectionLevel = bp.protectionLevel;
3026        return pi;
3027    }
3028
3029    @Override
3030    public PermissionInfo getPermissionInfo(String name, int flags) {
3031        // reader
3032        synchronized (mPackages) {
3033            final BasePermission p = mSettings.mPermissions.get(name);
3034            if (p != null) {
3035                return generatePermissionInfo(p, flags);
3036            }
3037            return null;
3038        }
3039    }
3040
3041    @Override
3042    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3043            int flags) {
3044        // reader
3045        synchronized (mPackages) {
3046            if (group != null && !mPermissionGroups.containsKey(group)) {
3047                // This is thrown as NameNotFoundException
3048                return null;
3049            }
3050
3051            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3052            for (BasePermission p : mSettings.mPermissions.values()) {
3053                if (group == null) {
3054                    if (p.perm == null || p.perm.info.group == null) {
3055                        out.add(generatePermissionInfo(p, flags));
3056                    }
3057                } else {
3058                    if (p.perm != null && group.equals(p.perm.info.group)) {
3059                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3060                    }
3061                }
3062            }
3063            return new ParceledListSlice<>(out);
3064        }
3065    }
3066
3067    @Override
3068    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3069        // reader
3070        synchronized (mPackages) {
3071            return PackageParser.generatePermissionGroupInfo(
3072                    mPermissionGroups.get(name), flags);
3073        }
3074    }
3075
3076    @Override
3077    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3078        // reader
3079        synchronized (mPackages) {
3080            final int N = mPermissionGroups.size();
3081            ArrayList<PermissionGroupInfo> out
3082                    = new ArrayList<PermissionGroupInfo>(N);
3083            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3084                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3085            }
3086            return new ParceledListSlice<>(out);
3087        }
3088    }
3089
3090    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3091            int userId) {
3092        if (!sUserManager.exists(userId)) return null;
3093        PackageSetting ps = mSettings.mPackages.get(packageName);
3094        if (ps != null) {
3095            if (ps.pkg == null) {
3096                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
3097                        flags, userId);
3098                if (pInfo != null) {
3099                    return pInfo.applicationInfo;
3100                }
3101                return null;
3102            }
3103            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3104                    ps.readUserState(userId), userId);
3105        }
3106        return null;
3107    }
3108
3109    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
3110            int userId) {
3111        if (!sUserManager.exists(userId)) return null;
3112        PackageSetting ps = mSettings.mPackages.get(packageName);
3113        if (ps != null) {
3114            PackageParser.Package pkg = ps.pkg;
3115            if (pkg == null) {
3116                if ((flags & MATCH_UNINSTALLED_PACKAGES) == 0) {
3117                    return null;
3118                }
3119                // Only data remains, so we aren't worried about code paths
3120                pkg = new PackageParser.Package(packageName);
3121                pkg.applicationInfo.packageName = packageName;
3122                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
3123                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
3124                pkg.applicationInfo.uid = ps.appId;
3125                pkg.applicationInfo.initForUser(userId);
3126                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
3127                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
3128            }
3129            return generatePackageInfo(pkg, flags, userId);
3130        }
3131        return null;
3132    }
3133
3134    @Override
3135    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3136        if (!sUserManager.exists(userId)) return null;
3137        flags = updateFlagsForApplication(flags, userId, packageName);
3138        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3139                false /* requireFullPermission */, false /* checkShell */, "get application info");
3140        // writer
3141        synchronized (mPackages) {
3142            PackageParser.Package p = mPackages.get(packageName);
3143            if (DEBUG_PACKAGE_INFO) Log.v(
3144                    TAG, "getApplicationInfo " + packageName
3145                    + ": " + p);
3146            if (p != null) {
3147                PackageSetting ps = mSettings.mPackages.get(packageName);
3148                if (ps == null) return null;
3149                // Note: isEnabledLP() does not apply here - always return info
3150                return PackageParser.generateApplicationInfo(
3151                        p, flags, ps.readUserState(userId), userId);
3152            }
3153            if ("android".equals(packageName)||"system".equals(packageName)) {
3154                return mAndroidApplication;
3155            }
3156            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3157                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3158            }
3159        }
3160        return null;
3161    }
3162
3163    @Override
3164    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3165            final IPackageDataObserver observer) {
3166        mContext.enforceCallingOrSelfPermission(
3167                android.Manifest.permission.CLEAR_APP_CACHE, null);
3168        // Queue up an async operation since clearing cache may take a little while.
3169        mHandler.post(new Runnable() {
3170            public void run() {
3171                mHandler.removeCallbacks(this);
3172                boolean success = true;
3173                synchronized (mInstallLock) {
3174                    try {
3175                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3176                    } catch (InstallerException e) {
3177                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3178                        success = false;
3179                    }
3180                }
3181                if (observer != null) {
3182                    try {
3183                        observer.onRemoveCompleted(null, success);
3184                    } catch (RemoteException e) {
3185                        Slog.w(TAG, "RemoveException when invoking call back");
3186                    }
3187                }
3188            }
3189        });
3190    }
3191
3192    @Override
3193    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3194            final IntentSender pi) {
3195        mContext.enforceCallingOrSelfPermission(
3196                android.Manifest.permission.CLEAR_APP_CACHE, null);
3197        // Queue up an async operation since clearing cache may take a little while.
3198        mHandler.post(new Runnable() {
3199            public void run() {
3200                mHandler.removeCallbacks(this);
3201                boolean success = true;
3202                synchronized (mInstallLock) {
3203                    try {
3204                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3205                    } catch (InstallerException e) {
3206                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3207                        success = false;
3208                    }
3209                }
3210                if(pi != null) {
3211                    try {
3212                        // Callback via pending intent
3213                        int code = success ? 1 : 0;
3214                        pi.sendIntent(null, code, null,
3215                                null, null);
3216                    } catch (SendIntentException e1) {
3217                        Slog.i(TAG, "Failed to send pending intent");
3218                    }
3219                }
3220            }
3221        });
3222    }
3223
3224    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3225        synchronized (mInstallLock) {
3226            try {
3227                mInstaller.freeCache(volumeUuid, freeStorageSize);
3228            } catch (InstallerException e) {
3229                throw new IOException("Failed to free enough space", e);
3230            }
3231        }
3232    }
3233
3234    /**
3235     * Return if the user key is currently unlocked.
3236     */
3237    private boolean isUserKeyUnlocked(int userId) {
3238        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3239            final IMountService mount = IMountService.Stub
3240                    .asInterface(ServiceManager.getService("mount"));
3241            if (mount == null) {
3242                Slog.w(TAG, "Early during boot, assuming locked");
3243                return false;
3244            }
3245            final long token = Binder.clearCallingIdentity();
3246            try {
3247                return mount.isUserKeyUnlocked(userId);
3248            } catch (RemoteException e) {
3249                throw e.rethrowAsRuntimeException();
3250            } finally {
3251                Binder.restoreCallingIdentity(token);
3252            }
3253        } else {
3254            return true;
3255        }
3256    }
3257
3258    /**
3259     * Update given flags based on encryption status of current user.
3260     */
3261    private int updateFlags(int flags, int userId) {
3262        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3263                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3264            // Caller expressed an explicit opinion about what encryption
3265            // aware/unaware components they want to see, so fall through and
3266            // give them what they want
3267        } else {
3268            // Caller expressed no opinion, so match based on user state
3269            if (isUserKeyUnlocked(userId)) {
3270                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3271            } else {
3272                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3273            }
3274        }
3275        return flags;
3276    }
3277
3278    /**
3279     * Update given flags when being used to request {@link PackageInfo}.
3280     */
3281    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3282        boolean triaged = true;
3283        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3284                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3285            // Caller is asking for component details, so they'd better be
3286            // asking for specific encryption matching behavior, or be triaged
3287            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3288                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3289                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3290                triaged = false;
3291            }
3292        }
3293        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3294                | PackageManager.MATCH_SYSTEM_ONLY
3295                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3296            triaged = false;
3297        }
3298        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3299            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3300                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3301        }
3302        return updateFlags(flags, userId);
3303    }
3304
3305    /**
3306     * Update given flags when being used to request {@link ApplicationInfo}.
3307     */
3308    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3309        return updateFlagsForPackage(flags, userId, cookie);
3310    }
3311
3312    /**
3313     * Update given flags when being used to request {@link ComponentInfo}.
3314     */
3315    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3316        if (cookie instanceof Intent) {
3317            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3318                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3319            }
3320        }
3321
3322        boolean triaged = true;
3323        // Caller is asking for component details, so they'd better be
3324        // asking for specific encryption matching behavior, or be triaged
3325        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3326                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3327                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3328            triaged = false;
3329        }
3330        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3331            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3332                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3333        }
3334
3335        return updateFlags(flags, userId);
3336    }
3337
3338    /**
3339     * Update given flags when being used to request {@link ResolveInfo}.
3340     */
3341    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3342        // Safe mode means we shouldn't match any third-party components
3343        if (mSafeMode) {
3344            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3345        }
3346
3347        return updateFlagsForComponent(flags, userId, cookie);
3348    }
3349
3350    @Override
3351    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3352        if (!sUserManager.exists(userId)) return null;
3353        flags = updateFlagsForComponent(flags, userId, component);
3354        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3355                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3356        synchronized (mPackages) {
3357            PackageParser.Activity a = mActivities.mActivities.get(component);
3358
3359            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3360            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3361                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3362                if (ps == null) return null;
3363                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3364                        userId);
3365            }
3366            if (mResolveComponentName.equals(component)) {
3367                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3368                        new PackageUserState(), userId);
3369            }
3370        }
3371        return null;
3372    }
3373
3374    @Override
3375    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3376            String resolvedType) {
3377        synchronized (mPackages) {
3378            if (component.equals(mResolveComponentName)) {
3379                // The resolver supports EVERYTHING!
3380                return true;
3381            }
3382            PackageParser.Activity a = mActivities.mActivities.get(component);
3383            if (a == null) {
3384                return false;
3385            }
3386            for (int i=0; i<a.intents.size(); i++) {
3387                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3388                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3389                    return true;
3390                }
3391            }
3392            return false;
3393        }
3394    }
3395
3396    @Override
3397    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3398        if (!sUserManager.exists(userId)) return null;
3399        flags = updateFlagsForComponent(flags, userId, component);
3400        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3401                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3402        synchronized (mPackages) {
3403            PackageParser.Activity a = mReceivers.mActivities.get(component);
3404            if (DEBUG_PACKAGE_INFO) Log.v(
3405                TAG, "getReceiverInfo " + component + ": " + a);
3406            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3407                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3408                if (ps == null) return null;
3409                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3410                        userId);
3411            }
3412        }
3413        return null;
3414    }
3415
3416    @Override
3417    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3418        if (!sUserManager.exists(userId)) return null;
3419        flags = updateFlagsForComponent(flags, userId, component);
3420        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3421                false /* requireFullPermission */, false /* checkShell */, "get service info");
3422        synchronized (mPackages) {
3423            PackageParser.Service s = mServices.mServices.get(component);
3424            if (DEBUG_PACKAGE_INFO) Log.v(
3425                TAG, "getServiceInfo " + component + ": " + s);
3426            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3427                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3428                if (ps == null) return null;
3429                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3430                        userId);
3431            }
3432        }
3433        return null;
3434    }
3435
3436    @Override
3437    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3438        if (!sUserManager.exists(userId)) return null;
3439        flags = updateFlagsForComponent(flags, userId, component);
3440        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3441                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3442        synchronized (mPackages) {
3443            PackageParser.Provider p = mProviders.mProviders.get(component);
3444            if (DEBUG_PACKAGE_INFO) Log.v(
3445                TAG, "getProviderInfo " + component + ": " + p);
3446            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3447                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3448                if (ps == null) return null;
3449                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3450                        userId);
3451            }
3452        }
3453        return null;
3454    }
3455
3456    @Override
3457    public String[] getSystemSharedLibraryNames() {
3458        Set<String> libSet;
3459        synchronized (mPackages) {
3460            libSet = mSharedLibraries.keySet();
3461            int size = libSet.size();
3462            if (size > 0) {
3463                String[] libs = new String[size];
3464                libSet.toArray(libs);
3465                return libs;
3466            }
3467        }
3468        return null;
3469    }
3470
3471    @Override
3472    public @Nullable String getServicesSystemSharedLibraryPackageName() {
3473        synchronized (mPackages) {
3474            SharedLibraryEntry libraryEntry = mSharedLibraries.get(
3475                    PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
3476            if (libraryEntry != null) {
3477                return libraryEntry.apk;
3478            }
3479        }
3480        return null;
3481    }
3482
3483    @Override
3484    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3485        synchronized (mPackages) {
3486            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3487
3488            final FeatureInfo fi = new FeatureInfo();
3489            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3490                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3491            res.add(fi);
3492
3493            return new ParceledListSlice<>(res);
3494        }
3495    }
3496
3497    @Override
3498    public boolean hasSystemFeature(String name, int version) {
3499        synchronized (mPackages) {
3500            final FeatureInfo feat = mAvailableFeatures.get(name);
3501            if (feat == null) {
3502                return false;
3503            } else {
3504                return feat.version >= version;
3505            }
3506        }
3507    }
3508
3509    @Override
3510    public int checkPermission(String permName, String pkgName, int userId) {
3511        if (!sUserManager.exists(userId)) {
3512            return PackageManager.PERMISSION_DENIED;
3513        }
3514
3515        synchronized (mPackages) {
3516            final PackageParser.Package p = mPackages.get(pkgName);
3517            if (p != null && p.mExtras != null) {
3518                final PackageSetting ps = (PackageSetting) p.mExtras;
3519                final PermissionsState permissionsState = ps.getPermissionsState();
3520                if (permissionsState.hasPermission(permName, userId)) {
3521                    return PackageManager.PERMISSION_GRANTED;
3522                }
3523                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3524                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3525                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3526                    return PackageManager.PERMISSION_GRANTED;
3527                }
3528            }
3529        }
3530
3531        return PackageManager.PERMISSION_DENIED;
3532    }
3533
3534    @Override
3535    public int checkUidPermission(String permName, int uid) {
3536        final int userId = UserHandle.getUserId(uid);
3537
3538        if (!sUserManager.exists(userId)) {
3539            return PackageManager.PERMISSION_DENIED;
3540        }
3541
3542        synchronized (mPackages) {
3543            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3544            if (obj != null) {
3545                final SettingBase ps = (SettingBase) obj;
3546                final PermissionsState permissionsState = ps.getPermissionsState();
3547                if (permissionsState.hasPermission(permName, userId)) {
3548                    return PackageManager.PERMISSION_GRANTED;
3549                }
3550                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3551                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3552                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3553                    return PackageManager.PERMISSION_GRANTED;
3554                }
3555            } else {
3556                ArraySet<String> perms = mSystemPermissions.get(uid);
3557                if (perms != null) {
3558                    if (perms.contains(permName)) {
3559                        return PackageManager.PERMISSION_GRANTED;
3560                    }
3561                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3562                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3563                        return PackageManager.PERMISSION_GRANTED;
3564                    }
3565                }
3566            }
3567        }
3568
3569        return PackageManager.PERMISSION_DENIED;
3570    }
3571
3572    @Override
3573    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3574        if (UserHandle.getCallingUserId() != userId) {
3575            mContext.enforceCallingPermission(
3576                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3577                    "isPermissionRevokedByPolicy for user " + userId);
3578        }
3579
3580        if (checkPermission(permission, packageName, userId)
3581                == PackageManager.PERMISSION_GRANTED) {
3582            return false;
3583        }
3584
3585        final long identity = Binder.clearCallingIdentity();
3586        try {
3587            final int flags = getPermissionFlags(permission, packageName, userId);
3588            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3589        } finally {
3590            Binder.restoreCallingIdentity(identity);
3591        }
3592    }
3593
3594    @Override
3595    public String getPermissionControllerPackageName() {
3596        synchronized (mPackages) {
3597            return mRequiredInstallerPackage;
3598        }
3599    }
3600
3601    /**
3602     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3603     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3604     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3605     * @param message the message to log on security exception
3606     */
3607    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3608            boolean checkShell, String message) {
3609        if (userId < 0) {
3610            throw new IllegalArgumentException("Invalid userId " + userId);
3611        }
3612        if (checkShell) {
3613            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3614        }
3615        if (userId == UserHandle.getUserId(callingUid)) return;
3616        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3617            if (requireFullPermission) {
3618                mContext.enforceCallingOrSelfPermission(
3619                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3620            } else {
3621                try {
3622                    mContext.enforceCallingOrSelfPermission(
3623                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3624                } catch (SecurityException se) {
3625                    mContext.enforceCallingOrSelfPermission(
3626                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3627                }
3628            }
3629        }
3630    }
3631
3632    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3633        if (callingUid == Process.SHELL_UID) {
3634            if (userHandle >= 0
3635                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3636                throw new SecurityException("Shell does not have permission to access user "
3637                        + userHandle);
3638            } else if (userHandle < 0) {
3639                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3640                        + Debug.getCallers(3));
3641            }
3642        }
3643    }
3644
3645    private BasePermission findPermissionTreeLP(String permName) {
3646        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3647            if (permName.startsWith(bp.name) &&
3648                    permName.length() > bp.name.length() &&
3649                    permName.charAt(bp.name.length()) == '.') {
3650                return bp;
3651            }
3652        }
3653        return null;
3654    }
3655
3656    private BasePermission checkPermissionTreeLP(String permName) {
3657        if (permName != null) {
3658            BasePermission bp = findPermissionTreeLP(permName);
3659            if (bp != null) {
3660                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3661                    return bp;
3662                }
3663                throw new SecurityException("Calling uid "
3664                        + Binder.getCallingUid()
3665                        + " is not allowed to add to permission tree "
3666                        + bp.name + " owned by uid " + bp.uid);
3667            }
3668        }
3669        throw new SecurityException("No permission tree found for " + permName);
3670    }
3671
3672    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3673        if (s1 == null) {
3674            return s2 == null;
3675        }
3676        if (s2 == null) {
3677            return false;
3678        }
3679        if (s1.getClass() != s2.getClass()) {
3680            return false;
3681        }
3682        return s1.equals(s2);
3683    }
3684
3685    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3686        if (pi1.icon != pi2.icon) return false;
3687        if (pi1.logo != pi2.logo) return false;
3688        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3689        if (!compareStrings(pi1.name, pi2.name)) return false;
3690        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3691        // We'll take care of setting this one.
3692        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3693        // These are not currently stored in settings.
3694        //if (!compareStrings(pi1.group, pi2.group)) return false;
3695        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3696        //if (pi1.labelRes != pi2.labelRes) return false;
3697        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3698        return true;
3699    }
3700
3701    int permissionInfoFootprint(PermissionInfo info) {
3702        int size = info.name.length();
3703        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3704        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3705        return size;
3706    }
3707
3708    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3709        int size = 0;
3710        for (BasePermission perm : mSettings.mPermissions.values()) {
3711            if (perm.uid == tree.uid) {
3712                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3713            }
3714        }
3715        return size;
3716    }
3717
3718    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3719        // We calculate the max size of permissions defined by this uid and throw
3720        // if that plus the size of 'info' would exceed our stated maximum.
3721        if (tree.uid != Process.SYSTEM_UID) {
3722            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3723            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3724                throw new SecurityException("Permission tree size cap exceeded");
3725            }
3726        }
3727    }
3728
3729    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3730        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3731            throw new SecurityException("Label must be specified in permission");
3732        }
3733        BasePermission tree = checkPermissionTreeLP(info.name);
3734        BasePermission bp = mSettings.mPermissions.get(info.name);
3735        boolean added = bp == null;
3736        boolean changed = true;
3737        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3738        if (added) {
3739            enforcePermissionCapLocked(info, tree);
3740            bp = new BasePermission(info.name, tree.sourcePackage,
3741                    BasePermission.TYPE_DYNAMIC);
3742        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3743            throw new SecurityException(
3744                    "Not allowed to modify non-dynamic permission "
3745                    + info.name);
3746        } else {
3747            if (bp.protectionLevel == fixedLevel
3748                    && bp.perm.owner.equals(tree.perm.owner)
3749                    && bp.uid == tree.uid
3750                    && comparePermissionInfos(bp.perm.info, info)) {
3751                changed = false;
3752            }
3753        }
3754        bp.protectionLevel = fixedLevel;
3755        info = new PermissionInfo(info);
3756        info.protectionLevel = fixedLevel;
3757        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3758        bp.perm.info.packageName = tree.perm.info.packageName;
3759        bp.uid = tree.uid;
3760        if (added) {
3761            mSettings.mPermissions.put(info.name, bp);
3762        }
3763        if (changed) {
3764            if (!async) {
3765                mSettings.writeLPr();
3766            } else {
3767                scheduleWriteSettingsLocked();
3768            }
3769        }
3770        return added;
3771    }
3772
3773    @Override
3774    public boolean addPermission(PermissionInfo info) {
3775        synchronized (mPackages) {
3776            return addPermissionLocked(info, false);
3777        }
3778    }
3779
3780    @Override
3781    public boolean addPermissionAsync(PermissionInfo info) {
3782        synchronized (mPackages) {
3783            return addPermissionLocked(info, true);
3784        }
3785    }
3786
3787    @Override
3788    public void removePermission(String name) {
3789        synchronized (mPackages) {
3790            checkPermissionTreeLP(name);
3791            BasePermission bp = mSettings.mPermissions.get(name);
3792            if (bp != null) {
3793                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3794                    throw new SecurityException(
3795                            "Not allowed to modify non-dynamic permission "
3796                            + name);
3797                }
3798                mSettings.mPermissions.remove(name);
3799                mSettings.writeLPr();
3800            }
3801        }
3802    }
3803
3804    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3805            BasePermission bp) {
3806        int index = pkg.requestedPermissions.indexOf(bp.name);
3807        if (index == -1) {
3808            throw new SecurityException("Package " + pkg.packageName
3809                    + " has not requested permission " + bp.name);
3810        }
3811        if (!bp.isRuntime() && !bp.isDevelopment()) {
3812            throw new SecurityException("Permission " + bp.name
3813                    + " is not a changeable permission type");
3814        }
3815    }
3816
3817    @Override
3818    public void grantRuntimePermission(String packageName, String name, final int userId) {
3819        if (!sUserManager.exists(userId)) {
3820            Log.e(TAG, "No such user:" + userId);
3821            return;
3822        }
3823
3824        mContext.enforceCallingOrSelfPermission(
3825                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3826                "grantRuntimePermission");
3827
3828        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3829                true /* requireFullPermission */, true /* checkShell */,
3830                "grantRuntimePermission");
3831
3832        final int uid;
3833        final SettingBase sb;
3834
3835        synchronized (mPackages) {
3836            final PackageParser.Package pkg = mPackages.get(packageName);
3837            if (pkg == null) {
3838                throw new IllegalArgumentException("Unknown package: " + packageName);
3839            }
3840
3841            final BasePermission bp = mSettings.mPermissions.get(name);
3842            if (bp == null) {
3843                throw new IllegalArgumentException("Unknown permission: " + name);
3844            }
3845
3846            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3847
3848            // If a permission review is required for legacy apps we represent
3849            // their permissions as always granted runtime ones since we need
3850            // to keep the review required permission flag per user while an
3851            // install permission's state is shared across all users.
3852            if (Build.PERMISSIONS_REVIEW_REQUIRED
3853                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3854                    && bp.isRuntime()) {
3855                return;
3856            }
3857
3858            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3859            sb = (SettingBase) pkg.mExtras;
3860            if (sb == null) {
3861                throw new IllegalArgumentException("Unknown package: " + packageName);
3862            }
3863
3864            final PermissionsState permissionsState = sb.getPermissionsState();
3865
3866            final int flags = permissionsState.getPermissionFlags(name, userId);
3867            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3868                throw new SecurityException("Cannot grant system fixed permission "
3869                        + name + " for package " + packageName);
3870            }
3871
3872            if (bp.isDevelopment()) {
3873                // Development permissions must be handled specially, since they are not
3874                // normal runtime permissions.  For now they apply to all users.
3875                if (permissionsState.grantInstallPermission(bp) !=
3876                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3877                    scheduleWriteSettingsLocked();
3878                }
3879                return;
3880            }
3881
3882            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3883                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3884                return;
3885            }
3886
3887            final int result = permissionsState.grantRuntimePermission(bp, userId);
3888            switch (result) {
3889                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3890                    return;
3891                }
3892
3893                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3894                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3895                    mHandler.post(new Runnable() {
3896                        @Override
3897                        public void run() {
3898                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3899                        }
3900                    });
3901                }
3902                break;
3903            }
3904
3905            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3906
3907            // Not critical if that is lost - app has to request again.
3908            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3909        }
3910
3911        // Only need to do this if user is initialized. Otherwise it's a new user
3912        // and there are no processes running as the user yet and there's no need
3913        // to make an expensive call to remount processes for the changed permissions.
3914        if (READ_EXTERNAL_STORAGE.equals(name)
3915                || WRITE_EXTERNAL_STORAGE.equals(name)) {
3916            final long token = Binder.clearCallingIdentity();
3917            try {
3918                if (sUserManager.isInitialized(userId)) {
3919                    MountServiceInternal mountServiceInternal = LocalServices.getService(
3920                            MountServiceInternal.class);
3921                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
3922                }
3923            } finally {
3924                Binder.restoreCallingIdentity(token);
3925            }
3926        }
3927    }
3928
3929    @Override
3930    public void revokeRuntimePermission(String packageName, String name, int userId) {
3931        if (!sUserManager.exists(userId)) {
3932            Log.e(TAG, "No such user:" + userId);
3933            return;
3934        }
3935
3936        mContext.enforceCallingOrSelfPermission(
3937                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
3938                "revokeRuntimePermission");
3939
3940        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3941                true /* requireFullPermission */, true /* checkShell */,
3942                "revokeRuntimePermission");
3943
3944        final int appId;
3945
3946        synchronized (mPackages) {
3947            final PackageParser.Package pkg = mPackages.get(packageName);
3948            if (pkg == null) {
3949                throw new IllegalArgumentException("Unknown package: " + packageName);
3950            }
3951
3952            final BasePermission bp = mSettings.mPermissions.get(name);
3953            if (bp == null) {
3954                throw new IllegalArgumentException("Unknown permission: " + name);
3955            }
3956
3957            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3958
3959            // If a permission review is required for legacy apps we represent
3960            // their permissions as always granted runtime ones since we need
3961            // to keep the review required permission flag per user while an
3962            // install permission's state is shared across all users.
3963            if (Build.PERMISSIONS_REVIEW_REQUIRED
3964                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3965                    && bp.isRuntime()) {
3966                return;
3967            }
3968
3969            SettingBase sb = (SettingBase) pkg.mExtras;
3970            if (sb == null) {
3971                throw new IllegalArgumentException("Unknown package: " + packageName);
3972            }
3973
3974            final PermissionsState permissionsState = sb.getPermissionsState();
3975
3976            final int flags = permissionsState.getPermissionFlags(name, userId);
3977            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3978                throw new SecurityException("Cannot revoke system fixed permission "
3979                        + name + " for package " + packageName);
3980            }
3981
3982            if (bp.isDevelopment()) {
3983                // Development permissions must be handled specially, since they are not
3984                // normal runtime permissions.  For now they apply to all users.
3985                if (permissionsState.revokeInstallPermission(bp) !=
3986                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3987                    scheduleWriteSettingsLocked();
3988                }
3989                return;
3990            }
3991
3992            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3993                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3994                return;
3995            }
3996
3997            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
3998
3999            // Critical, after this call app should never have the permission.
4000            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4001
4002            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4003        }
4004
4005        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4006    }
4007
4008    @Override
4009    public void resetRuntimePermissions() {
4010        mContext.enforceCallingOrSelfPermission(
4011                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4012                "revokeRuntimePermission");
4013
4014        int callingUid = Binder.getCallingUid();
4015        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4016            mContext.enforceCallingOrSelfPermission(
4017                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4018                    "resetRuntimePermissions");
4019        }
4020
4021        synchronized (mPackages) {
4022            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4023            for (int userId : UserManagerService.getInstance().getUserIds()) {
4024                final int packageCount = mPackages.size();
4025                for (int i = 0; i < packageCount; i++) {
4026                    PackageParser.Package pkg = mPackages.valueAt(i);
4027                    if (!(pkg.mExtras instanceof PackageSetting)) {
4028                        continue;
4029                    }
4030                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4031                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4032                }
4033            }
4034        }
4035    }
4036
4037    @Override
4038    public int getPermissionFlags(String name, String packageName, int userId) {
4039        if (!sUserManager.exists(userId)) {
4040            return 0;
4041        }
4042
4043        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4044
4045        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4046                true /* requireFullPermission */, false /* checkShell */,
4047                "getPermissionFlags");
4048
4049        synchronized (mPackages) {
4050            final PackageParser.Package pkg = mPackages.get(packageName);
4051            if (pkg == null) {
4052                throw new IllegalArgumentException("Unknown package: " + packageName);
4053            }
4054
4055            final BasePermission bp = mSettings.mPermissions.get(name);
4056            if (bp == null) {
4057                throw new IllegalArgumentException("Unknown permission: " + name);
4058            }
4059
4060            SettingBase sb = (SettingBase) pkg.mExtras;
4061            if (sb == null) {
4062                throw new IllegalArgumentException("Unknown package: " + packageName);
4063            }
4064
4065            PermissionsState permissionsState = sb.getPermissionsState();
4066            return permissionsState.getPermissionFlags(name, userId);
4067        }
4068    }
4069
4070    @Override
4071    public void updatePermissionFlags(String name, String packageName, int flagMask,
4072            int flagValues, int userId) {
4073        if (!sUserManager.exists(userId)) {
4074            return;
4075        }
4076
4077        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4078
4079        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4080                true /* requireFullPermission */, true /* checkShell */,
4081                "updatePermissionFlags");
4082
4083        // Only the system can change these flags and nothing else.
4084        if (getCallingUid() != Process.SYSTEM_UID) {
4085            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4086            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4087            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4088            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4089            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4090        }
4091
4092        synchronized (mPackages) {
4093            final PackageParser.Package pkg = mPackages.get(packageName);
4094            if (pkg == null) {
4095                throw new IllegalArgumentException("Unknown package: " + packageName);
4096            }
4097
4098            final BasePermission bp = mSettings.mPermissions.get(name);
4099            if (bp == null) {
4100                throw new IllegalArgumentException("Unknown permission: " + name);
4101            }
4102
4103            SettingBase sb = (SettingBase) pkg.mExtras;
4104            if (sb == null) {
4105                throw new IllegalArgumentException("Unknown package: " + packageName);
4106            }
4107
4108            PermissionsState permissionsState = sb.getPermissionsState();
4109
4110            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4111
4112            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4113                // Install and runtime permissions are stored in different places,
4114                // so figure out what permission changed and persist the change.
4115                if (permissionsState.getInstallPermissionState(name) != null) {
4116                    scheduleWriteSettingsLocked();
4117                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4118                        || hadState) {
4119                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4120                }
4121            }
4122        }
4123    }
4124
4125    /**
4126     * Update the permission flags for all packages and runtime permissions of a user in order
4127     * to allow device or profile owner to remove POLICY_FIXED.
4128     */
4129    @Override
4130    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4131        if (!sUserManager.exists(userId)) {
4132            return;
4133        }
4134
4135        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4136
4137        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4138                true /* requireFullPermission */, true /* checkShell */,
4139                "updatePermissionFlagsForAllApps");
4140
4141        // Only the system can change system fixed flags.
4142        if (getCallingUid() != Process.SYSTEM_UID) {
4143            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4144            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4145        }
4146
4147        synchronized (mPackages) {
4148            boolean changed = false;
4149            final int packageCount = mPackages.size();
4150            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4151                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4152                SettingBase sb = (SettingBase) pkg.mExtras;
4153                if (sb == null) {
4154                    continue;
4155                }
4156                PermissionsState permissionsState = sb.getPermissionsState();
4157                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4158                        userId, flagMask, flagValues);
4159            }
4160            if (changed) {
4161                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4162            }
4163        }
4164    }
4165
4166    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4167        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4168                != PackageManager.PERMISSION_GRANTED
4169            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4170                != PackageManager.PERMISSION_GRANTED) {
4171            throw new SecurityException(message + " requires "
4172                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4173                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4174        }
4175    }
4176
4177    @Override
4178    public boolean shouldShowRequestPermissionRationale(String permissionName,
4179            String packageName, int userId) {
4180        if (UserHandle.getCallingUserId() != userId) {
4181            mContext.enforceCallingPermission(
4182                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4183                    "canShowRequestPermissionRationale for user " + userId);
4184        }
4185
4186        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4187        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4188            return false;
4189        }
4190
4191        if (checkPermission(permissionName, packageName, userId)
4192                == PackageManager.PERMISSION_GRANTED) {
4193            return false;
4194        }
4195
4196        final int flags;
4197
4198        final long identity = Binder.clearCallingIdentity();
4199        try {
4200            flags = getPermissionFlags(permissionName,
4201                    packageName, userId);
4202        } finally {
4203            Binder.restoreCallingIdentity(identity);
4204        }
4205
4206        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4207                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4208                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4209
4210        if ((flags & fixedFlags) != 0) {
4211            return false;
4212        }
4213
4214        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4215    }
4216
4217    @Override
4218    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4219        mContext.enforceCallingOrSelfPermission(
4220                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4221                "addOnPermissionsChangeListener");
4222
4223        synchronized (mPackages) {
4224            mOnPermissionChangeListeners.addListenerLocked(listener);
4225        }
4226    }
4227
4228    @Override
4229    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4230        synchronized (mPackages) {
4231            mOnPermissionChangeListeners.removeListenerLocked(listener);
4232        }
4233    }
4234
4235    @Override
4236    public boolean isProtectedBroadcast(String actionName) {
4237        synchronized (mPackages) {
4238            if (mProtectedBroadcasts.contains(actionName)) {
4239                return true;
4240            } else if (actionName != null) {
4241                // TODO: remove these terrible hacks
4242                if (actionName.startsWith("android.net.netmon.lingerExpired")
4243                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4244                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4245                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4246                    return true;
4247                }
4248            }
4249        }
4250        return false;
4251    }
4252
4253    @Override
4254    public int checkSignatures(String pkg1, String pkg2) {
4255        synchronized (mPackages) {
4256            final PackageParser.Package p1 = mPackages.get(pkg1);
4257            final PackageParser.Package p2 = mPackages.get(pkg2);
4258            if (p1 == null || p1.mExtras == null
4259                    || p2 == null || p2.mExtras == null) {
4260                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4261            }
4262            return compareSignatures(p1.mSignatures, p2.mSignatures);
4263        }
4264    }
4265
4266    @Override
4267    public int checkUidSignatures(int uid1, int uid2) {
4268        // Map to base uids.
4269        uid1 = UserHandle.getAppId(uid1);
4270        uid2 = UserHandle.getAppId(uid2);
4271        // reader
4272        synchronized (mPackages) {
4273            Signature[] s1;
4274            Signature[] s2;
4275            Object obj = mSettings.getUserIdLPr(uid1);
4276            if (obj != null) {
4277                if (obj instanceof SharedUserSetting) {
4278                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4279                } else if (obj instanceof PackageSetting) {
4280                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4281                } else {
4282                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4283                }
4284            } else {
4285                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4286            }
4287            obj = mSettings.getUserIdLPr(uid2);
4288            if (obj != null) {
4289                if (obj instanceof SharedUserSetting) {
4290                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4291                } else if (obj instanceof PackageSetting) {
4292                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4293                } else {
4294                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4295                }
4296            } else {
4297                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4298            }
4299            return compareSignatures(s1, s2);
4300        }
4301    }
4302
4303    private void killUid(int appId, int userId, String reason) {
4304        final long identity = Binder.clearCallingIdentity();
4305        try {
4306            IActivityManager am = ActivityManagerNative.getDefault();
4307            if (am != null) {
4308                try {
4309                    am.killUid(appId, userId, reason);
4310                } catch (RemoteException e) {
4311                    /* ignore - same process */
4312                }
4313            }
4314        } finally {
4315            Binder.restoreCallingIdentity(identity);
4316        }
4317    }
4318
4319    /**
4320     * Compares two sets of signatures. Returns:
4321     * <br />
4322     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4323     * <br />
4324     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4325     * <br />
4326     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4327     * <br />
4328     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4329     * <br />
4330     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4331     */
4332    static int compareSignatures(Signature[] s1, Signature[] s2) {
4333        if (s1 == null) {
4334            return s2 == null
4335                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4336                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4337        }
4338
4339        if (s2 == null) {
4340            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4341        }
4342
4343        if (s1.length != s2.length) {
4344            return PackageManager.SIGNATURE_NO_MATCH;
4345        }
4346
4347        // Since both signature sets are of size 1, we can compare without HashSets.
4348        if (s1.length == 1) {
4349            return s1[0].equals(s2[0]) ?
4350                    PackageManager.SIGNATURE_MATCH :
4351                    PackageManager.SIGNATURE_NO_MATCH;
4352        }
4353
4354        ArraySet<Signature> set1 = new ArraySet<Signature>();
4355        for (Signature sig : s1) {
4356            set1.add(sig);
4357        }
4358        ArraySet<Signature> set2 = new ArraySet<Signature>();
4359        for (Signature sig : s2) {
4360            set2.add(sig);
4361        }
4362        // Make sure s2 contains all signatures in s1.
4363        if (set1.equals(set2)) {
4364            return PackageManager.SIGNATURE_MATCH;
4365        }
4366        return PackageManager.SIGNATURE_NO_MATCH;
4367    }
4368
4369    /**
4370     * If the database version for this type of package (internal storage or
4371     * external storage) is less than the version where package signatures
4372     * were updated, return true.
4373     */
4374    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4375        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4376        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4377    }
4378
4379    /**
4380     * Used for backward compatibility to make sure any packages with
4381     * certificate chains get upgraded to the new style. {@code existingSigs}
4382     * will be in the old format (since they were stored on disk from before the
4383     * system upgrade) and {@code scannedSigs} will be in the newer format.
4384     */
4385    private int compareSignaturesCompat(PackageSignatures existingSigs,
4386            PackageParser.Package scannedPkg) {
4387        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4388            return PackageManager.SIGNATURE_NO_MATCH;
4389        }
4390
4391        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4392        for (Signature sig : existingSigs.mSignatures) {
4393            existingSet.add(sig);
4394        }
4395        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4396        for (Signature sig : scannedPkg.mSignatures) {
4397            try {
4398                Signature[] chainSignatures = sig.getChainSignatures();
4399                for (Signature chainSig : chainSignatures) {
4400                    scannedCompatSet.add(chainSig);
4401                }
4402            } catch (CertificateEncodingException e) {
4403                scannedCompatSet.add(sig);
4404            }
4405        }
4406        /*
4407         * Make sure the expanded scanned set contains all signatures in the
4408         * existing one.
4409         */
4410        if (scannedCompatSet.equals(existingSet)) {
4411            // Migrate the old signatures to the new scheme.
4412            existingSigs.assignSignatures(scannedPkg.mSignatures);
4413            // The new KeySets will be re-added later in the scanning process.
4414            synchronized (mPackages) {
4415                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4416            }
4417            return PackageManager.SIGNATURE_MATCH;
4418        }
4419        return PackageManager.SIGNATURE_NO_MATCH;
4420    }
4421
4422    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4423        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4424        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4425    }
4426
4427    private int compareSignaturesRecover(PackageSignatures existingSigs,
4428            PackageParser.Package scannedPkg) {
4429        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4430            return PackageManager.SIGNATURE_NO_MATCH;
4431        }
4432
4433        String msg = null;
4434        try {
4435            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4436                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4437                        + scannedPkg.packageName);
4438                return PackageManager.SIGNATURE_MATCH;
4439            }
4440        } catch (CertificateException e) {
4441            msg = e.getMessage();
4442        }
4443
4444        logCriticalInfo(Log.INFO,
4445                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4446        return PackageManager.SIGNATURE_NO_MATCH;
4447    }
4448
4449    @Override
4450    public List<String> getAllPackages() {
4451        synchronized (mPackages) {
4452            return new ArrayList<String>(mPackages.keySet());
4453        }
4454    }
4455
4456    @Override
4457    public String[] getPackagesForUid(int uid) {
4458        uid = UserHandle.getAppId(uid);
4459        // reader
4460        synchronized (mPackages) {
4461            Object obj = mSettings.getUserIdLPr(uid);
4462            if (obj instanceof SharedUserSetting) {
4463                final SharedUserSetting sus = (SharedUserSetting) obj;
4464                final int N = sus.packages.size();
4465                final String[] res = new String[N];
4466                final Iterator<PackageSetting> it = sus.packages.iterator();
4467                int i = 0;
4468                while (it.hasNext()) {
4469                    res[i++] = it.next().name;
4470                }
4471                return res;
4472            } else if (obj instanceof PackageSetting) {
4473                final PackageSetting ps = (PackageSetting) obj;
4474                return new String[] { ps.name };
4475            }
4476        }
4477        return null;
4478    }
4479
4480    @Override
4481    public String getNameForUid(int uid) {
4482        // reader
4483        synchronized (mPackages) {
4484            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4485            if (obj instanceof SharedUserSetting) {
4486                final SharedUserSetting sus = (SharedUserSetting) obj;
4487                return sus.name + ":" + sus.userId;
4488            } else if (obj instanceof PackageSetting) {
4489                final PackageSetting ps = (PackageSetting) obj;
4490                return ps.name;
4491            }
4492        }
4493        return null;
4494    }
4495
4496    @Override
4497    public int getUidForSharedUser(String sharedUserName) {
4498        if(sharedUserName == null) {
4499            return -1;
4500        }
4501        // reader
4502        synchronized (mPackages) {
4503            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4504            if (suid == null) {
4505                return -1;
4506            }
4507            return suid.userId;
4508        }
4509    }
4510
4511    @Override
4512    public int getFlagsForUid(int uid) {
4513        synchronized (mPackages) {
4514            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4515            if (obj instanceof SharedUserSetting) {
4516                final SharedUserSetting sus = (SharedUserSetting) obj;
4517                return sus.pkgFlags;
4518            } else if (obj instanceof PackageSetting) {
4519                final PackageSetting ps = (PackageSetting) obj;
4520                return ps.pkgFlags;
4521            }
4522        }
4523        return 0;
4524    }
4525
4526    @Override
4527    public int getPrivateFlagsForUid(int uid) {
4528        synchronized (mPackages) {
4529            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4530            if (obj instanceof SharedUserSetting) {
4531                final SharedUserSetting sus = (SharedUserSetting) obj;
4532                return sus.pkgPrivateFlags;
4533            } else if (obj instanceof PackageSetting) {
4534                final PackageSetting ps = (PackageSetting) obj;
4535                return ps.pkgPrivateFlags;
4536            }
4537        }
4538        return 0;
4539    }
4540
4541    @Override
4542    public boolean isUidPrivileged(int uid) {
4543        uid = UserHandle.getAppId(uid);
4544        // reader
4545        synchronized (mPackages) {
4546            Object obj = mSettings.getUserIdLPr(uid);
4547            if (obj instanceof SharedUserSetting) {
4548                final SharedUserSetting sus = (SharedUserSetting) obj;
4549                final Iterator<PackageSetting> it = sus.packages.iterator();
4550                while (it.hasNext()) {
4551                    if (it.next().isPrivileged()) {
4552                        return true;
4553                    }
4554                }
4555            } else if (obj instanceof PackageSetting) {
4556                final PackageSetting ps = (PackageSetting) obj;
4557                return ps.isPrivileged();
4558            }
4559        }
4560        return false;
4561    }
4562
4563    @Override
4564    public String[] getAppOpPermissionPackages(String permissionName) {
4565        synchronized (mPackages) {
4566            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4567            if (pkgs == null) {
4568                return null;
4569            }
4570            return pkgs.toArray(new String[pkgs.size()]);
4571        }
4572    }
4573
4574    @Override
4575    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4576            int flags, int userId) {
4577        if (!sUserManager.exists(userId)) return null;
4578        flags = updateFlagsForResolve(flags, userId, intent);
4579        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4580                false /* requireFullPermission */, false /* checkShell */, "resolve intent");
4581        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4582                userId);
4583        final ResolveInfo bestChoice =
4584                chooseBestActivity(intent, resolvedType, flags, query, userId);
4585
4586        if (isEphemeralAllowed(intent, query, userId)) {
4587            final EphemeralResolveInfo ai =
4588                    getEphemeralResolveInfo(intent, resolvedType, userId);
4589            if (ai != null) {
4590                if (DEBUG_EPHEMERAL) {
4591                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4592                }
4593                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4594                bestChoice.ephemeralResolveInfo = ai;
4595            }
4596        }
4597        return bestChoice;
4598    }
4599
4600    @Override
4601    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4602            IntentFilter filter, int match, ComponentName activity) {
4603        final int userId = UserHandle.getCallingUserId();
4604        if (DEBUG_PREFERRED) {
4605            Log.v(TAG, "setLastChosenActivity intent=" + intent
4606                + " resolvedType=" + resolvedType
4607                + " flags=" + flags
4608                + " filter=" + filter
4609                + " match=" + match
4610                + " activity=" + activity);
4611            filter.dump(new PrintStreamPrinter(System.out), "    ");
4612        }
4613        intent.setComponent(null);
4614        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4615                userId);
4616        // Find any earlier preferred or last chosen entries and nuke them
4617        findPreferredActivity(intent, resolvedType,
4618                flags, query, 0, false, true, false, userId);
4619        // Add the new activity as the last chosen for this filter
4620        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4621                "Setting last chosen");
4622    }
4623
4624    @Override
4625    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4626        final int userId = UserHandle.getCallingUserId();
4627        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4628        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4629                userId);
4630        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4631                false, false, false, userId);
4632    }
4633
4634
4635    private boolean isEphemeralAllowed(
4636            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4637        // Short circuit and return early if possible.
4638        if (DISABLE_EPHEMERAL_APPS) {
4639            return false;
4640        }
4641        final int callingUser = UserHandle.getCallingUserId();
4642        if (callingUser != UserHandle.USER_SYSTEM) {
4643            return false;
4644        }
4645        if (mEphemeralResolverConnection == null) {
4646            return false;
4647        }
4648        if (intent.getComponent() != null) {
4649            return false;
4650        }
4651        if (intent.getPackage() != null) {
4652            return false;
4653        }
4654        final boolean isWebUri = hasWebURI(intent);
4655        if (!isWebUri) {
4656            return false;
4657        }
4658        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4659        synchronized (mPackages) {
4660            final int count = resolvedActivites.size();
4661            for (int n = 0; n < count; n++) {
4662                ResolveInfo info = resolvedActivites.get(n);
4663                String packageName = info.activityInfo.packageName;
4664                PackageSetting ps = mSettings.mPackages.get(packageName);
4665                if (ps != null) {
4666                    // Try to get the status from User settings first
4667                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4668                    int status = (int) (packedStatus >> 32);
4669                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4670                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4671                        if (DEBUG_EPHEMERAL) {
4672                            Slog.v(TAG, "DENY ephemeral apps;"
4673                                + " pkg: " + packageName + ", status: " + status);
4674                        }
4675                        return false;
4676                    }
4677                }
4678            }
4679        }
4680        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4681        return true;
4682    }
4683
4684    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4685            int userId) {
4686        MessageDigest digest = null;
4687        try {
4688            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4689        } catch (NoSuchAlgorithmException e) {
4690            // If we can't create a digest, ignore ephemeral apps.
4691            return null;
4692        }
4693
4694        final byte[] hostBytes = intent.getData().getHost().getBytes();
4695        final byte[] digestBytes = digest.digest(hostBytes);
4696        int shaPrefix =
4697                digestBytes[0] << 24
4698                | digestBytes[1] << 16
4699                | digestBytes[2] << 8
4700                | digestBytes[3] << 0;
4701        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4702                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4703        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4704            // No hash prefix match; there are no ephemeral apps for this domain.
4705            return null;
4706        }
4707        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4708            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4709            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4710                continue;
4711            }
4712            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4713            // No filters; this should never happen.
4714            if (filters.isEmpty()) {
4715                continue;
4716            }
4717            // We have a domain match; resolve the filters to see if anything matches.
4718            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4719            for (int j = filters.size() - 1; j >= 0; --j) {
4720                final EphemeralResolveIntentInfo intentInfo =
4721                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4722                ephemeralResolver.addFilter(intentInfo);
4723            }
4724            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4725                    intent, resolvedType, false /*defaultOnly*/, userId);
4726            if (!matchedResolveInfoList.isEmpty()) {
4727                return matchedResolveInfoList.get(0);
4728            }
4729        }
4730        // Hash or filter mis-match; no ephemeral apps for this domain.
4731        return null;
4732    }
4733
4734    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4735            int flags, List<ResolveInfo> query, int userId) {
4736        if (query != null) {
4737            final int N = query.size();
4738            if (N == 1) {
4739                return query.get(0);
4740            } else if (N > 1) {
4741                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4742                // If there is more than one activity with the same priority,
4743                // then let the user decide between them.
4744                ResolveInfo r0 = query.get(0);
4745                ResolveInfo r1 = query.get(1);
4746                if (DEBUG_INTENT_MATCHING || debug) {
4747                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4748                            + r1.activityInfo.name + "=" + r1.priority);
4749                }
4750                // If the first activity has a higher priority, or a different
4751                // default, then it is always desirable to pick it.
4752                if (r0.priority != r1.priority
4753                        || r0.preferredOrder != r1.preferredOrder
4754                        || r0.isDefault != r1.isDefault) {
4755                    return query.get(0);
4756                }
4757                // If we have saved a preference for a preferred activity for
4758                // this Intent, use that.
4759                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4760                        flags, query, r0.priority, true, false, debug, userId);
4761                if (ri != null) {
4762                    return ri;
4763                }
4764                ri = new ResolveInfo(mResolveInfo);
4765                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4766                ri.activityInfo.applicationInfo = new ApplicationInfo(
4767                        ri.activityInfo.applicationInfo);
4768                if (userId != 0) {
4769                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4770                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4771                }
4772                // Make sure that the resolver is displayable in car mode
4773                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4774                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4775                return ri;
4776            }
4777        }
4778        return null;
4779    }
4780
4781    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4782            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4783        final int N = query.size();
4784        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4785                .get(userId);
4786        // Get the list of persistent preferred activities that handle the intent
4787        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4788        List<PersistentPreferredActivity> pprefs = ppir != null
4789                ? ppir.queryIntent(intent, resolvedType,
4790                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4791                : null;
4792        if (pprefs != null && pprefs.size() > 0) {
4793            final int M = pprefs.size();
4794            for (int i=0; i<M; i++) {
4795                final PersistentPreferredActivity ppa = pprefs.get(i);
4796                if (DEBUG_PREFERRED || debug) {
4797                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4798                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4799                            + "\n  component=" + ppa.mComponent);
4800                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4801                }
4802                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4803                        flags | MATCH_DISABLED_COMPONENTS, userId);
4804                if (DEBUG_PREFERRED || debug) {
4805                    Slog.v(TAG, "Found persistent preferred activity:");
4806                    if (ai != null) {
4807                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4808                    } else {
4809                        Slog.v(TAG, "  null");
4810                    }
4811                }
4812                if (ai == null) {
4813                    // This previously registered persistent preferred activity
4814                    // component is no longer known. Ignore it and do NOT remove it.
4815                    continue;
4816                }
4817                for (int j=0; j<N; j++) {
4818                    final ResolveInfo ri = query.get(j);
4819                    if (!ri.activityInfo.applicationInfo.packageName
4820                            .equals(ai.applicationInfo.packageName)) {
4821                        continue;
4822                    }
4823                    if (!ri.activityInfo.name.equals(ai.name)) {
4824                        continue;
4825                    }
4826                    //  Found a persistent preference that can handle the intent.
4827                    if (DEBUG_PREFERRED || debug) {
4828                        Slog.v(TAG, "Returning persistent preferred activity: " +
4829                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4830                    }
4831                    return ri;
4832                }
4833            }
4834        }
4835        return null;
4836    }
4837
4838    // TODO: handle preferred activities missing while user has amnesia
4839    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4840            List<ResolveInfo> query, int priority, boolean always,
4841            boolean removeMatches, boolean debug, int userId) {
4842        if (!sUserManager.exists(userId)) return null;
4843        flags = updateFlagsForResolve(flags, userId, intent);
4844        // writer
4845        synchronized (mPackages) {
4846            if (intent.getSelector() != null) {
4847                intent = intent.getSelector();
4848            }
4849            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4850
4851            // Try to find a matching persistent preferred activity.
4852            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4853                    debug, userId);
4854
4855            // If a persistent preferred activity matched, use it.
4856            if (pri != null) {
4857                return pri;
4858            }
4859
4860            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4861            // Get the list of preferred activities that handle the intent
4862            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4863            List<PreferredActivity> prefs = pir != null
4864                    ? pir.queryIntent(intent, resolvedType,
4865                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4866                    : null;
4867            if (prefs != null && prefs.size() > 0) {
4868                boolean changed = false;
4869                try {
4870                    // First figure out how good the original match set is.
4871                    // We will only allow preferred activities that came
4872                    // from the same match quality.
4873                    int match = 0;
4874
4875                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4876
4877                    final int N = query.size();
4878                    for (int j=0; j<N; j++) {
4879                        final ResolveInfo ri = query.get(j);
4880                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4881                                + ": 0x" + Integer.toHexString(match));
4882                        if (ri.match > match) {
4883                            match = ri.match;
4884                        }
4885                    }
4886
4887                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4888                            + Integer.toHexString(match));
4889
4890                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4891                    final int M = prefs.size();
4892                    for (int i=0; i<M; i++) {
4893                        final PreferredActivity pa = prefs.get(i);
4894                        if (DEBUG_PREFERRED || debug) {
4895                            Slog.v(TAG, "Checking PreferredActivity ds="
4896                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4897                                    + "\n  component=" + pa.mPref.mComponent);
4898                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4899                        }
4900                        if (pa.mPref.mMatch != match) {
4901                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4902                                    + Integer.toHexString(pa.mPref.mMatch));
4903                            continue;
4904                        }
4905                        // If it's not an "always" type preferred activity and that's what we're
4906                        // looking for, skip it.
4907                        if (always && !pa.mPref.mAlways) {
4908                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4909                            continue;
4910                        }
4911                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
4912                                flags | MATCH_DISABLED_COMPONENTS, userId);
4913                        if (DEBUG_PREFERRED || debug) {
4914                            Slog.v(TAG, "Found preferred activity:");
4915                            if (ai != null) {
4916                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4917                            } else {
4918                                Slog.v(TAG, "  null");
4919                            }
4920                        }
4921                        if (ai == null) {
4922                            // This previously registered preferred activity
4923                            // component is no longer known.  Most likely an update
4924                            // to the app was installed and in the new version this
4925                            // component no longer exists.  Clean it up by removing
4926                            // it from the preferred activities list, and skip it.
4927                            Slog.w(TAG, "Removing dangling preferred activity: "
4928                                    + pa.mPref.mComponent);
4929                            pir.removeFilter(pa);
4930                            changed = true;
4931                            continue;
4932                        }
4933                        for (int j=0; j<N; j++) {
4934                            final ResolveInfo ri = query.get(j);
4935                            if (!ri.activityInfo.applicationInfo.packageName
4936                                    .equals(ai.applicationInfo.packageName)) {
4937                                continue;
4938                            }
4939                            if (!ri.activityInfo.name.equals(ai.name)) {
4940                                continue;
4941                            }
4942
4943                            if (removeMatches) {
4944                                pir.removeFilter(pa);
4945                                changed = true;
4946                                if (DEBUG_PREFERRED) {
4947                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
4948                                }
4949                                break;
4950                            }
4951
4952                            // Okay we found a previously set preferred or last chosen app.
4953                            // If the result set is different from when this
4954                            // was created, we need to clear it and re-ask the
4955                            // user their preference, if we're looking for an "always" type entry.
4956                            if (always && !pa.mPref.sameSet(query)) {
4957                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
4958                                        + intent + " type " + resolvedType);
4959                                if (DEBUG_PREFERRED) {
4960                                    Slog.v(TAG, "Removing preferred activity since set changed "
4961                                            + pa.mPref.mComponent);
4962                                }
4963                                pir.removeFilter(pa);
4964                                // Re-add the filter as a "last chosen" entry (!always)
4965                                PreferredActivity lastChosen = new PreferredActivity(
4966                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
4967                                pir.addFilter(lastChosen);
4968                                changed = true;
4969                                return null;
4970                            }
4971
4972                            // Yay! Either the set matched or we're looking for the last chosen
4973                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
4974                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4975                            return ri;
4976                        }
4977                    }
4978                } finally {
4979                    if (changed) {
4980                        if (DEBUG_PREFERRED) {
4981                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
4982                        }
4983                        scheduleWritePackageRestrictionsLocked(userId);
4984                    }
4985                }
4986            }
4987        }
4988        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
4989        return null;
4990    }
4991
4992    /*
4993     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
4994     */
4995    @Override
4996    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
4997            int targetUserId) {
4998        mContext.enforceCallingOrSelfPermission(
4999                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5000        List<CrossProfileIntentFilter> matches =
5001                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5002        if (matches != null) {
5003            int size = matches.size();
5004            for (int i = 0; i < size; i++) {
5005                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5006            }
5007        }
5008        if (hasWebURI(intent)) {
5009            // cross-profile app linking works only towards the parent.
5010            final UserInfo parent = getProfileParent(sourceUserId);
5011            synchronized(mPackages) {
5012                int flags = updateFlagsForResolve(0, parent.id, intent);
5013                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5014                        intent, resolvedType, flags, sourceUserId, parent.id);
5015                return xpDomainInfo != null;
5016            }
5017        }
5018        return false;
5019    }
5020
5021    private UserInfo getProfileParent(int userId) {
5022        final long identity = Binder.clearCallingIdentity();
5023        try {
5024            return sUserManager.getProfileParent(userId);
5025        } finally {
5026            Binder.restoreCallingIdentity(identity);
5027        }
5028    }
5029
5030    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5031            String resolvedType, int userId) {
5032        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5033        if (resolver != null) {
5034            return resolver.queryIntent(intent, resolvedType, false, userId);
5035        }
5036        return null;
5037    }
5038
5039    @Override
5040    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5041            String resolvedType, int flags, int userId) {
5042        return new ParceledListSlice<>(
5043                queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5044    }
5045
5046    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5047            String resolvedType, int flags, int userId) {
5048        if (!sUserManager.exists(userId)) return Collections.emptyList();
5049        flags = updateFlagsForResolve(flags, userId, intent);
5050        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5051                false /* requireFullPermission */, false /* checkShell */,
5052                "query intent activities");
5053        ComponentName comp = intent.getComponent();
5054        if (comp == null) {
5055            if (intent.getSelector() != null) {
5056                intent = intent.getSelector();
5057                comp = intent.getComponent();
5058            }
5059        }
5060
5061        if (comp != null) {
5062            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5063            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5064            if (ai != null) {
5065                final ResolveInfo ri = new ResolveInfo();
5066                ri.activityInfo = ai;
5067                list.add(ri);
5068            }
5069            return list;
5070        }
5071
5072        // reader
5073        synchronized (mPackages) {
5074            final String pkgName = intent.getPackage();
5075            if (pkgName == null) {
5076                List<CrossProfileIntentFilter> matchingFilters =
5077                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5078                // Check for results that need to skip the current profile.
5079                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5080                        resolvedType, flags, userId);
5081                if (xpResolveInfo != null) {
5082                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5083                    result.add(xpResolveInfo);
5084                    return filterIfNotSystemUser(result, userId);
5085                }
5086
5087                // Check for results in the current profile.
5088                List<ResolveInfo> result = mActivities.queryIntent(
5089                        intent, resolvedType, flags, userId);
5090                result = filterIfNotSystemUser(result, userId);
5091
5092                // Check for cross profile results.
5093                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5094                xpResolveInfo = queryCrossProfileIntents(
5095                        matchingFilters, intent, resolvedType, flags, userId,
5096                        hasNonNegativePriorityResult);
5097                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5098                    boolean isVisibleToUser = filterIfNotSystemUser(
5099                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5100                    if (isVisibleToUser) {
5101                        result.add(xpResolveInfo);
5102                        Collections.sort(result, mResolvePrioritySorter);
5103                    }
5104                }
5105                if (hasWebURI(intent)) {
5106                    CrossProfileDomainInfo xpDomainInfo = null;
5107                    final UserInfo parent = getProfileParent(userId);
5108                    if (parent != null) {
5109                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5110                                flags, userId, parent.id);
5111                    }
5112                    if (xpDomainInfo != null) {
5113                        if (xpResolveInfo != null) {
5114                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5115                            // in the result.
5116                            result.remove(xpResolveInfo);
5117                        }
5118                        if (result.size() == 0) {
5119                            result.add(xpDomainInfo.resolveInfo);
5120                            return result;
5121                        }
5122                    } else if (result.size() <= 1) {
5123                        return result;
5124                    }
5125                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5126                            xpDomainInfo, userId);
5127                    Collections.sort(result, mResolvePrioritySorter);
5128                }
5129                return result;
5130            }
5131            final PackageParser.Package pkg = mPackages.get(pkgName);
5132            if (pkg != null) {
5133                return filterIfNotSystemUser(
5134                        mActivities.queryIntentForPackage(
5135                                intent, resolvedType, flags, pkg.activities, userId),
5136                        userId);
5137            }
5138            return new ArrayList<ResolveInfo>();
5139        }
5140    }
5141
5142    private static class CrossProfileDomainInfo {
5143        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5144        ResolveInfo resolveInfo;
5145        /* Best domain verification status of the activities found in the other profile */
5146        int bestDomainVerificationStatus;
5147    }
5148
5149    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5150            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5151        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5152                sourceUserId)) {
5153            return null;
5154        }
5155        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5156                resolvedType, flags, parentUserId);
5157
5158        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5159            return null;
5160        }
5161        CrossProfileDomainInfo result = null;
5162        int size = resultTargetUser.size();
5163        for (int i = 0; i < size; i++) {
5164            ResolveInfo riTargetUser = resultTargetUser.get(i);
5165            // Intent filter verification is only for filters that specify a host. So don't return
5166            // those that handle all web uris.
5167            if (riTargetUser.handleAllWebDataURI) {
5168                continue;
5169            }
5170            String packageName = riTargetUser.activityInfo.packageName;
5171            PackageSetting ps = mSettings.mPackages.get(packageName);
5172            if (ps == null) {
5173                continue;
5174            }
5175            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5176            int status = (int)(verificationState >> 32);
5177            if (result == null) {
5178                result = new CrossProfileDomainInfo();
5179                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5180                        sourceUserId, parentUserId);
5181                result.bestDomainVerificationStatus = status;
5182            } else {
5183                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5184                        result.bestDomainVerificationStatus);
5185            }
5186        }
5187        // Don't consider matches with status NEVER across profiles.
5188        if (result != null && result.bestDomainVerificationStatus
5189                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5190            return null;
5191        }
5192        return result;
5193    }
5194
5195    /**
5196     * Verification statuses are ordered from the worse to the best, except for
5197     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5198     */
5199    private int bestDomainVerificationStatus(int status1, int status2) {
5200        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5201            return status2;
5202        }
5203        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5204            return status1;
5205        }
5206        return (int) MathUtils.max(status1, status2);
5207    }
5208
5209    private boolean isUserEnabled(int userId) {
5210        long callingId = Binder.clearCallingIdentity();
5211        try {
5212            UserInfo userInfo = sUserManager.getUserInfo(userId);
5213            return userInfo != null && userInfo.isEnabled();
5214        } finally {
5215            Binder.restoreCallingIdentity(callingId);
5216        }
5217    }
5218
5219    /**
5220     * Filter out activities with systemUserOnly flag set, when current user is not System.
5221     *
5222     * @return filtered list
5223     */
5224    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5225        if (userId == UserHandle.USER_SYSTEM) {
5226            return resolveInfos;
5227        }
5228        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5229            ResolveInfo info = resolveInfos.get(i);
5230            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5231                resolveInfos.remove(i);
5232            }
5233        }
5234        return resolveInfos;
5235    }
5236
5237    /**
5238     * @param resolveInfos list of resolve infos in descending priority order
5239     * @return if the list contains a resolve info with non-negative priority
5240     */
5241    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5242        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5243    }
5244
5245    private static boolean hasWebURI(Intent intent) {
5246        if (intent.getData() == null) {
5247            return false;
5248        }
5249        final String scheme = intent.getScheme();
5250        if (TextUtils.isEmpty(scheme)) {
5251            return false;
5252        }
5253        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5254    }
5255
5256    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5257            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5258            int userId) {
5259        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5260
5261        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5262            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5263                    candidates.size());
5264        }
5265
5266        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5267        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5268        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5269        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5270        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5271        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5272
5273        synchronized (mPackages) {
5274            final int count = candidates.size();
5275            // First, try to use linked apps. Partition the candidates into four lists:
5276            // one for the final results, one for the "do not use ever", one for "undefined status"
5277            // and finally one for "browser app type".
5278            for (int n=0; n<count; n++) {
5279                ResolveInfo info = candidates.get(n);
5280                String packageName = info.activityInfo.packageName;
5281                PackageSetting ps = mSettings.mPackages.get(packageName);
5282                if (ps != null) {
5283                    // Add to the special match all list (Browser use case)
5284                    if (info.handleAllWebDataURI) {
5285                        matchAllList.add(info);
5286                        continue;
5287                    }
5288                    // Try to get the status from User settings first
5289                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5290                    int status = (int)(packedStatus >> 32);
5291                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5292                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5293                        if (DEBUG_DOMAIN_VERIFICATION) {
5294                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5295                                    + " : linkgen=" + linkGeneration);
5296                        }
5297                        // Use link-enabled generation as preferredOrder, i.e.
5298                        // prefer newly-enabled over earlier-enabled.
5299                        info.preferredOrder = linkGeneration;
5300                        alwaysList.add(info);
5301                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5302                        if (DEBUG_DOMAIN_VERIFICATION) {
5303                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5304                        }
5305                        neverList.add(info);
5306                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5307                        if (DEBUG_DOMAIN_VERIFICATION) {
5308                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5309                        }
5310                        alwaysAskList.add(info);
5311                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5312                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5313                        if (DEBUG_DOMAIN_VERIFICATION) {
5314                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5315                        }
5316                        undefinedList.add(info);
5317                    }
5318                }
5319            }
5320
5321            // We'll want to include browser possibilities in a few cases
5322            boolean includeBrowser = false;
5323
5324            // First try to add the "always" resolution(s) for the current user, if any
5325            if (alwaysList.size() > 0) {
5326                result.addAll(alwaysList);
5327            } else {
5328                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5329                result.addAll(undefinedList);
5330                // Maybe add one for the other profile.
5331                if (xpDomainInfo != null && (
5332                        xpDomainInfo.bestDomainVerificationStatus
5333                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5334                    result.add(xpDomainInfo.resolveInfo);
5335                }
5336                includeBrowser = true;
5337            }
5338
5339            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5340            // If there were 'always' entries their preferred order has been set, so we also
5341            // back that off to make the alternatives equivalent
5342            if (alwaysAskList.size() > 0) {
5343                for (ResolveInfo i : result) {
5344                    i.preferredOrder = 0;
5345                }
5346                result.addAll(alwaysAskList);
5347                includeBrowser = true;
5348            }
5349
5350            if (includeBrowser) {
5351                // Also add browsers (all of them or only the default one)
5352                if (DEBUG_DOMAIN_VERIFICATION) {
5353                    Slog.v(TAG, "   ...including browsers in candidate set");
5354                }
5355                if ((matchFlags & MATCH_ALL) != 0) {
5356                    result.addAll(matchAllList);
5357                } else {
5358                    // Browser/generic handling case.  If there's a default browser, go straight
5359                    // to that (but only if there is no other higher-priority match).
5360                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5361                    int maxMatchPrio = 0;
5362                    ResolveInfo defaultBrowserMatch = null;
5363                    final int numCandidates = matchAllList.size();
5364                    for (int n = 0; n < numCandidates; n++) {
5365                        ResolveInfo info = matchAllList.get(n);
5366                        // track the highest overall match priority...
5367                        if (info.priority > maxMatchPrio) {
5368                            maxMatchPrio = info.priority;
5369                        }
5370                        // ...and the highest-priority default browser match
5371                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5372                            if (defaultBrowserMatch == null
5373                                    || (defaultBrowserMatch.priority < info.priority)) {
5374                                if (debug) {
5375                                    Slog.v(TAG, "Considering default browser match " + info);
5376                                }
5377                                defaultBrowserMatch = info;
5378                            }
5379                        }
5380                    }
5381                    if (defaultBrowserMatch != null
5382                            && defaultBrowserMatch.priority >= maxMatchPrio
5383                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5384                    {
5385                        if (debug) {
5386                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5387                        }
5388                        result.add(defaultBrowserMatch);
5389                    } else {
5390                        result.addAll(matchAllList);
5391                    }
5392                }
5393
5394                // If there is nothing selected, add all candidates and remove the ones that the user
5395                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5396                if (result.size() == 0) {
5397                    result.addAll(candidates);
5398                    result.removeAll(neverList);
5399                }
5400            }
5401        }
5402        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5403            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5404                    result.size());
5405            for (ResolveInfo info : result) {
5406                Slog.v(TAG, "  + " + info.activityInfo);
5407            }
5408        }
5409        return result;
5410    }
5411
5412    // Returns a packed value as a long:
5413    //
5414    // high 'int'-sized word: link status: undefined/ask/never/always.
5415    // low 'int'-sized word: relative priority among 'always' results.
5416    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5417        long result = ps.getDomainVerificationStatusForUser(userId);
5418        // if none available, get the master status
5419        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5420            if (ps.getIntentFilterVerificationInfo() != null) {
5421                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5422            }
5423        }
5424        return result;
5425    }
5426
5427    private ResolveInfo querySkipCurrentProfileIntents(
5428            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5429            int flags, int sourceUserId) {
5430        if (matchingFilters != null) {
5431            int size = matchingFilters.size();
5432            for (int i = 0; i < size; i ++) {
5433                CrossProfileIntentFilter filter = matchingFilters.get(i);
5434                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5435                    // Checking if there are activities in the target user that can handle the
5436                    // intent.
5437                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5438                            resolvedType, flags, sourceUserId);
5439                    if (resolveInfo != null) {
5440                        return resolveInfo;
5441                    }
5442                }
5443            }
5444        }
5445        return null;
5446    }
5447
5448    // Return matching ResolveInfo in target user if any.
5449    private ResolveInfo queryCrossProfileIntents(
5450            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5451            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5452        if (matchingFilters != null) {
5453            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5454            // match the same intent. For performance reasons, it is better not to
5455            // run queryIntent twice for the same userId
5456            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5457            int size = matchingFilters.size();
5458            for (int i = 0; i < size; i++) {
5459                CrossProfileIntentFilter filter = matchingFilters.get(i);
5460                int targetUserId = filter.getTargetUserId();
5461                boolean skipCurrentProfile =
5462                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5463                boolean skipCurrentProfileIfNoMatchFound =
5464                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5465                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5466                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5467                    // Checking if there are activities in the target user that can handle the
5468                    // intent.
5469                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5470                            resolvedType, flags, sourceUserId);
5471                    if (resolveInfo != null) return resolveInfo;
5472                    alreadyTriedUserIds.put(targetUserId, true);
5473                }
5474            }
5475        }
5476        return null;
5477    }
5478
5479    /**
5480     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5481     * will forward the intent to the filter's target user.
5482     * Otherwise, returns null.
5483     */
5484    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5485            String resolvedType, int flags, int sourceUserId) {
5486        int targetUserId = filter.getTargetUserId();
5487        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5488                resolvedType, flags, targetUserId);
5489        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5490            // If all the matches in the target profile are suspended, return null.
5491            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5492                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5493                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5494                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5495                            targetUserId);
5496                }
5497            }
5498        }
5499        return null;
5500    }
5501
5502    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5503            int sourceUserId, int targetUserId) {
5504        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5505        long ident = Binder.clearCallingIdentity();
5506        boolean targetIsProfile;
5507        try {
5508            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5509        } finally {
5510            Binder.restoreCallingIdentity(ident);
5511        }
5512        String className;
5513        if (targetIsProfile) {
5514            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5515        } else {
5516            className = FORWARD_INTENT_TO_PARENT;
5517        }
5518        ComponentName forwardingActivityComponentName = new ComponentName(
5519                mAndroidApplication.packageName, className);
5520        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5521                sourceUserId);
5522        if (!targetIsProfile) {
5523            forwardingActivityInfo.showUserIcon = targetUserId;
5524            forwardingResolveInfo.noResourceId = true;
5525        }
5526        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5527        forwardingResolveInfo.priority = 0;
5528        forwardingResolveInfo.preferredOrder = 0;
5529        forwardingResolveInfo.match = 0;
5530        forwardingResolveInfo.isDefault = true;
5531        forwardingResolveInfo.filter = filter;
5532        forwardingResolveInfo.targetUserId = targetUserId;
5533        return forwardingResolveInfo;
5534    }
5535
5536    @Override
5537    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5538            Intent[] specifics, String[] specificTypes, Intent intent,
5539            String resolvedType, int flags, int userId) {
5540        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5541                specificTypes, intent, resolvedType, flags, userId));
5542    }
5543
5544    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5545            Intent[] specifics, String[] specificTypes, Intent intent,
5546            String resolvedType, int flags, int userId) {
5547        if (!sUserManager.exists(userId)) return Collections.emptyList();
5548        flags = updateFlagsForResolve(flags, userId, intent);
5549        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5550                false /* requireFullPermission */, false /* checkShell */,
5551                "query intent activity options");
5552        final String resultsAction = intent.getAction();
5553
5554        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5555                | PackageManager.GET_RESOLVED_FILTER, userId);
5556
5557        if (DEBUG_INTENT_MATCHING) {
5558            Log.v(TAG, "Query " + intent + ": " + results);
5559        }
5560
5561        int specificsPos = 0;
5562        int N;
5563
5564        // todo: note that the algorithm used here is O(N^2).  This
5565        // isn't a problem in our current environment, but if we start running
5566        // into situations where we have more than 5 or 10 matches then this
5567        // should probably be changed to something smarter...
5568
5569        // First we go through and resolve each of the specific items
5570        // that were supplied, taking care of removing any corresponding
5571        // duplicate items in the generic resolve list.
5572        if (specifics != null) {
5573            for (int i=0; i<specifics.length; i++) {
5574                final Intent sintent = specifics[i];
5575                if (sintent == null) {
5576                    continue;
5577                }
5578
5579                if (DEBUG_INTENT_MATCHING) {
5580                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5581                }
5582
5583                String action = sintent.getAction();
5584                if (resultsAction != null && resultsAction.equals(action)) {
5585                    // If this action was explicitly requested, then don't
5586                    // remove things that have it.
5587                    action = null;
5588                }
5589
5590                ResolveInfo ri = null;
5591                ActivityInfo ai = null;
5592
5593                ComponentName comp = sintent.getComponent();
5594                if (comp == null) {
5595                    ri = resolveIntent(
5596                        sintent,
5597                        specificTypes != null ? specificTypes[i] : null,
5598                            flags, userId);
5599                    if (ri == null) {
5600                        continue;
5601                    }
5602                    if (ri == mResolveInfo) {
5603                        // ACK!  Must do something better with this.
5604                    }
5605                    ai = ri.activityInfo;
5606                    comp = new ComponentName(ai.applicationInfo.packageName,
5607                            ai.name);
5608                } else {
5609                    ai = getActivityInfo(comp, flags, userId);
5610                    if (ai == null) {
5611                        continue;
5612                    }
5613                }
5614
5615                // Look for any generic query activities that are duplicates
5616                // of this specific one, and remove them from the results.
5617                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5618                N = results.size();
5619                int j;
5620                for (j=specificsPos; j<N; j++) {
5621                    ResolveInfo sri = results.get(j);
5622                    if ((sri.activityInfo.name.equals(comp.getClassName())
5623                            && sri.activityInfo.applicationInfo.packageName.equals(
5624                                    comp.getPackageName()))
5625                        || (action != null && sri.filter.matchAction(action))) {
5626                        results.remove(j);
5627                        if (DEBUG_INTENT_MATCHING) Log.v(
5628                            TAG, "Removing duplicate item from " + j
5629                            + " due to specific " + specificsPos);
5630                        if (ri == null) {
5631                            ri = sri;
5632                        }
5633                        j--;
5634                        N--;
5635                    }
5636                }
5637
5638                // Add this specific item to its proper place.
5639                if (ri == null) {
5640                    ri = new ResolveInfo();
5641                    ri.activityInfo = ai;
5642                }
5643                results.add(specificsPos, ri);
5644                ri.specificIndex = i;
5645                specificsPos++;
5646            }
5647        }
5648
5649        // Now we go through the remaining generic results and remove any
5650        // duplicate actions that are found here.
5651        N = results.size();
5652        for (int i=specificsPos; i<N-1; i++) {
5653            final ResolveInfo rii = results.get(i);
5654            if (rii.filter == null) {
5655                continue;
5656            }
5657
5658            // Iterate over all of the actions of this result's intent
5659            // filter...  typically this should be just one.
5660            final Iterator<String> it = rii.filter.actionsIterator();
5661            if (it == null) {
5662                continue;
5663            }
5664            while (it.hasNext()) {
5665                final String action = it.next();
5666                if (resultsAction != null && resultsAction.equals(action)) {
5667                    // If this action was explicitly requested, then don't
5668                    // remove things that have it.
5669                    continue;
5670                }
5671                for (int j=i+1; j<N; j++) {
5672                    final ResolveInfo rij = results.get(j);
5673                    if (rij.filter != null && rij.filter.hasAction(action)) {
5674                        results.remove(j);
5675                        if (DEBUG_INTENT_MATCHING) Log.v(
5676                            TAG, "Removing duplicate item from " + j
5677                            + " due to action " + action + " at " + i);
5678                        j--;
5679                        N--;
5680                    }
5681                }
5682            }
5683
5684            // If the caller didn't request filter information, drop it now
5685            // so we don't have to marshall/unmarshall it.
5686            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5687                rii.filter = null;
5688            }
5689        }
5690
5691        // Filter out the caller activity if so requested.
5692        if (caller != null) {
5693            N = results.size();
5694            for (int i=0; i<N; i++) {
5695                ActivityInfo ainfo = results.get(i).activityInfo;
5696                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5697                        && caller.getClassName().equals(ainfo.name)) {
5698                    results.remove(i);
5699                    break;
5700                }
5701            }
5702        }
5703
5704        // If the caller didn't request filter information,
5705        // drop them now so we don't have to
5706        // marshall/unmarshall it.
5707        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5708            N = results.size();
5709            for (int i=0; i<N; i++) {
5710                results.get(i).filter = null;
5711            }
5712        }
5713
5714        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5715        return results;
5716    }
5717
5718    @Override
5719    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5720            String resolvedType, int flags, int userId) {
5721        return new ParceledListSlice<>(
5722                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5723    }
5724
5725    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5726            String resolvedType, int flags, int userId) {
5727        if (!sUserManager.exists(userId)) return Collections.emptyList();
5728        flags = updateFlagsForResolve(flags, userId, intent);
5729        ComponentName comp = intent.getComponent();
5730        if (comp == null) {
5731            if (intent.getSelector() != null) {
5732                intent = intent.getSelector();
5733                comp = intent.getComponent();
5734            }
5735        }
5736        if (comp != null) {
5737            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5738            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5739            if (ai != null) {
5740                ResolveInfo ri = new ResolveInfo();
5741                ri.activityInfo = ai;
5742                list.add(ri);
5743            }
5744            return list;
5745        }
5746
5747        // reader
5748        synchronized (mPackages) {
5749            String pkgName = intent.getPackage();
5750            if (pkgName == null) {
5751                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5752            }
5753            final PackageParser.Package pkg = mPackages.get(pkgName);
5754            if (pkg != null) {
5755                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5756                        userId);
5757            }
5758            return Collections.emptyList();
5759        }
5760    }
5761
5762    @Override
5763    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5764        if (!sUserManager.exists(userId)) return null;
5765        flags = updateFlagsForResolve(flags, userId, intent);
5766        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5767        if (query != null) {
5768            if (query.size() >= 1) {
5769                // If there is more than one service with the same priority,
5770                // just arbitrarily pick the first one.
5771                return query.get(0);
5772            }
5773        }
5774        return null;
5775    }
5776
5777    @Override
5778    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5779            String resolvedType, int flags, int userId) {
5780        return new ParceledListSlice<>(
5781                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5782    }
5783
5784    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5785            String resolvedType, int flags, int userId) {
5786        if (!sUserManager.exists(userId)) return Collections.emptyList();
5787        flags = updateFlagsForResolve(flags, userId, intent);
5788        ComponentName comp = intent.getComponent();
5789        if (comp == null) {
5790            if (intent.getSelector() != null) {
5791                intent = intent.getSelector();
5792                comp = intent.getComponent();
5793            }
5794        }
5795        if (comp != null) {
5796            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5797            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5798            if (si != null) {
5799                final ResolveInfo ri = new ResolveInfo();
5800                ri.serviceInfo = si;
5801                list.add(ri);
5802            }
5803            return list;
5804        }
5805
5806        // reader
5807        synchronized (mPackages) {
5808            String pkgName = intent.getPackage();
5809            if (pkgName == null) {
5810                return mServices.queryIntent(intent, resolvedType, flags, userId);
5811            }
5812            final PackageParser.Package pkg = mPackages.get(pkgName);
5813            if (pkg != null) {
5814                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5815                        userId);
5816            }
5817            return Collections.emptyList();
5818        }
5819    }
5820
5821    @Override
5822    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
5823            String resolvedType, int flags, int userId) {
5824        return new ParceledListSlice<>(
5825                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
5826    }
5827
5828    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
5829            Intent intent, String resolvedType, int flags, int userId) {
5830        if (!sUserManager.exists(userId)) return Collections.emptyList();
5831        flags = updateFlagsForResolve(flags, userId, intent);
5832        ComponentName comp = intent.getComponent();
5833        if (comp == null) {
5834            if (intent.getSelector() != null) {
5835                intent = intent.getSelector();
5836                comp = intent.getComponent();
5837            }
5838        }
5839        if (comp != null) {
5840            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5841            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5842            if (pi != null) {
5843                final ResolveInfo ri = new ResolveInfo();
5844                ri.providerInfo = pi;
5845                list.add(ri);
5846            }
5847            return list;
5848        }
5849
5850        // reader
5851        synchronized (mPackages) {
5852            String pkgName = intent.getPackage();
5853            if (pkgName == null) {
5854                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5855            }
5856            final PackageParser.Package pkg = mPackages.get(pkgName);
5857            if (pkg != null) {
5858                return mProviders.queryIntentForPackage(
5859                        intent, resolvedType, flags, pkg.providers, userId);
5860            }
5861            return Collections.emptyList();
5862        }
5863    }
5864
5865    @Override
5866    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5867        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5868        flags = updateFlagsForPackage(flags, userId, null);
5869        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5870        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5871                true /* requireFullPermission */, false /* checkShell */,
5872                "get installed packages");
5873
5874        // writer
5875        synchronized (mPackages) {
5876            ArrayList<PackageInfo> list;
5877            if (listUninstalled) {
5878                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5879                for (PackageSetting ps : mSettings.mPackages.values()) {
5880                    PackageInfo pi;
5881                    if (ps.pkg != null) {
5882                        pi = generatePackageInfo(ps.pkg, flags, userId);
5883                    } else {
5884                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5885                    }
5886                    if (pi != null) {
5887                        list.add(pi);
5888                    }
5889                }
5890            } else {
5891                list = new ArrayList<PackageInfo>(mPackages.size());
5892                for (PackageParser.Package p : mPackages.values()) {
5893                    PackageInfo pi = generatePackageInfo(p, flags, userId);
5894                    if (pi != null) {
5895                        list.add(pi);
5896                    }
5897                }
5898            }
5899
5900            return new ParceledListSlice<PackageInfo>(list);
5901        }
5902    }
5903
5904    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5905            String[] permissions, boolean[] tmp, int flags, int userId) {
5906        int numMatch = 0;
5907        final PermissionsState permissionsState = ps.getPermissionsState();
5908        for (int i=0; i<permissions.length; i++) {
5909            final String permission = permissions[i];
5910            if (permissionsState.hasPermission(permission, userId)) {
5911                tmp[i] = true;
5912                numMatch++;
5913            } else {
5914                tmp[i] = false;
5915            }
5916        }
5917        if (numMatch == 0) {
5918            return;
5919        }
5920        PackageInfo pi;
5921        if (ps.pkg != null) {
5922            pi = generatePackageInfo(ps.pkg, flags, userId);
5923        } else {
5924            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
5925        }
5926        // The above might return null in cases of uninstalled apps or install-state
5927        // skew across users/profiles.
5928        if (pi != null) {
5929            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
5930                if (numMatch == permissions.length) {
5931                    pi.requestedPermissions = permissions;
5932                } else {
5933                    pi.requestedPermissions = new String[numMatch];
5934                    numMatch = 0;
5935                    for (int i=0; i<permissions.length; i++) {
5936                        if (tmp[i]) {
5937                            pi.requestedPermissions[numMatch] = permissions[i];
5938                            numMatch++;
5939                        }
5940                    }
5941                }
5942            }
5943            list.add(pi);
5944        }
5945    }
5946
5947    @Override
5948    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
5949            String[] permissions, int flags, int userId) {
5950        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5951        flags = updateFlagsForPackage(flags, userId, permissions);
5952        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5953
5954        // writer
5955        synchronized (mPackages) {
5956            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
5957            boolean[] tmpBools = new boolean[permissions.length];
5958            if (listUninstalled) {
5959                for (PackageSetting ps : mSettings.mPackages.values()) {
5960                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
5961                }
5962            } else {
5963                for (PackageParser.Package pkg : mPackages.values()) {
5964                    PackageSetting ps = (PackageSetting)pkg.mExtras;
5965                    if (ps != null) {
5966                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
5967                                userId);
5968                    }
5969                }
5970            }
5971
5972            return new ParceledListSlice<PackageInfo>(list);
5973        }
5974    }
5975
5976    @Override
5977    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
5978        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5979        flags = updateFlagsForApplication(flags, userId, null);
5980        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5981
5982        // writer
5983        synchronized (mPackages) {
5984            ArrayList<ApplicationInfo> list;
5985            if (listUninstalled) {
5986                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
5987                for (PackageSetting ps : mSettings.mPackages.values()) {
5988                    ApplicationInfo ai;
5989                    if (ps.pkg != null) {
5990                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
5991                                ps.readUserState(userId), userId);
5992                    } else {
5993                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
5994                    }
5995                    if (ai != null) {
5996                        list.add(ai);
5997                    }
5998                }
5999            } else {
6000                list = new ArrayList<ApplicationInfo>(mPackages.size());
6001                for (PackageParser.Package p : mPackages.values()) {
6002                    if (p.mExtras != null) {
6003                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6004                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6005                        if (ai != null) {
6006                            list.add(ai);
6007                        }
6008                    }
6009                }
6010            }
6011
6012            return new ParceledListSlice<ApplicationInfo>(list);
6013        }
6014    }
6015
6016    @Override
6017    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6018        if (DISABLE_EPHEMERAL_APPS) {
6019            return null;
6020        }
6021
6022        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6023                "getEphemeralApplications");
6024        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6025                true /* requireFullPermission */, false /* checkShell */,
6026                "getEphemeralApplications");
6027        synchronized (mPackages) {
6028            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6029                    .getEphemeralApplicationsLPw(userId);
6030            if (ephemeralApps != null) {
6031                return new ParceledListSlice<>(ephemeralApps);
6032            }
6033        }
6034        return null;
6035    }
6036
6037    @Override
6038    public boolean isEphemeralApplication(String packageName, int userId) {
6039        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6040                true /* requireFullPermission */, false /* checkShell */,
6041                "isEphemeral");
6042        if (DISABLE_EPHEMERAL_APPS) {
6043            return false;
6044        }
6045
6046        if (!isCallerSameApp(packageName)) {
6047            return false;
6048        }
6049        synchronized (mPackages) {
6050            PackageParser.Package pkg = mPackages.get(packageName);
6051            if (pkg != null) {
6052                return pkg.applicationInfo.isEphemeralApp();
6053            }
6054        }
6055        return false;
6056    }
6057
6058    @Override
6059    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6060        if (DISABLE_EPHEMERAL_APPS) {
6061            return null;
6062        }
6063
6064        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6065                true /* requireFullPermission */, false /* checkShell */,
6066                "getCookie");
6067        if (!isCallerSameApp(packageName)) {
6068            return null;
6069        }
6070        synchronized (mPackages) {
6071            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6072                    packageName, userId);
6073        }
6074    }
6075
6076    @Override
6077    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6078        if (DISABLE_EPHEMERAL_APPS) {
6079            return true;
6080        }
6081
6082        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6083                true /* requireFullPermission */, true /* checkShell */,
6084                "setCookie");
6085        if (!isCallerSameApp(packageName)) {
6086            return false;
6087        }
6088        synchronized (mPackages) {
6089            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6090                    packageName, cookie, userId);
6091        }
6092    }
6093
6094    @Override
6095    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6096        if (DISABLE_EPHEMERAL_APPS) {
6097            return null;
6098        }
6099
6100        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6101                "getEphemeralApplicationIcon");
6102        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6103                true /* requireFullPermission */, false /* checkShell */,
6104                "getEphemeralApplicationIcon");
6105        synchronized (mPackages) {
6106            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6107                    packageName, userId);
6108        }
6109    }
6110
6111    private boolean isCallerSameApp(String packageName) {
6112        PackageParser.Package pkg = mPackages.get(packageName);
6113        return pkg != null
6114                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6115    }
6116
6117    @Override
6118    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6119        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6120    }
6121
6122    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6123        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6124
6125        // reader
6126        synchronized (mPackages) {
6127            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6128            final int userId = UserHandle.getCallingUserId();
6129            while (i.hasNext()) {
6130                final PackageParser.Package p = i.next();
6131                if (p.applicationInfo == null) continue;
6132
6133                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6134                        && !p.applicationInfo.isDirectBootAware();
6135                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6136                        && p.applicationInfo.isDirectBootAware();
6137
6138                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6139                        && (!mSafeMode || isSystemApp(p))
6140                        && (matchesUnaware || matchesAware)) {
6141                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6142                    if (ps != null) {
6143                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6144                                ps.readUserState(userId), userId);
6145                        if (ai != null) {
6146                            finalList.add(ai);
6147                        }
6148                    }
6149                }
6150            }
6151        }
6152
6153        return finalList;
6154    }
6155
6156    @Override
6157    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6158        if (!sUserManager.exists(userId)) return null;
6159        flags = updateFlagsForComponent(flags, userId, name);
6160        // reader
6161        synchronized (mPackages) {
6162            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6163            PackageSetting ps = provider != null
6164                    ? mSettings.mPackages.get(provider.owner.packageName)
6165                    : null;
6166            return ps != null
6167                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6168                    ? PackageParser.generateProviderInfo(provider, flags,
6169                            ps.readUserState(userId), userId)
6170                    : null;
6171        }
6172    }
6173
6174    /**
6175     * @deprecated
6176     */
6177    @Deprecated
6178    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6179        // reader
6180        synchronized (mPackages) {
6181            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6182                    .entrySet().iterator();
6183            final int userId = UserHandle.getCallingUserId();
6184            while (i.hasNext()) {
6185                Map.Entry<String, PackageParser.Provider> entry = i.next();
6186                PackageParser.Provider p = entry.getValue();
6187                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6188
6189                if (ps != null && p.syncable
6190                        && (!mSafeMode || (p.info.applicationInfo.flags
6191                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6192                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6193                            ps.readUserState(userId), userId);
6194                    if (info != null) {
6195                        outNames.add(entry.getKey());
6196                        outInfo.add(info);
6197                    }
6198                }
6199            }
6200        }
6201    }
6202
6203    @Override
6204    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6205            int uid, int flags) {
6206        final int userId = processName != null ? UserHandle.getUserId(uid)
6207                : UserHandle.getCallingUserId();
6208        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6209        flags = updateFlagsForComponent(flags, userId, processName);
6210
6211        ArrayList<ProviderInfo> finalList = null;
6212        // reader
6213        synchronized (mPackages) {
6214            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6215            while (i.hasNext()) {
6216                final PackageParser.Provider p = i.next();
6217                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6218                if (ps != null && p.info.authority != null
6219                        && (processName == null
6220                                || (p.info.processName.equals(processName)
6221                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6222                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6223                    if (finalList == null) {
6224                        finalList = new ArrayList<ProviderInfo>(3);
6225                    }
6226                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6227                            ps.readUserState(userId), userId);
6228                    if (info != null) {
6229                        finalList.add(info);
6230                    }
6231                }
6232            }
6233        }
6234
6235        if (finalList != null) {
6236            Collections.sort(finalList, mProviderInitOrderSorter);
6237            return new ParceledListSlice<ProviderInfo>(finalList);
6238        }
6239
6240        return ParceledListSlice.emptyList();
6241    }
6242
6243    @Override
6244    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6245        // reader
6246        synchronized (mPackages) {
6247            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6248            return PackageParser.generateInstrumentationInfo(i, flags);
6249        }
6250    }
6251
6252    @Override
6253    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6254            String targetPackage, int flags) {
6255        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6256    }
6257
6258    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6259            int flags) {
6260        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6261
6262        // reader
6263        synchronized (mPackages) {
6264            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6265            while (i.hasNext()) {
6266                final PackageParser.Instrumentation p = i.next();
6267                if (targetPackage == null
6268                        || targetPackage.equals(p.info.targetPackage)) {
6269                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6270                            flags);
6271                    if (ii != null) {
6272                        finalList.add(ii);
6273                    }
6274                }
6275            }
6276        }
6277
6278        return finalList;
6279    }
6280
6281    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6282        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6283        if (overlays == null) {
6284            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6285            return;
6286        }
6287        for (PackageParser.Package opkg : overlays.values()) {
6288            // Not much to do if idmap fails: we already logged the error
6289            // and we certainly don't want to abort installation of pkg simply
6290            // because an overlay didn't fit properly. For these reasons,
6291            // ignore the return value of createIdmapForPackagePairLI.
6292            createIdmapForPackagePairLI(pkg, opkg);
6293        }
6294    }
6295
6296    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6297            PackageParser.Package opkg) {
6298        if (!opkg.mTrustedOverlay) {
6299            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6300                    opkg.baseCodePath + ": overlay not trusted");
6301            return false;
6302        }
6303        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6304        if (overlaySet == null) {
6305            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6306                    opkg.baseCodePath + " but target package has no known overlays");
6307            return false;
6308        }
6309        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6310        // TODO: generate idmap for split APKs
6311        try {
6312            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6313        } catch (InstallerException e) {
6314            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6315                    + opkg.baseCodePath);
6316            return false;
6317        }
6318        PackageParser.Package[] overlayArray =
6319            overlaySet.values().toArray(new PackageParser.Package[0]);
6320        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6321            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6322                return p1.mOverlayPriority - p2.mOverlayPriority;
6323            }
6324        };
6325        Arrays.sort(overlayArray, cmp);
6326
6327        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6328        int i = 0;
6329        for (PackageParser.Package p : overlayArray) {
6330            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6331        }
6332        return true;
6333    }
6334
6335    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6336        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6337        try {
6338            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6339        } finally {
6340            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6341        }
6342    }
6343
6344    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6345        final File[] files = dir.listFiles();
6346        if (ArrayUtils.isEmpty(files)) {
6347            Log.d(TAG, "No files in app dir " + dir);
6348            return;
6349        }
6350
6351        if (DEBUG_PACKAGE_SCANNING) {
6352            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6353                    + " flags=0x" + Integer.toHexString(parseFlags));
6354        }
6355
6356        for (File file : files) {
6357            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6358                    && !PackageInstallerService.isStageName(file.getName());
6359            if (!isPackage) {
6360                // Ignore entries which are not packages
6361                continue;
6362            }
6363            try {
6364                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6365                        scanFlags, currentTime, null);
6366            } catch (PackageManagerException e) {
6367                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6368
6369                // Delete invalid userdata apps
6370                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6371                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6372                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6373                    removeCodePathLI(file);
6374                }
6375            }
6376        }
6377    }
6378
6379    private static File getSettingsProblemFile() {
6380        File dataDir = Environment.getDataDirectory();
6381        File systemDir = new File(dataDir, "system");
6382        File fname = new File(systemDir, "uiderrors.txt");
6383        return fname;
6384    }
6385
6386    static void reportSettingsProblem(int priority, String msg) {
6387        logCriticalInfo(priority, msg);
6388    }
6389
6390    static void logCriticalInfo(int priority, String msg) {
6391        Slog.println(priority, TAG, msg);
6392        EventLogTags.writePmCriticalInfo(msg);
6393        try {
6394            File fname = getSettingsProblemFile();
6395            FileOutputStream out = new FileOutputStream(fname, true);
6396            PrintWriter pw = new FastPrintWriter(out);
6397            SimpleDateFormat formatter = new SimpleDateFormat();
6398            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6399            pw.println(dateString + ": " + msg);
6400            pw.close();
6401            FileUtils.setPermissions(
6402                    fname.toString(),
6403                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6404                    -1, -1);
6405        } catch (java.io.IOException e) {
6406        }
6407    }
6408
6409    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6410            int parseFlags) throws PackageManagerException {
6411        if (ps != null
6412                && ps.codePath.equals(srcFile)
6413                && ps.timeStamp == srcFile.lastModified()
6414                && !isCompatSignatureUpdateNeeded(pkg)
6415                && !isRecoverSignatureUpdateNeeded(pkg)) {
6416            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6417            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6418            ArraySet<PublicKey> signingKs;
6419            synchronized (mPackages) {
6420                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6421            }
6422            if (ps.signatures.mSignatures != null
6423                    && ps.signatures.mSignatures.length != 0
6424                    && signingKs != null) {
6425                // Optimization: reuse the existing cached certificates
6426                // if the package appears to be unchanged.
6427                pkg.mSignatures = ps.signatures.mSignatures;
6428                pkg.mSigningKeys = signingKs;
6429                return;
6430            }
6431
6432            Slog.w(TAG, "PackageSetting for " + ps.name
6433                    + " is missing signatures.  Collecting certs again to recover them.");
6434        } else {
6435            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6436        }
6437
6438        try {
6439            PackageParser.collectCertificates(pkg, parseFlags);
6440        } catch (PackageParserException e) {
6441            throw PackageManagerException.from(e);
6442        }
6443    }
6444
6445    /**
6446     *  Traces a package scan.
6447     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6448     */
6449    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6450            long currentTime, UserHandle user) throws PackageManagerException {
6451        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6452        try {
6453            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6454        } finally {
6455            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6456        }
6457    }
6458
6459    /**
6460     *  Scans a package and returns the newly parsed package.
6461     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6462     */
6463    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6464            long currentTime, UserHandle user) throws PackageManagerException {
6465        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6466        parseFlags |= mDefParseFlags;
6467        PackageParser pp = new PackageParser();
6468        pp.setSeparateProcesses(mSeparateProcesses);
6469        pp.setOnlyCoreApps(mOnlyCore);
6470        pp.setDisplayMetrics(mMetrics);
6471
6472        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6473            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6474        }
6475
6476        final PackageParser.Package pkg;
6477        try {
6478            pkg = pp.parsePackage(scanFile, parseFlags);
6479        } catch (PackageParserException e) {
6480            throw PackageManagerException.from(e);
6481        }
6482
6483        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6484    }
6485
6486    /**
6487     *  Scans a package and returns the newly parsed package.
6488     *  @throws PackageManagerException on a parse error.
6489     */
6490    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6491            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6492            throws PackageManagerException {
6493        // If the package has children and this is the first dive in the function
6494        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6495        // packages (parent and children) would be successfully scanned before the
6496        // actual scan since scanning mutates internal state and we want to atomically
6497        // install the package and its children.
6498        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6499            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6500                scanFlags |= SCAN_CHECK_ONLY;
6501            }
6502        } else {
6503            scanFlags &= ~SCAN_CHECK_ONLY;
6504        }
6505
6506        // Scan the parent
6507        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6508                scanFlags, currentTime, user);
6509
6510        // Scan the children
6511        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6512        for (int i = 0; i < childCount; i++) {
6513            PackageParser.Package childPackage = pkg.childPackages.get(i);
6514            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6515                    currentTime, user);
6516        }
6517
6518
6519        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6520            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6521        }
6522
6523        return scannedPkg;
6524    }
6525
6526    /**
6527     *  Scans a package and returns the newly parsed package.
6528     *  @throws PackageManagerException on a parse error.
6529     */
6530    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6531            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6532            throws PackageManagerException {
6533        PackageSetting ps = null;
6534        PackageSetting updatedPkg;
6535        // reader
6536        synchronized (mPackages) {
6537            // Look to see if we already know about this package.
6538            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6539            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6540                // This package has been renamed to its original name.  Let's
6541                // use that.
6542                ps = mSettings.peekPackageLPr(oldName);
6543            }
6544            // If there was no original package, see one for the real package name.
6545            if (ps == null) {
6546                ps = mSettings.peekPackageLPr(pkg.packageName);
6547            }
6548            // Check to see if this package could be hiding/updating a system
6549            // package.  Must look for it either under the original or real
6550            // package name depending on our state.
6551            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6552            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6553
6554            // If this is a package we don't know about on the system partition, we
6555            // may need to remove disabled child packages on the system partition
6556            // or may need to not add child packages if the parent apk is updated
6557            // on the data partition and no longer defines this child package.
6558            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6559                // If this is a parent package for an updated system app and this system
6560                // app got an OTA update which no longer defines some of the child packages
6561                // we have to prune them from the disabled system packages.
6562                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6563                if (disabledPs != null) {
6564                    final int scannedChildCount = (pkg.childPackages != null)
6565                            ? pkg.childPackages.size() : 0;
6566                    final int disabledChildCount = disabledPs.childPackageNames != null
6567                            ? disabledPs.childPackageNames.size() : 0;
6568                    for (int i = 0; i < disabledChildCount; i++) {
6569                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6570                        boolean disabledPackageAvailable = false;
6571                        for (int j = 0; j < scannedChildCount; j++) {
6572                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6573                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6574                                disabledPackageAvailable = true;
6575                                break;
6576                            }
6577                         }
6578                         if (!disabledPackageAvailable) {
6579                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6580                         }
6581                    }
6582                }
6583            }
6584        }
6585
6586        boolean updatedPkgBetter = false;
6587        // First check if this is a system package that may involve an update
6588        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6589            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6590            // it needs to drop FLAG_PRIVILEGED.
6591            if (locationIsPrivileged(scanFile)) {
6592                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6593            } else {
6594                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6595            }
6596
6597            if (ps != null && !ps.codePath.equals(scanFile)) {
6598                // The path has changed from what was last scanned...  check the
6599                // version of the new path against what we have stored to determine
6600                // what to do.
6601                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6602                if (pkg.mVersionCode <= ps.versionCode) {
6603                    // The system package has been updated and the code path does not match
6604                    // Ignore entry. Skip it.
6605                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6606                            + " ignored: updated version " + ps.versionCode
6607                            + " better than this " + pkg.mVersionCode);
6608                    if (!updatedPkg.codePath.equals(scanFile)) {
6609                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6610                                + ps.name + " changing from " + updatedPkg.codePathString
6611                                + " to " + scanFile);
6612                        updatedPkg.codePath = scanFile;
6613                        updatedPkg.codePathString = scanFile.toString();
6614                        updatedPkg.resourcePath = scanFile;
6615                        updatedPkg.resourcePathString = scanFile.toString();
6616                    }
6617                    updatedPkg.pkg = pkg;
6618                    updatedPkg.versionCode = pkg.mVersionCode;
6619
6620                    // Update the disabled system child packages to point to the package too.
6621                    final int childCount = updatedPkg.childPackageNames != null
6622                            ? updatedPkg.childPackageNames.size() : 0;
6623                    for (int i = 0; i < childCount; i++) {
6624                        String childPackageName = updatedPkg.childPackageNames.get(i);
6625                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6626                                childPackageName);
6627                        if (updatedChildPkg != null) {
6628                            updatedChildPkg.pkg = pkg;
6629                            updatedChildPkg.versionCode = pkg.mVersionCode;
6630                        }
6631                    }
6632
6633                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6634                            + scanFile + " ignored: updated version " + ps.versionCode
6635                            + " better than this " + pkg.mVersionCode);
6636                } else {
6637                    // The current app on the system partition is better than
6638                    // what we have updated to on the data partition; switch
6639                    // back to the system partition version.
6640                    // At this point, its safely assumed that package installation for
6641                    // apps in system partition will go through. If not there won't be a working
6642                    // version of the app
6643                    // writer
6644                    synchronized (mPackages) {
6645                        // Just remove the loaded entries from package lists.
6646                        mPackages.remove(ps.name);
6647                    }
6648
6649                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6650                            + " reverting from " + ps.codePathString
6651                            + ": new version " + pkg.mVersionCode
6652                            + " better than installed " + ps.versionCode);
6653
6654                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6655                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6656                    synchronized (mInstallLock) {
6657                        args.cleanUpResourcesLI();
6658                    }
6659                    synchronized (mPackages) {
6660                        mSettings.enableSystemPackageLPw(ps.name);
6661                    }
6662                    updatedPkgBetter = true;
6663                }
6664            }
6665        }
6666
6667        if (updatedPkg != null) {
6668            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6669            // initially
6670            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6671
6672            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6673            // flag set initially
6674            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6675                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6676            }
6677        }
6678
6679        // Verify certificates against what was last scanned
6680        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6681
6682        /*
6683         * A new system app appeared, but we already had a non-system one of the
6684         * same name installed earlier.
6685         */
6686        boolean shouldHideSystemApp = false;
6687        if (updatedPkg == null && ps != null
6688                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6689            /*
6690             * Check to make sure the signatures match first. If they don't,
6691             * wipe the installed application and its data.
6692             */
6693            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6694                    != PackageManager.SIGNATURE_MATCH) {
6695                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6696                        + " signatures don't match existing userdata copy; removing");
6697                deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null);
6698                ps = null;
6699            } else {
6700                /*
6701                 * If the newly-added system app is an older version than the
6702                 * already installed version, hide it. It will be scanned later
6703                 * and re-added like an update.
6704                 */
6705                if (pkg.mVersionCode <= ps.versionCode) {
6706                    shouldHideSystemApp = true;
6707                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6708                            + " but new version " + pkg.mVersionCode + " better than installed "
6709                            + ps.versionCode + "; hiding system");
6710                } else {
6711                    /*
6712                     * The newly found system app is a newer version that the
6713                     * one previously installed. Simply remove the
6714                     * already-installed application and replace it with our own
6715                     * while keeping the application data.
6716                     */
6717                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6718                            + " reverting from " + ps.codePathString + ": new version "
6719                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6720                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6721                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6722                    synchronized (mInstallLock) {
6723                        args.cleanUpResourcesLI();
6724                    }
6725                }
6726            }
6727        }
6728
6729        // The apk is forward locked (not public) if its code and resources
6730        // are kept in different files. (except for app in either system or
6731        // vendor path).
6732        // TODO grab this value from PackageSettings
6733        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6734            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6735                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6736            }
6737        }
6738
6739        // TODO: extend to support forward-locked splits
6740        String resourcePath = null;
6741        String baseResourcePath = null;
6742        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6743            if (ps != null && ps.resourcePathString != null) {
6744                resourcePath = ps.resourcePathString;
6745                baseResourcePath = ps.resourcePathString;
6746            } else {
6747                // Should not happen at all. Just log an error.
6748                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6749            }
6750        } else {
6751            resourcePath = pkg.codePath;
6752            baseResourcePath = pkg.baseCodePath;
6753        }
6754
6755        // Set application objects path explicitly.
6756        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6757        pkg.setApplicationInfoCodePath(pkg.codePath);
6758        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6759        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6760        pkg.setApplicationInfoResourcePath(resourcePath);
6761        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6762        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6763
6764        // Note that we invoke the following method only if we are about to unpack an application
6765        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6766                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6767
6768        /*
6769         * If the system app should be overridden by a previously installed
6770         * data, hide the system app now and let the /data/app scan pick it up
6771         * again.
6772         */
6773        if (shouldHideSystemApp) {
6774            synchronized (mPackages) {
6775                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6776            }
6777        }
6778
6779        return scannedPkg;
6780    }
6781
6782    private static String fixProcessName(String defProcessName,
6783            String processName, int uid) {
6784        if (processName == null) {
6785            return defProcessName;
6786        }
6787        return processName;
6788    }
6789
6790    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6791            throws PackageManagerException {
6792        if (pkgSetting.signatures.mSignatures != null) {
6793            // Already existing package. Make sure signatures match
6794            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6795                    == PackageManager.SIGNATURE_MATCH;
6796            if (!match) {
6797                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6798                        == PackageManager.SIGNATURE_MATCH;
6799            }
6800            if (!match) {
6801                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6802                        == PackageManager.SIGNATURE_MATCH;
6803            }
6804            if (!match) {
6805                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6806                        + pkg.packageName + " signatures do not match the "
6807                        + "previously installed version; ignoring!");
6808            }
6809        }
6810
6811        // Check for shared user signatures
6812        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6813            // Already existing package. Make sure signatures match
6814            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6815                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6816            if (!match) {
6817                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6818                        == PackageManager.SIGNATURE_MATCH;
6819            }
6820            if (!match) {
6821                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6822                        == PackageManager.SIGNATURE_MATCH;
6823            }
6824            if (!match) {
6825                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6826                        "Package " + pkg.packageName
6827                        + " has no signatures that match those in shared user "
6828                        + pkgSetting.sharedUser.name + "; ignoring!");
6829            }
6830        }
6831    }
6832
6833    /**
6834     * Enforces that only the system UID or root's UID can call a method exposed
6835     * via Binder.
6836     *
6837     * @param message used as message if SecurityException is thrown
6838     * @throws SecurityException if the caller is not system or root
6839     */
6840    private static final void enforceSystemOrRoot(String message) {
6841        final int uid = Binder.getCallingUid();
6842        if (uid != Process.SYSTEM_UID && uid != 0) {
6843            throw new SecurityException(message);
6844        }
6845    }
6846
6847    @Override
6848    public void performFstrimIfNeeded() {
6849        enforceSystemOrRoot("Only the system can request fstrim");
6850
6851        // Before everything else, see whether we need to fstrim.
6852        try {
6853            IMountService ms = PackageHelper.getMountService();
6854            if (ms != null) {
6855                final boolean isUpgrade = isUpgrade();
6856                boolean doTrim = isUpgrade;
6857                if (doTrim) {
6858                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6859                } else {
6860                    final long interval = android.provider.Settings.Global.getLong(
6861                            mContext.getContentResolver(),
6862                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6863                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6864                    if (interval > 0) {
6865                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6866                        if (timeSinceLast > interval) {
6867                            doTrim = true;
6868                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6869                                    + "; running immediately");
6870                        }
6871                    }
6872                }
6873                if (doTrim) {
6874                    if (!isFirstBoot()) {
6875                        try {
6876                            ActivityManagerNative.getDefault().showBootMessage(
6877                                    mContext.getResources().getString(
6878                                            R.string.android_upgrading_fstrim), true);
6879                        } catch (RemoteException e) {
6880                        }
6881                    }
6882                    ms.runMaintenance();
6883                }
6884            } else {
6885                Slog.e(TAG, "Mount service unavailable!");
6886            }
6887        } catch (RemoteException e) {
6888            // Can't happen; MountService is local
6889        }
6890    }
6891
6892    @Override
6893    public void extractPackagesIfNeeded() {
6894        enforceSystemOrRoot("Only the system can request package extraction");
6895
6896        // Extract pacakges only if profile-guided compilation is enabled because
6897        // otherwise BackgroundDexOptService will not dexopt them later.
6898        boolean prunedCache = VMRuntime.didPruneDalvikCache();
6899        if (!isUpgrade() && !prunedCache) {
6900            return;
6901        }
6902
6903        List<PackageParser.Package> pkgs;
6904        synchronized (mPackages) {
6905            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
6906        }
6907
6908        int curr = 0;
6909        int total = pkgs.size();
6910        for (PackageParser.Package pkg : pkgs) {
6911            curr++;
6912
6913            if (DEBUG_DEXOPT) {
6914                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
6915            }
6916
6917            if (!isFirstBoot()) {
6918                try {
6919                    ActivityManagerNative.getDefault().showBootMessage(
6920                            mContext.getResources().getString(R.string.android_upgrading_apk,
6921                                    curr, total), true);
6922                } catch (RemoteException e) {
6923                }
6924            }
6925
6926            if (PackageDexOptimizer.canOptimizePackage(pkg)) {
6927                // If the cache was pruned, any compiled odex files will likely be out of date
6928                // and would have to be patched (would be SELF_PATCHOAT, which is deprecated).
6929                // Instead, force the extraction in this case.
6930                performDexOpt(pkg.packageName, null /* instructionSet */,
6931                         false /* useProfiles */, true /* extractOnly */, prunedCache);
6932            }
6933        }
6934    }
6935
6936    @Override
6937    public void notifyPackageUse(String packageName) {
6938        synchronized (mPackages) {
6939            PackageParser.Package p = mPackages.get(packageName);
6940            if (p == null) {
6941                return;
6942            }
6943            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
6944        }
6945    }
6946
6947    // TODO: this is not used nor needed. Delete it.
6948    @Override
6949    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
6950        return performDexOptTraced(packageName, instructionSet, false /* useProfiles */,
6951                false /* extractOnly */, false /* force */);
6952    }
6953
6954    @Override
6955    public boolean performDexOpt(String packageName, String instructionSet, boolean useProfiles,
6956            boolean extractOnly, boolean force) {
6957        return performDexOptTraced(packageName, instructionSet, useProfiles, extractOnly, force);
6958    }
6959
6960    private boolean performDexOptTraced(String packageName, String instructionSet,
6961                boolean useProfiles, boolean extractOnly, boolean force) {
6962        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
6963        try {
6964            return performDexOptInternal(packageName, instructionSet, useProfiles, extractOnly,
6965                    force);
6966        } finally {
6967            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6968        }
6969    }
6970
6971    private boolean performDexOptInternal(String packageName, String instructionSet,
6972                boolean useProfiles, boolean extractOnly, boolean force) {
6973        PackageParser.Package p;
6974        final String targetInstructionSet;
6975        synchronized (mPackages) {
6976            p = mPackages.get(packageName);
6977            if (p == null) {
6978                return false;
6979            }
6980            mPackageUsage.write(false);
6981
6982            targetInstructionSet = instructionSet != null ? instructionSet :
6983                    getPrimaryInstructionSet(p.applicationInfo);
6984        }
6985        long callingId = Binder.clearCallingIdentity();
6986        try {
6987            synchronized (mInstallLock) {
6988                final String[] instructionSets = new String[] { targetInstructionSet };
6989                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
6990                        useProfiles, extractOnly, force);
6991                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
6992            }
6993        } finally {
6994            Binder.restoreCallingIdentity(callingId);
6995        }
6996    }
6997
6998    public ArraySet<String> getOptimizablePackages() {
6999        ArraySet<String> pkgs = new ArraySet<String>();
7000        synchronized (mPackages) {
7001            for (PackageParser.Package p : mPackages.values()) {
7002                if (PackageDexOptimizer.canOptimizePackage(p)) {
7003                    pkgs.add(p.packageName);
7004                }
7005            }
7006        }
7007        return pkgs;
7008    }
7009
7010    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7011            String instructionSets[], boolean useProfiles, boolean extractOnly, boolean force) {
7012        // Select the dex optimizer based on the force parameter.
7013        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7014        //       allocate an object here.
7015        PackageDexOptimizer pdo = force
7016                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7017                : mPackageDexOptimizer;
7018
7019        // Optimize all dependencies first. Note: we ignore the return value and march on
7020        // on errors.
7021        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7022        if (!deps.isEmpty()) {
7023            for (PackageParser.Package depPackage : deps) {
7024                // TODO: Analyze and investigate if we (should) profile libraries.
7025                // Currently this will do a full compilation of the library.
7026                pdo.performDexOpt(depPackage, instructionSets, false /* useProfiles */,
7027                        false /* extractOnly */);
7028            }
7029        }
7030
7031        return pdo.performDexOpt(p, instructionSets, useProfiles, extractOnly);
7032    }
7033
7034    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7035        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7036            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7037            Set<String> collectedNames = new HashSet<>();
7038            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7039
7040            retValue.remove(p);
7041
7042            return retValue;
7043        } else {
7044            return Collections.emptyList();
7045        }
7046    }
7047
7048    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7049            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7050        if (!collectedNames.contains(p.packageName)) {
7051            collectedNames.add(p.packageName);
7052            collected.add(p);
7053
7054            if (p.usesLibraries != null) {
7055                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7056            }
7057            if (p.usesOptionalLibraries != null) {
7058                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7059                        collectedNames);
7060            }
7061        }
7062    }
7063
7064    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7065            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7066        for (String libName : libs) {
7067            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7068            if (libPkg != null) {
7069                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7070            }
7071        }
7072    }
7073
7074    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7075        synchronized (mPackages) {
7076            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7077            if (lib != null && lib.apk != null) {
7078                return mPackages.get(lib.apk);
7079            }
7080        }
7081        return null;
7082    }
7083
7084    public void shutdown() {
7085        mPackageUsage.write(true);
7086    }
7087
7088    @Override
7089    public void forceDexOpt(String packageName) {
7090        enforceSystemOrRoot("forceDexOpt");
7091
7092        PackageParser.Package pkg;
7093        synchronized (mPackages) {
7094            pkg = mPackages.get(packageName);
7095            if (pkg == null) {
7096                throw new IllegalArgumentException("Unknown package: " + packageName);
7097            }
7098        }
7099
7100        synchronized (mInstallLock) {
7101            final String[] instructionSets = new String[] {
7102                    getPrimaryInstructionSet(pkg.applicationInfo) };
7103
7104            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7105
7106            // Whoever is calling forceDexOpt wants a fully compiled package.
7107            // Don't use profiles since that may cause compilation to be skipped.
7108            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7109                    false /* useProfiles */, false /* extractOnly */, true /* force */);
7110
7111            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7112            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7113                throw new IllegalStateException("Failed to dexopt: " + res);
7114            }
7115        }
7116    }
7117
7118    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7119        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7120            Slog.w(TAG, "Unable to update from " + oldPkg.name
7121                    + " to " + newPkg.packageName
7122                    + ": old package not in system partition");
7123            return false;
7124        } else if (mPackages.get(oldPkg.name) != null) {
7125            Slog.w(TAG, "Unable to update from " + oldPkg.name
7126                    + " to " + newPkg.packageName
7127                    + ": old package still exists");
7128            return false;
7129        }
7130        return true;
7131    }
7132
7133    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
7134        // TODO: triage flags as part of 26466827
7135        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7136
7137        boolean res = true;
7138        final int[] users = sUserManager.getUserIds();
7139        for (int user : users) {
7140            try {
7141                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7142            } catch (InstallerException e) {
7143                Slog.w(TAG, "Failed to delete data directory", e);
7144                res = false;
7145            }
7146        }
7147        return res;
7148    }
7149
7150    void removeCodePathLI(File codePath) {
7151        if (codePath.isDirectory()) {
7152            try {
7153                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7154            } catch (InstallerException e) {
7155                Slog.w(TAG, "Failed to remove code path", e);
7156            }
7157        } else {
7158            codePath.delete();
7159        }
7160    }
7161
7162    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7163        try {
7164            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7165        } catch (InstallerException e) {
7166            Slog.w(TAG, "Failed to destroy app data", e);
7167        }
7168    }
7169
7170    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7171            int appId, String seinfo) {
7172        try {
7173            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7174        } catch (InstallerException e) {
7175            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7176        }
7177    }
7178
7179    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7180        final PackageParser.Package pkg;
7181        synchronized (mPackages) {
7182            pkg = mPackages.get(packageName);
7183        }
7184        if (pkg == null) {
7185            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7186            return;
7187        }
7188        deleteCodeCacheDirsLI(pkg);
7189    }
7190
7191    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7192        // TODO: triage flags as part of 26466827
7193        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7194
7195        int[] users = sUserManager.getUserIds();
7196        int res = 0;
7197        for (int user : users) {
7198            // Remove the parent code cache
7199            try {
7200                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7201                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7202            } catch (InstallerException e) {
7203                Slog.w(TAG, "Failed to delete code cache directory", e);
7204            }
7205            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7206            for (int i = 0; i < childCount; i++) {
7207                PackageParser.Package childPkg = pkg.childPackages.get(i);
7208                // Remove the child code cache
7209                try {
7210                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7211                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7212                } catch (InstallerException e) {
7213                    Slog.w(TAG, "Failed to delete code cache directory", e);
7214                }
7215            }
7216        }
7217    }
7218
7219    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7220            long lastUpdateTime) {
7221        // Set parent install/update time
7222        PackageSetting ps = (PackageSetting) pkg.mExtras;
7223        if (ps != null) {
7224            ps.firstInstallTime = firstInstallTime;
7225            ps.lastUpdateTime = lastUpdateTime;
7226        }
7227        // Set children install/update time
7228        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7229        for (int i = 0; i < childCount; i++) {
7230            PackageParser.Package childPkg = pkg.childPackages.get(i);
7231            ps = (PackageSetting) childPkg.mExtras;
7232            if (ps != null) {
7233                ps.firstInstallTime = firstInstallTime;
7234                ps.lastUpdateTime = lastUpdateTime;
7235            }
7236        }
7237    }
7238
7239    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7240            PackageParser.Package changingLib) {
7241        if (file.path != null) {
7242            usesLibraryFiles.add(file.path);
7243            return;
7244        }
7245        PackageParser.Package p = mPackages.get(file.apk);
7246        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7247            // If we are doing this while in the middle of updating a library apk,
7248            // then we need to make sure to use that new apk for determining the
7249            // dependencies here.  (We haven't yet finished committing the new apk
7250            // to the package manager state.)
7251            if (p == null || p.packageName.equals(changingLib.packageName)) {
7252                p = changingLib;
7253            }
7254        }
7255        if (p != null) {
7256            usesLibraryFiles.addAll(p.getAllCodePaths());
7257        }
7258    }
7259
7260    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7261            PackageParser.Package changingLib) throws PackageManagerException {
7262        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7263            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7264            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7265            for (int i=0; i<N; i++) {
7266                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7267                if (file == null) {
7268                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7269                            "Package " + pkg.packageName + " requires unavailable shared library "
7270                            + pkg.usesLibraries.get(i) + "; failing!");
7271                }
7272                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7273            }
7274            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7275            for (int i=0; i<N; i++) {
7276                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7277                if (file == null) {
7278                    Slog.w(TAG, "Package " + pkg.packageName
7279                            + " desires unavailable shared library "
7280                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7281                } else {
7282                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7283                }
7284            }
7285            N = usesLibraryFiles.size();
7286            if (N > 0) {
7287                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7288            } else {
7289                pkg.usesLibraryFiles = null;
7290            }
7291        }
7292    }
7293
7294    private static boolean hasString(List<String> list, List<String> which) {
7295        if (list == null) {
7296            return false;
7297        }
7298        for (int i=list.size()-1; i>=0; i--) {
7299            for (int j=which.size()-1; j>=0; j--) {
7300                if (which.get(j).equals(list.get(i))) {
7301                    return true;
7302                }
7303            }
7304        }
7305        return false;
7306    }
7307
7308    private void updateAllSharedLibrariesLPw() {
7309        for (PackageParser.Package pkg : mPackages.values()) {
7310            try {
7311                updateSharedLibrariesLPw(pkg, null);
7312            } catch (PackageManagerException e) {
7313                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7314            }
7315        }
7316    }
7317
7318    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7319            PackageParser.Package changingPkg) {
7320        ArrayList<PackageParser.Package> res = null;
7321        for (PackageParser.Package pkg : mPackages.values()) {
7322            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7323                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7324                if (res == null) {
7325                    res = new ArrayList<PackageParser.Package>();
7326                }
7327                res.add(pkg);
7328                try {
7329                    updateSharedLibrariesLPw(pkg, changingPkg);
7330                } catch (PackageManagerException e) {
7331                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7332                }
7333            }
7334        }
7335        return res;
7336    }
7337
7338    /**
7339     * Derive the value of the {@code cpuAbiOverride} based on the provided
7340     * value and an optional stored value from the package settings.
7341     */
7342    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7343        String cpuAbiOverride = null;
7344
7345        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7346            cpuAbiOverride = null;
7347        } else if (abiOverride != null) {
7348            cpuAbiOverride = abiOverride;
7349        } else if (settings != null) {
7350            cpuAbiOverride = settings.cpuAbiOverrideString;
7351        }
7352
7353        return cpuAbiOverride;
7354    }
7355
7356    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7357            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7358        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7359        // If the package has children and this is the first dive in the function
7360        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7361        // whether all packages (parent and children) would be successfully scanned
7362        // before the actual scan since scanning mutates internal state and we want
7363        // to atomically install the package and its children.
7364        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7365            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7366                scanFlags |= SCAN_CHECK_ONLY;
7367            }
7368        } else {
7369            scanFlags &= ~SCAN_CHECK_ONLY;
7370        }
7371
7372        final PackageParser.Package scannedPkg;
7373        try {
7374            // Scan the parent
7375            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7376            // Scan the children
7377            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7378            for (int i = 0; i < childCount; i++) {
7379                PackageParser.Package childPkg = pkg.childPackages.get(i);
7380                scanPackageLI(childPkg, parseFlags,
7381                        scanFlags, currentTime, user);
7382            }
7383        } finally {
7384            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7385        }
7386
7387        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7388            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7389        }
7390
7391        return scannedPkg;
7392    }
7393
7394    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7395            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7396        boolean success = false;
7397        try {
7398            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7399                    currentTime, user);
7400            success = true;
7401            return res;
7402        } finally {
7403            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7404                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7405            }
7406        }
7407    }
7408
7409    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7410            int scanFlags, long currentTime, UserHandle user)
7411            throws PackageManagerException {
7412        final File scanFile = new File(pkg.codePath);
7413        if (pkg.applicationInfo.getCodePath() == null ||
7414                pkg.applicationInfo.getResourcePath() == null) {
7415            // Bail out. The resource and code paths haven't been set.
7416            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7417                    "Code and resource paths haven't been set correctly");
7418        }
7419
7420        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7421            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7422        } else {
7423            // Only allow system apps to be flagged as core apps.
7424            pkg.coreApp = false;
7425        }
7426
7427        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7428            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7429        }
7430
7431        if (mCustomResolverComponentName != null &&
7432                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7433            setUpCustomResolverActivity(pkg);
7434        }
7435
7436        if (pkg.packageName.equals("android")) {
7437            synchronized (mPackages) {
7438                if (mAndroidApplication != null) {
7439                    Slog.w(TAG, "*************************************************");
7440                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7441                    Slog.w(TAG, " file=" + scanFile);
7442                    Slog.w(TAG, "*************************************************");
7443                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7444                            "Core android package being redefined.  Skipping.");
7445                }
7446
7447                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7448                    // Set up information for our fall-back user intent resolution activity.
7449                    mPlatformPackage = pkg;
7450                    pkg.mVersionCode = mSdkVersion;
7451                    mAndroidApplication = pkg.applicationInfo;
7452
7453                    if (!mResolverReplaced) {
7454                        mResolveActivity.applicationInfo = mAndroidApplication;
7455                        mResolveActivity.name = ResolverActivity.class.getName();
7456                        mResolveActivity.packageName = mAndroidApplication.packageName;
7457                        mResolveActivity.processName = "system:ui";
7458                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7459                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7460                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7461                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7462                        mResolveActivity.exported = true;
7463                        mResolveActivity.enabled = true;
7464                        mResolveInfo.activityInfo = mResolveActivity;
7465                        mResolveInfo.priority = 0;
7466                        mResolveInfo.preferredOrder = 0;
7467                        mResolveInfo.match = 0;
7468                        mResolveComponentName = new ComponentName(
7469                                mAndroidApplication.packageName, mResolveActivity.name);
7470                    }
7471                }
7472            }
7473        }
7474
7475        if (DEBUG_PACKAGE_SCANNING) {
7476            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7477                Log.d(TAG, "Scanning package " + pkg.packageName);
7478        }
7479
7480        synchronized (mPackages) {
7481            if (mPackages.containsKey(pkg.packageName)
7482                    || mSharedLibraries.containsKey(pkg.packageName)) {
7483                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7484                        "Application package " + pkg.packageName
7485                                + " already installed.  Skipping duplicate.");
7486            }
7487
7488            // If we're only installing presumed-existing packages, require that the
7489            // scanned APK is both already known and at the path previously established
7490            // for it.  Previously unknown packages we pick up normally, but if we have an
7491            // a priori expectation about this package's install presence, enforce it.
7492            // With a singular exception for new system packages. When an OTA contains
7493            // a new system package, we allow the codepath to change from a system location
7494            // to the user-installed location. If we don't allow this change, any newer,
7495            // user-installed version of the application will be ignored.
7496            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7497                if (mExpectingBetter.containsKey(pkg.packageName)) {
7498                    logCriticalInfo(Log.WARN,
7499                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7500                } else {
7501                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7502                    if (known != null) {
7503                        if (DEBUG_PACKAGE_SCANNING) {
7504                            Log.d(TAG, "Examining " + pkg.codePath
7505                                    + " and requiring known paths " + known.codePathString
7506                                    + " & " + known.resourcePathString);
7507                        }
7508                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7509                                || !pkg.applicationInfo.getResourcePath().equals(
7510                                known.resourcePathString)) {
7511                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7512                                    "Application package " + pkg.packageName
7513                                            + " found at " + pkg.applicationInfo.getCodePath()
7514                                            + " but expected at " + known.codePathString
7515                                            + "; ignoring.");
7516                        }
7517                    }
7518                }
7519            }
7520        }
7521
7522        // Initialize package source and resource directories
7523        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7524        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7525
7526        SharedUserSetting suid = null;
7527        PackageSetting pkgSetting = null;
7528
7529        if (!isSystemApp(pkg)) {
7530            // Only system apps can use these features.
7531            pkg.mOriginalPackages = null;
7532            pkg.mRealPackage = null;
7533            pkg.mAdoptPermissions = null;
7534        }
7535
7536        // Getting the package setting may have a side-effect, so if we
7537        // are only checking if scan would succeed, stash a copy of the
7538        // old setting to restore at the end.
7539        PackageSetting nonMutatedPs = null;
7540
7541        // writer
7542        synchronized (mPackages) {
7543            if (pkg.mSharedUserId != null) {
7544                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7545                if (suid == null) {
7546                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7547                            "Creating application package " + pkg.packageName
7548                            + " for shared user failed");
7549                }
7550                if (DEBUG_PACKAGE_SCANNING) {
7551                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7552                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7553                                + "): packages=" + suid.packages);
7554                }
7555            }
7556
7557            // Check if we are renaming from an original package name.
7558            PackageSetting origPackage = null;
7559            String realName = null;
7560            if (pkg.mOriginalPackages != null) {
7561                // This package may need to be renamed to a previously
7562                // installed name.  Let's check on that...
7563                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7564                if (pkg.mOriginalPackages.contains(renamed)) {
7565                    // This package had originally been installed as the
7566                    // original name, and we have already taken care of
7567                    // transitioning to the new one.  Just update the new
7568                    // one to continue using the old name.
7569                    realName = pkg.mRealPackage;
7570                    if (!pkg.packageName.equals(renamed)) {
7571                        // Callers into this function may have already taken
7572                        // care of renaming the package; only do it here if
7573                        // it is not already done.
7574                        pkg.setPackageName(renamed);
7575                    }
7576
7577                } else {
7578                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7579                        if ((origPackage = mSettings.peekPackageLPr(
7580                                pkg.mOriginalPackages.get(i))) != null) {
7581                            // We do have the package already installed under its
7582                            // original name...  should we use it?
7583                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7584                                // New package is not compatible with original.
7585                                origPackage = null;
7586                                continue;
7587                            } else if (origPackage.sharedUser != null) {
7588                                // Make sure uid is compatible between packages.
7589                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7590                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7591                                            + " to " + pkg.packageName + ": old uid "
7592                                            + origPackage.sharedUser.name
7593                                            + " differs from " + pkg.mSharedUserId);
7594                                    origPackage = null;
7595                                    continue;
7596                                }
7597                            } else {
7598                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7599                                        + pkg.packageName + " to old name " + origPackage.name);
7600                            }
7601                            break;
7602                        }
7603                    }
7604                }
7605            }
7606
7607            if (mTransferedPackages.contains(pkg.packageName)) {
7608                Slog.w(TAG, "Package " + pkg.packageName
7609                        + " was transferred to another, but its .apk remains");
7610            }
7611
7612            // See comments in nonMutatedPs declaration
7613            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7614                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7615                if (foundPs != null) {
7616                    nonMutatedPs = new PackageSetting(foundPs);
7617                }
7618            }
7619
7620            // Just create the setting, don't add it yet. For already existing packages
7621            // the PkgSetting exists already and doesn't have to be created.
7622            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7623                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7624                    pkg.applicationInfo.primaryCpuAbi,
7625                    pkg.applicationInfo.secondaryCpuAbi,
7626                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7627                    user, false);
7628            if (pkgSetting == null) {
7629                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7630                        "Creating application package " + pkg.packageName + " failed");
7631            }
7632
7633            if (pkgSetting.origPackage != null) {
7634                // If we are first transitioning from an original package,
7635                // fix up the new package's name now.  We need to do this after
7636                // looking up the package under its new name, so getPackageLP
7637                // can take care of fiddling things correctly.
7638                pkg.setPackageName(origPackage.name);
7639
7640                // File a report about this.
7641                String msg = "New package " + pkgSetting.realName
7642                        + " renamed to replace old package " + pkgSetting.name;
7643                reportSettingsProblem(Log.WARN, msg);
7644
7645                // Make a note of it.
7646                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7647                    mTransferedPackages.add(origPackage.name);
7648                }
7649
7650                // No longer need to retain this.
7651                pkgSetting.origPackage = null;
7652            }
7653
7654            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7655                // Make a note of it.
7656                mTransferedPackages.add(pkg.packageName);
7657            }
7658
7659            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7660                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7661            }
7662
7663            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7664                // Check all shared libraries and map to their actual file path.
7665                // We only do this here for apps not on a system dir, because those
7666                // are the only ones that can fail an install due to this.  We
7667                // will take care of the system apps by updating all of their
7668                // library paths after the scan is done.
7669                updateSharedLibrariesLPw(pkg, null);
7670            }
7671
7672            if (mFoundPolicyFile) {
7673                SELinuxMMAC.assignSeinfoValue(pkg);
7674            }
7675
7676            pkg.applicationInfo.uid = pkgSetting.appId;
7677            pkg.mExtras = pkgSetting;
7678            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7679                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7680                    // We just determined the app is signed correctly, so bring
7681                    // over the latest parsed certs.
7682                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7683                } else {
7684                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7685                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7686                                "Package " + pkg.packageName + " upgrade keys do not match the "
7687                                + "previously installed version");
7688                    } else {
7689                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7690                        String msg = "System package " + pkg.packageName
7691                            + " signature changed; retaining data.";
7692                        reportSettingsProblem(Log.WARN, msg);
7693                    }
7694                }
7695            } else {
7696                try {
7697                    verifySignaturesLP(pkgSetting, pkg);
7698                    // We just determined the app is signed correctly, so bring
7699                    // over the latest parsed certs.
7700                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7701                } catch (PackageManagerException e) {
7702                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7703                        throw e;
7704                    }
7705                    // The signature has changed, but this package is in the system
7706                    // image...  let's recover!
7707                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7708                    // However...  if this package is part of a shared user, but it
7709                    // doesn't match the signature of the shared user, let's fail.
7710                    // What this means is that you can't change the signatures
7711                    // associated with an overall shared user, which doesn't seem all
7712                    // that unreasonable.
7713                    if (pkgSetting.sharedUser != null) {
7714                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7715                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7716                            throw new PackageManagerException(
7717                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7718                                            "Signature mismatch for shared user: "
7719                                            + pkgSetting.sharedUser);
7720                        }
7721                    }
7722                    // File a report about this.
7723                    String msg = "System package " + pkg.packageName
7724                        + " signature changed; retaining data.";
7725                    reportSettingsProblem(Log.WARN, msg);
7726                }
7727            }
7728            // Verify that this new package doesn't have any content providers
7729            // that conflict with existing packages.  Only do this if the
7730            // package isn't already installed, since we don't want to break
7731            // things that are installed.
7732            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7733                final int N = pkg.providers.size();
7734                int i;
7735                for (i=0; i<N; i++) {
7736                    PackageParser.Provider p = pkg.providers.get(i);
7737                    if (p.info.authority != null) {
7738                        String names[] = p.info.authority.split(";");
7739                        for (int j = 0; j < names.length; j++) {
7740                            if (mProvidersByAuthority.containsKey(names[j])) {
7741                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7742                                final String otherPackageName =
7743                                        ((other != null && other.getComponentName() != null) ?
7744                                                other.getComponentName().getPackageName() : "?");
7745                                throw new PackageManagerException(
7746                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7747                                                "Can't install because provider name " + names[j]
7748                                                + " (in package " + pkg.applicationInfo.packageName
7749                                                + ") is already used by " + otherPackageName);
7750                            }
7751                        }
7752                    }
7753                }
7754            }
7755
7756            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7757                // This package wants to adopt ownership of permissions from
7758                // another package.
7759                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7760                    final String origName = pkg.mAdoptPermissions.get(i);
7761                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7762                    if (orig != null) {
7763                        if (verifyPackageUpdateLPr(orig, pkg)) {
7764                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7765                                    + pkg.packageName);
7766                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7767                        }
7768                    }
7769                }
7770            }
7771        }
7772
7773        final String pkgName = pkg.packageName;
7774
7775        final long scanFileTime = scanFile.lastModified();
7776        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7777        pkg.applicationInfo.processName = fixProcessName(
7778                pkg.applicationInfo.packageName,
7779                pkg.applicationInfo.processName,
7780                pkg.applicationInfo.uid);
7781
7782        if (pkg != mPlatformPackage) {
7783            // Get all of our default paths setup
7784            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7785        }
7786
7787        final String path = scanFile.getPath();
7788        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7789
7790        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7791            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7792
7793            // Some system apps still use directory structure for native libraries
7794            // in which case we might end up not detecting abi solely based on apk
7795            // structure. Try to detect abi based on directory structure.
7796            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7797                    pkg.applicationInfo.primaryCpuAbi == null) {
7798                setBundledAppAbisAndRoots(pkg, pkgSetting);
7799                setNativeLibraryPaths(pkg);
7800            }
7801
7802        } else {
7803            if ((scanFlags & SCAN_MOVE) != 0) {
7804                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7805                // but we already have this packages package info in the PackageSetting. We just
7806                // use that and derive the native library path based on the new codepath.
7807                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7808                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7809            }
7810
7811            // Set native library paths again. For moves, the path will be updated based on the
7812            // ABIs we've determined above. For non-moves, the path will be updated based on the
7813            // ABIs we determined during compilation, but the path will depend on the final
7814            // package path (after the rename away from the stage path).
7815            setNativeLibraryPaths(pkg);
7816        }
7817
7818        // This is a special case for the "system" package, where the ABI is
7819        // dictated by the zygote configuration (and init.rc). We should keep track
7820        // of this ABI so that we can deal with "normal" applications that run under
7821        // the same UID correctly.
7822        if (mPlatformPackage == pkg) {
7823            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7824                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7825        }
7826
7827        // If there's a mismatch between the abi-override in the package setting
7828        // and the abiOverride specified for the install. Warn about this because we
7829        // would've already compiled the app without taking the package setting into
7830        // account.
7831        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7832            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7833                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7834                        " for package " + pkg.packageName);
7835            }
7836        }
7837
7838        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7839        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7840        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7841
7842        // Copy the derived override back to the parsed package, so that we can
7843        // update the package settings accordingly.
7844        pkg.cpuAbiOverride = cpuAbiOverride;
7845
7846        if (DEBUG_ABI_SELECTION) {
7847            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7848                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7849                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7850        }
7851
7852        // Push the derived path down into PackageSettings so we know what to
7853        // clean up at uninstall time.
7854        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7855
7856        if (DEBUG_ABI_SELECTION) {
7857            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7858                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7859                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7860        }
7861
7862        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7863            // We don't do this here during boot because we can do it all
7864            // at once after scanning all existing packages.
7865            //
7866            // We also do this *before* we perform dexopt on this package, so that
7867            // we can avoid redundant dexopts, and also to make sure we've got the
7868            // code and package path correct.
7869            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7870                    pkg, true /* boot complete */);
7871        }
7872
7873        if (mFactoryTest && pkg.requestedPermissions.contains(
7874                android.Manifest.permission.FACTORY_TEST)) {
7875            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
7876        }
7877
7878        ArrayList<PackageParser.Package> clientLibPkgs = null;
7879
7880        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7881            if (nonMutatedPs != null) {
7882                synchronized (mPackages) {
7883                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
7884                }
7885            }
7886            return pkg;
7887        }
7888
7889        // Only privileged apps and updated privileged apps can add child packages.
7890        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
7891            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
7892                throw new PackageManagerException("Only privileged apps and updated "
7893                        + "privileged apps can add child packages. Ignoring package "
7894                        + pkg.packageName);
7895            }
7896            final int childCount = pkg.childPackages.size();
7897            for (int i = 0; i < childCount; i++) {
7898                PackageParser.Package childPkg = pkg.childPackages.get(i);
7899                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
7900                        childPkg.packageName)) {
7901                    throw new PackageManagerException("Cannot override a child package of "
7902                            + "another disabled system app. Ignoring package " + pkg.packageName);
7903                }
7904            }
7905        }
7906
7907        // writer
7908        synchronized (mPackages) {
7909            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7910                // Only system apps can add new shared libraries.
7911                if (pkg.libraryNames != null) {
7912                    for (int i=0; i<pkg.libraryNames.size(); i++) {
7913                        String name = pkg.libraryNames.get(i);
7914                        boolean allowed = false;
7915                        if (pkg.isUpdatedSystemApp()) {
7916                            // New library entries can only be added through the
7917                            // system image.  This is important to get rid of a lot
7918                            // of nasty edge cases: for example if we allowed a non-
7919                            // system update of the app to add a library, then uninstalling
7920                            // the update would make the library go away, and assumptions
7921                            // we made such as through app install filtering would now
7922                            // have allowed apps on the device which aren't compatible
7923                            // with it.  Better to just have the restriction here, be
7924                            // conservative, and create many fewer cases that can negatively
7925                            // impact the user experience.
7926                            final PackageSetting sysPs = mSettings
7927                                    .getDisabledSystemPkgLPr(pkg.packageName);
7928                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
7929                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
7930                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
7931                                        allowed = true;
7932                                        break;
7933                                    }
7934                                }
7935                            }
7936                        } else {
7937                            allowed = true;
7938                        }
7939                        if (allowed) {
7940                            if (!mSharedLibraries.containsKey(name)) {
7941                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
7942                            } else if (!name.equals(pkg.packageName)) {
7943                                Slog.w(TAG, "Package " + pkg.packageName + " library "
7944                                        + name + " already exists; skipping");
7945                            }
7946                        } else {
7947                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
7948                                    + name + " that is not declared on system image; skipping");
7949                        }
7950                    }
7951                    if ((scanFlags & SCAN_BOOTING) == 0) {
7952                        // If we are not booting, we need to update any applications
7953                        // that are clients of our shared library.  If we are booting,
7954                        // this will all be done once the scan is complete.
7955                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
7956                    }
7957                }
7958            }
7959        }
7960
7961        // Request the ActivityManager to kill the process(only for existing packages)
7962        // so that we do not end up in a confused state while the user is still using the older
7963        // version of the application while the new one gets installed.
7964        final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0;
7965        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
7966        if (killApp) {
7967            if (isReplacing) {
7968                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
7969
7970                killApplication(pkg.applicationInfo.packageName,
7971                            pkg.applicationInfo.uid, "replace pkg");
7972
7973                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7974            }
7975        }
7976
7977        // Also need to kill any apps that are dependent on the library.
7978        if (clientLibPkgs != null) {
7979            for (int i=0; i<clientLibPkgs.size(); i++) {
7980                PackageParser.Package clientPkg = clientLibPkgs.get(i);
7981                killApplication(clientPkg.applicationInfo.packageName,
7982                        clientPkg.applicationInfo.uid, "update lib");
7983            }
7984        }
7985
7986        // Make sure we're not adding any bogus keyset info
7987        KeySetManagerService ksms = mSettings.mKeySetManagerService;
7988        ksms.assertScannedPackageValid(pkg);
7989
7990        // writer
7991        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
7992
7993        boolean createIdmapFailed = false;
7994        synchronized (mPackages) {
7995            // We don't expect installation to fail beyond this point
7996
7997            // Add the new setting to mSettings
7998            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
7999            // Add the new setting to mPackages
8000            mPackages.put(pkg.applicationInfo.packageName, pkg);
8001            // Make sure we don't accidentally delete its data.
8002            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8003            while (iter.hasNext()) {
8004                PackageCleanItem item = iter.next();
8005                if (pkgName.equals(item.packageName)) {
8006                    iter.remove();
8007                }
8008            }
8009
8010            // Take care of first install / last update times.
8011            if (currentTime != 0) {
8012                if (pkgSetting.firstInstallTime == 0) {
8013                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8014                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8015                    pkgSetting.lastUpdateTime = currentTime;
8016                }
8017            } else if (pkgSetting.firstInstallTime == 0) {
8018                // We need *something*.  Take time time stamp of the file.
8019                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8020            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8021                if (scanFileTime != pkgSetting.timeStamp) {
8022                    // A package on the system image has changed; consider this
8023                    // to be an update.
8024                    pkgSetting.lastUpdateTime = scanFileTime;
8025                }
8026            }
8027
8028            // Add the package's KeySets to the global KeySetManagerService
8029            ksms.addScannedPackageLPw(pkg);
8030
8031            int N = pkg.providers.size();
8032            StringBuilder r = null;
8033            int i;
8034            for (i=0; i<N; i++) {
8035                PackageParser.Provider p = pkg.providers.get(i);
8036                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8037                        p.info.processName, pkg.applicationInfo.uid);
8038                mProviders.addProvider(p);
8039                p.syncable = p.info.isSyncable;
8040                if (p.info.authority != null) {
8041                    String names[] = p.info.authority.split(";");
8042                    p.info.authority = null;
8043                    for (int j = 0; j < names.length; j++) {
8044                        if (j == 1 && p.syncable) {
8045                            // We only want the first authority for a provider to possibly be
8046                            // syncable, so if we already added this provider using a different
8047                            // authority clear the syncable flag. We copy the provider before
8048                            // changing it because the mProviders object contains a reference
8049                            // to a provider that we don't want to change.
8050                            // Only do this for the second authority since the resulting provider
8051                            // object can be the same for all future authorities for this provider.
8052                            p = new PackageParser.Provider(p);
8053                            p.syncable = false;
8054                        }
8055                        if (!mProvidersByAuthority.containsKey(names[j])) {
8056                            mProvidersByAuthority.put(names[j], p);
8057                            if (p.info.authority == null) {
8058                                p.info.authority = names[j];
8059                            } else {
8060                                p.info.authority = p.info.authority + ";" + names[j];
8061                            }
8062                            if (DEBUG_PACKAGE_SCANNING) {
8063                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
8064                                    Log.d(TAG, "Registered content provider: " + names[j]
8065                                            + ", className = " + p.info.name + ", isSyncable = "
8066                                            + p.info.isSyncable);
8067                            }
8068                        } else {
8069                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8070                            Slog.w(TAG, "Skipping provider name " + names[j] +
8071                                    " (in package " + pkg.applicationInfo.packageName +
8072                                    "): name already used by "
8073                                    + ((other != null && other.getComponentName() != null)
8074                                            ? other.getComponentName().getPackageName() : "?"));
8075                        }
8076                    }
8077                }
8078                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8079                    if (r == null) {
8080                        r = new StringBuilder(256);
8081                    } else {
8082                        r.append(' ');
8083                    }
8084                    r.append(p.info.name);
8085                }
8086            }
8087            if (r != null) {
8088                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8089            }
8090
8091            N = pkg.services.size();
8092            r = null;
8093            for (i=0; i<N; i++) {
8094                PackageParser.Service s = pkg.services.get(i);
8095                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8096                        s.info.processName, pkg.applicationInfo.uid);
8097                mServices.addService(s);
8098                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8099                    if (r == null) {
8100                        r = new StringBuilder(256);
8101                    } else {
8102                        r.append(' ');
8103                    }
8104                    r.append(s.info.name);
8105                }
8106            }
8107            if (r != null) {
8108                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8109            }
8110
8111            N = pkg.receivers.size();
8112            r = null;
8113            for (i=0; i<N; i++) {
8114                PackageParser.Activity a = pkg.receivers.get(i);
8115                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8116                        a.info.processName, pkg.applicationInfo.uid);
8117                mReceivers.addActivity(a, "receiver");
8118                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8119                    if (r == null) {
8120                        r = new StringBuilder(256);
8121                    } else {
8122                        r.append(' ');
8123                    }
8124                    r.append(a.info.name);
8125                }
8126            }
8127            if (r != null) {
8128                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8129            }
8130
8131            N = pkg.activities.size();
8132            r = null;
8133            for (i=0; i<N; i++) {
8134                PackageParser.Activity a = pkg.activities.get(i);
8135                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8136                        a.info.processName, pkg.applicationInfo.uid);
8137                mActivities.addActivity(a, "activity");
8138                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8139                    if (r == null) {
8140                        r = new StringBuilder(256);
8141                    } else {
8142                        r.append(' ');
8143                    }
8144                    r.append(a.info.name);
8145                }
8146            }
8147            if (r != null) {
8148                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8149            }
8150
8151            N = pkg.permissionGroups.size();
8152            r = null;
8153            for (i=0; i<N; i++) {
8154                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8155                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8156                if (cur == null) {
8157                    mPermissionGroups.put(pg.info.name, pg);
8158                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8159                        if (r == null) {
8160                            r = new StringBuilder(256);
8161                        } else {
8162                            r.append(' ');
8163                        }
8164                        r.append(pg.info.name);
8165                    }
8166                } else {
8167                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8168                            + pg.info.packageName + " ignored: original from "
8169                            + cur.info.packageName);
8170                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8171                        if (r == null) {
8172                            r = new StringBuilder(256);
8173                        } else {
8174                            r.append(' ');
8175                        }
8176                        r.append("DUP:");
8177                        r.append(pg.info.name);
8178                    }
8179                }
8180            }
8181            if (r != null) {
8182                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8183            }
8184
8185            N = pkg.permissions.size();
8186            r = null;
8187            for (i=0; i<N; i++) {
8188                PackageParser.Permission p = pkg.permissions.get(i);
8189
8190                // Assume by default that we did not install this permission into the system.
8191                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8192
8193                // Now that permission groups have a special meaning, we ignore permission
8194                // groups for legacy apps to prevent unexpected behavior. In particular,
8195                // permissions for one app being granted to someone just becase they happen
8196                // to be in a group defined by another app (before this had no implications).
8197                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8198                    p.group = mPermissionGroups.get(p.info.group);
8199                    // Warn for a permission in an unknown group.
8200                    if (p.info.group != null && p.group == null) {
8201                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8202                                + p.info.packageName + " in an unknown group " + p.info.group);
8203                    }
8204                }
8205
8206                ArrayMap<String, BasePermission> permissionMap =
8207                        p.tree ? mSettings.mPermissionTrees
8208                                : mSettings.mPermissions;
8209                BasePermission bp = permissionMap.get(p.info.name);
8210
8211                // Allow system apps to redefine non-system permissions
8212                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8213                    final boolean currentOwnerIsSystem = (bp.perm != null
8214                            && isSystemApp(bp.perm.owner));
8215                    if (isSystemApp(p.owner)) {
8216                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8217                            // It's a built-in permission and no owner, take ownership now
8218                            bp.packageSetting = pkgSetting;
8219                            bp.perm = p;
8220                            bp.uid = pkg.applicationInfo.uid;
8221                            bp.sourcePackage = p.info.packageName;
8222                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8223                        } else if (!currentOwnerIsSystem) {
8224                            String msg = "New decl " + p.owner + " of permission  "
8225                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8226                            reportSettingsProblem(Log.WARN, msg);
8227                            bp = null;
8228                        }
8229                    }
8230                }
8231
8232                if (bp == null) {
8233                    bp = new BasePermission(p.info.name, p.info.packageName,
8234                            BasePermission.TYPE_NORMAL);
8235                    permissionMap.put(p.info.name, bp);
8236                }
8237
8238                if (bp.perm == null) {
8239                    if (bp.sourcePackage == null
8240                            || bp.sourcePackage.equals(p.info.packageName)) {
8241                        BasePermission tree = findPermissionTreeLP(p.info.name);
8242                        if (tree == null
8243                                || tree.sourcePackage.equals(p.info.packageName)) {
8244                            bp.packageSetting = pkgSetting;
8245                            bp.perm = p;
8246                            bp.uid = pkg.applicationInfo.uid;
8247                            bp.sourcePackage = p.info.packageName;
8248                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8249                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8250                                if (r == null) {
8251                                    r = new StringBuilder(256);
8252                                } else {
8253                                    r.append(' ');
8254                                }
8255                                r.append(p.info.name);
8256                            }
8257                        } else {
8258                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8259                                    + p.info.packageName + " ignored: base tree "
8260                                    + tree.name + " is from package "
8261                                    + tree.sourcePackage);
8262                        }
8263                    } else {
8264                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8265                                + p.info.packageName + " ignored: original from "
8266                                + bp.sourcePackage);
8267                    }
8268                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8269                    if (r == null) {
8270                        r = new StringBuilder(256);
8271                    } else {
8272                        r.append(' ');
8273                    }
8274                    r.append("DUP:");
8275                    r.append(p.info.name);
8276                }
8277                if (bp.perm == p) {
8278                    bp.protectionLevel = p.info.protectionLevel;
8279                }
8280            }
8281
8282            if (r != null) {
8283                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8284            }
8285
8286            N = pkg.instrumentation.size();
8287            r = null;
8288            for (i=0; i<N; i++) {
8289                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8290                a.info.packageName = pkg.applicationInfo.packageName;
8291                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8292                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8293                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8294                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8295                a.info.dataDir = pkg.applicationInfo.dataDir;
8296                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8297                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8298
8299                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8300                // need other information about the application, like the ABI and what not ?
8301                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8302                mInstrumentation.put(a.getComponentName(), a);
8303                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8304                    if (r == null) {
8305                        r = new StringBuilder(256);
8306                    } else {
8307                        r.append(' ');
8308                    }
8309                    r.append(a.info.name);
8310                }
8311            }
8312            if (r != null) {
8313                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8314            }
8315
8316            if (pkg.protectedBroadcasts != null) {
8317                N = pkg.protectedBroadcasts.size();
8318                for (i=0; i<N; i++) {
8319                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8320                }
8321            }
8322
8323            pkgSetting.setTimeStamp(scanFileTime);
8324
8325            // Create idmap files for pairs of (packages, overlay packages).
8326            // Note: "android", ie framework-res.apk, is handled by native layers.
8327            if (pkg.mOverlayTarget != null) {
8328                // This is an overlay package.
8329                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8330                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8331                        mOverlays.put(pkg.mOverlayTarget,
8332                                new ArrayMap<String, PackageParser.Package>());
8333                    }
8334                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8335                    map.put(pkg.packageName, pkg);
8336                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8337                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8338                        createIdmapFailed = true;
8339                    }
8340                }
8341            } else if (mOverlays.containsKey(pkg.packageName) &&
8342                    !pkg.packageName.equals("android")) {
8343                // This is a regular package, with one or more known overlay packages.
8344                createIdmapsForPackageLI(pkg);
8345            }
8346        }
8347
8348        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8349
8350        if (createIdmapFailed) {
8351            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8352                    "scanPackageLI failed to createIdmap");
8353        }
8354        return pkg;
8355    }
8356
8357    /**
8358     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8359     * is derived purely on the basis of the contents of {@code scanFile} and
8360     * {@code cpuAbiOverride}.
8361     *
8362     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8363     */
8364    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8365                                 String cpuAbiOverride, boolean extractLibs)
8366            throws PackageManagerException {
8367        // TODO: We can probably be smarter about this stuff. For installed apps,
8368        // we can calculate this information at install time once and for all. For
8369        // system apps, we can probably assume that this information doesn't change
8370        // after the first boot scan. As things stand, we do lots of unnecessary work.
8371
8372        // Give ourselves some initial paths; we'll come back for another
8373        // pass once we've determined ABI below.
8374        setNativeLibraryPaths(pkg);
8375
8376        // We would never need to extract libs for forward-locked and external packages,
8377        // since the container service will do it for us. We shouldn't attempt to
8378        // extract libs from system app when it was not updated.
8379        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8380                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8381            extractLibs = false;
8382        }
8383
8384        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8385        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8386
8387        NativeLibraryHelper.Handle handle = null;
8388        try {
8389            handle = NativeLibraryHelper.Handle.create(pkg);
8390            // TODO(multiArch): This can be null for apps that didn't go through the
8391            // usual installation process. We can calculate it again, like we
8392            // do during install time.
8393            //
8394            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8395            // unnecessary.
8396            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8397
8398            // Null out the abis so that they can be recalculated.
8399            pkg.applicationInfo.primaryCpuAbi = null;
8400            pkg.applicationInfo.secondaryCpuAbi = null;
8401            if (isMultiArch(pkg.applicationInfo)) {
8402                // Warn if we've set an abiOverride for multi-lib packages..
8403                // By definition, we need to copy both 32 and 64 bit libraries for
8404                // such packages.
8405                if (pkg.cpuAbiOverride != null
8406                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8407                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8408                }
8409
8410                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8411                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8412                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8413                    if (extractLibs) {
8414                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8415                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8416                                useIsaSpecificSubdirs);
8417                    } else {
8418                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8419                    }
8420                }
8421
8422                maybeThrowExceptionForMultiArchCopy(
8423                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8424
8425                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8426                    if (extractLibs) {
8427                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8428                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8429                                useIsaSpecificSubdirs);
8430                    } else {
8431                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8432                    }
8433                }
8434
8435                maybeThrowExceptionForMultiArchCopy(
8436                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8437
8438                if (abi64 >= 0) {
8439                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8440                }
8441
8442                if (abi32 >= 0) {
8443                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8444                    if (abi64 >= 0) {
8445                        if (cpuAbiOverride == null && pkg.use32bitAbi) {
8446                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8447                            pkg.applicationInfo.primaryCpuAbi = abi;
8448                        } else {
8449                            pkg.applicationInfo.secondaryCpuAbi = abi;
8450                        }
8451                    } else {
8452                        pkg.applicationInfo.primaryCpuAbi = abi;
8453                    }
8454                }
8455
8456            } else {
8457                String[] abiList = (cpuAbiOverride != null) ?
8458                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8459
8460                // Enable gross and lame hacks for apps that are built with old
8461                // SDK tools. We must scan their APKs for renderscript bitcode and
8462                // not launch them if it's present. Don't bother checking on devices
8463                // that don't have 64 bit support.
8464                boolean needsRenderScriptOverride = false;
8465                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8466                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8467                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8468                    needsRenderScriptOverride = true;
8469                }
8470
8471                final int copyRet;
8472                if (extractLibs) {
8473                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8474                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8475                } else {
8476                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8477                }
8478
8479                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8480                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8481                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8482                }
8483
8484                if (copyRet >= 0) {
8485                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8486                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8487                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8488                } else if (needsRenderScriptOverride) {
8489                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8490                }
8491            }
8492        } catch (IOException ioe) {
8493            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8494        } finally {
8495            IoUtils.closeQuietly(handle);
8496        }
8497
8498        // Now that we've calculated the ABIs and determined if it's an internal app,
8499        // we will go ahead and populate the nativeLibraryPath.
8500        setNativeLibraryPaths(pkg);
8501    }
8502
8503    /**
8504     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8505     * i.e, so that all packages can be run inside a single process if required.
8506     *
8507     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8508     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8509     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8510     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8511     * updating a package that belongs to a shared user.
8512     *
8513     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8514     * adds unnecessary complexity.
8515     */
8516    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8517            PackageParser.Package scannedPackage, boolean bootComplete) {
8518        String requiredInstructionSet = null;
8519        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8520            requiredInstructionSet = VMRuntime.getInstructionSet(
8521                     scannedPackage.applicationInfo.primaryCpuAbi);
8522        }
8523
8524        PackageSetting requirer = null;
8525        for (PackageSetting ps : packagesForUser) {
8526            // If packagesForUser contains scannedPackage, we skip it. This will happen
8527            // when scannedPackage is an update of an existing package. Without this check,
8528            // we will never be able to change the ABI of any package belonging to a shared
8529            // user, even if it's compatible with other packages.
8530            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8531                if (ps.primaryCpuAbiString == null) {
8532                    continue;
8533                }
8534
8535                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8536                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8537                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8538                    // this but there's not much we can do.
8539                    String errorMessage = "Instruction set mismatch, "
8540                            + ((requirer == null) ? "[caller]" : requirer)
8541                            + " requires " + requiredInstructionSet + " whereas " + ps
8542                            + " requires " + instructionSet;
8543                    Slog.w(TAG, errorMessage);
8544                }
8545
8546                if (requiredInstructionSet == null) {
8547                    requiredInstructionSet = instructionSet;
8548                    requirer = ps;
8549                }
8550            }
8551        }
8552
8553        if (requiredInstructionSet != null) {
8554            String adjustedAbi;
8555            if (requirer != null) {
8556                // requirer != null implies that either scannedPackage was null or that scannedPackage
8557                // did not require an ABI, in which case we have to adjust scannedPackage to match
8558                // the ABI of the set (which is the same as requirer's ABI)
8559                adjustedAbi = requirer.primaryCpuAbiString;
8560                if (scannedPackage != null) {
8561                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8562                }
8563            } else {
8564                // requirer == null implies that we're updating all ABIs in the set to
8565                // match scannedPackage.
8566                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8567            }
8568
8569            for (PackageSetting ps : packagesForUser) {
8570                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8571                    if (ps.primaryCpuAbiString != null) {
8572                        continue;
8573                    }
8574
8575                    ps.primaryCpuAbiString = adjustedAbi;
8576                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8577                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8578                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8579                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8580                                + " (requirer="
8581                                + (requirer == null ? "null" : requirer.pkg.packageName)
8582                                + ", scannedPackage="
8583                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8584                                + ")");
8585                        try {
8586                            mInstaller.rmdex(ps.codePathString,
8587                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8588                        } catch (InstallerException ignored) {
8589                        }
8590                    }
8591                }
8592            }
8593        }
8594    }
8595
8596    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8597        synchronized (mPackages) {
8598            mResolverReplaced = true;
8599            // Set up information for custom user intent resolution activity.
8600            mResolveActivity.applicationInfo = pkg.applicationInfo;
8601            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8602            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8603            mResolveActivity.processName = pkg.applicationInfo.packageName;
8604            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8605            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8606                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8607            mResolveActivity.theme = 0;
8608            mResolveActivity.exported = true;
8609            mResolveActivity.enabled = true;
8610            mResolveInfo.activityInfo = mResolveActivity;
8611            mResolveInfo.priority = 0;
8612            mResolveInfo.preferredOrder = 0;
8613            mResolveInfo.match = 0;
8614            mResolveComponentName = mCustomResolverComponentName;
8615            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8616                    mResolveComponentName);
8617        }
8618    }
8619
8620    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8621        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8622
8623        // Set up information for ephemeral installer activity
8624        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8625        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8626        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8627        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8628        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8629        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8630                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8631        mEphemeralInstallerActivity.theme = 0;
8632        mEphemeralInstallerActivity.exported = true;
8633        mEphemeralInstallerActivity.enabled = true;
8634        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8635        mEphemeralInstallerInfo.priority = 0;
8636        mEphemeralInstallerInfo.preferredOrder = 0;
8637        mEphemeralInstallerInfo.match = 0;
8638
8639        if (DEBUG_EPHEMERAL) {
8640            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8641        }
8642    }
8643
8644    private static String calculateBundledApkRoot(final String codePathString) {
8645        final File codePath = new File(codePathString);
8646        final File codeRoot;
8647        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8648            codeRoot = Environment.getRootDirectory();
8649        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8650            codeRoot = Environment.getOemDirectory();
8651        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8652            codeRoot = Environment.getVendorDirectory();
8653        } else {
8654            // Unrecognized code path; take its top real segment as the apk root:
8655            // e.g. /something/app/blah.apk => /something
8656            try {
8657                File f = codePath.getCanonicalFile();
8658                File parent = f.getParentFile();    // non-null because codePath is a file
8659                File tmp;
8660                while ((tmp = parent.getParentFile()) != null) {
8661                    f = parent;
8662                    parent = tmp;
8663                }
8664                codeRoot = f;
8665                Slog.w(TAG, "Unrecognized code path "
8666                        + codePath + " - using " + codeRoot);
8667            } catch (IOException e) {
8668                // Can't canonicalize the code path -- shenanigans?
8669                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8670                return Environment.getRootDirectory().getPath();
8671            }
8672        }
8673        return codeRoot.getPath();
8674    }
8675
8676    /**
8677     * Derive and set the location of native libraries for the given package,
8678     * which varies depending on where and how the package was installed.
8679     */
8680    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8681        final ApplicationInfo info = pkg.applicationInfo;
8682        final String codePath = pkg.codePath;
8683        final File codeFile = new File(codePath);
8684        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8685        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8686
8687        info.nativeLibraryRootDir = null;
8688        info.nativeLibraryRootRequiresIsa = false;
8689        info.nativeLibraryDir = null;
8690        info.secondaryNativeLibraryDir = null;
8691
8692        if (isApkFile(codeFile)) {
8693            // Monolithic install
8694            if (bundledApp) {
8695                // If "/system/lib64/apkname" exists, assume that is the per-package
8696                // native library directory to use; otherwise use "/system/lib/apkname".
8697                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8698                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8699                        getPrimaryInstructionSet(info));
8700
8701                // This is a bundled system app so choose the path based on the ABI.
8702                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8703                // is just the default path.
8704                final String apkName = deriveCodePathName(codePath);
8705                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8706                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8707                        apkName).getAbsolutePath();
8708
8709                if (info.secondaryCpuAbi != null) {
8710                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8711                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8712                            secondaryLibDir, apkName).getAbsolutePath();
8713                }
8714            } else if (asecApp) {
8715                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8716                        .getAbsolutePath();
8717            } else {
8718                final String apkName = deriveCodePathName(codePath);
8719                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8720                        .getAbsolutePath();
8721            }
8722
8723            info.nativeLibraryRootRequiresIsa = false;
8724            info.nativeLibraryDir = info.nativeLibraryRootDir;
8725        } else {
8726            // Cluster install
8727            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8728            info.nativeLibraryRootRequiresIsa = true;
8729
8730            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8731                    getPrimaryInstructionSet(info)).getAbsolutePath();
8732
8733            if (info.secondaryCpuAbi != null) {
8734                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8735                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8736            }
8737        }
8738    }
8739
8740    /**
8741     * Calculate the abis and roots for a bundled app. These can uniquely
8742     * be determined from the contents of the system partition, i.e whether
8743     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8744     * of this information, and instead assume that the system was built
8745     * sensibly.
8746     */
8747    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8748                                           PackageSetting pkgSetting) {
8749        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8750
8751        // If "/system/lib64/apkname" exists, assume that is the per-package
8752        // native library directory to use; otherwise use "/system/lib/apkname".
8753        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8754        setBundledAppAbi(pkg, apkRoot, apkName);
8755        // pkgSetting might be null during rescan following uninstall of updates
8756        // to a bundled app, so accommodate that possibility.  The settings in
8757        // that case will be established later from the parsed package.
8758        //
8759        // If the settings aren't null, sync them up with what we've just derived.
8760        // note that apkRoot isn't stored in the package settings.
8761        if (pkgSetting != null) {
8762            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8763            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8764        }
8765    }
8766
8767    /**
8768     * Deduces the ABI of a bundled app and sets the relevant fields on the
8769     * parsed pkg object.
8770     *
8771     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8772     *        under which system libraries are installed.
8773     * @param apkName the name of the installed package.
8774     */
8775    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8776        final File codeFile = new File(pkg.codePath);
8777
8778        final boolean has64BitLibs;
8779        final boolean has32BitLibs;
8780        if (isApkFile(codeFile)) {
8781            // Monolithic install
8782            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8783            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8784        } else {
8785            // Cluster install
8786            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8787            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8788                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8789                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8790                has64BitLibs = (new File(rootDir, isa)).exists();
8791            } else {
8792                has64BitLibs = false;
8793            }
8794            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8795                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8796                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8797                has32BitLibs = (new File(rootDir, isa)).exists();
8798            } else {
8799                has32BitLibs = false;
8800            }
8801        }
8802
8803        if (has64BitLibs && !has32BitLibs) {
8804            // The package has 64 bit libs, but not 32 bit libs. Its primary
8805            // ABI should be 64 bit. We can safely assume here that the bundled
8806            // native libraries correspond to the most preferred ABI in the list.
8807
8808            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8809            pkg.applicationInfo.secondaryCpuAbi = null;
8810        } else if (has32BitLibs && !has64BitLibs) {
8811            // The package has 32 bit libs but not 64 bit libs. Its primary
8812            // ABI should be 32 bit.
8813
8814            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8815            pkg.applicationInfo.secondaryCpuAbi = null;
8816        } else if (has32BitLibs && has64BitLibs) {
8817            // The application has both 64 and 32 bit bundled libraries. We check
8818            // here that the app declares multiArch support, and warn if it doesn't.
8819            //
8820            // We will be lenient here and record both ABIs. The primary will be the
8821            // ABI that's higher on the list, i.e, a device that's configured to prefer
8822            // 64 bit apps will see a 64 bit primary ABI,
8823
8824            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8825                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8826            }
8827
8828            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8829                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8830                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8831            } else {
8832                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8833                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8834            }
8835        } else {
8836            pkg.applicationInfo.primaryCpuAbi = null;
8837            pkg.applicationInfo.secondaryCpuAbi = null;
8838        }
8839    }
8840
8841    private void killPackage(PackageParser.Package pkg, String reason) {
8842        // Kill the parent package
8843        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8844        // Kill the child packages
8845        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8846        for (int i = 0; i < childCount; i++) {
8847            PackageParser.Package childPkg = pkg.childPackages.get(i);
8848            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8849        }
8850    }
8851
8852    private void killApplication(String pkgName, int appId, String reason) {
8853        // Request the ActivityManager to kill the process(only for existing packages)
8854        // so that we do not end up in a confused state while the user is still using the older
8855        // version of the application while the new one gets installed.
8856        IActivityManager am = ActivityManagerNative.getDefault();
8857        if (am != null) {
8858            try {
8859                am.killApplicationWithAppId(pkgName, appId, reason);
8860            } catch (RemoteException e) {
8861            }
8862        }
8863    }
8864
8865    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
8866        // Remove the parent package setting
8867        PackageSetting ps = (PackageSetting) pkg.mExtras;
8868        if (ps != null) {
8869            removePackageLI(ps, chatty);
8870        }
8871        // Remove the child package setting
8872        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8873        for (int i = 0; i < childCount; i++) {
8874            PackageParser.Package childPkg = pkg.childPackages.get(i);
8875            ps = (PackageSetting) childPkg.mExtras;
8876            if (ps != null) {
8877                removePackageLI(ps, chatty);
8878            }
8879        }
8880    }
8881
8882    void removePackageLI(PackageSetting ps, boolean chatty) {
8883        if (DEBUG_INSTALL) {
8884            if (chatty)
8885                Log.d(TAG, "Removing package " + ps.name);
8886        }
8887
8888        // writer
8889        synchronized (mPackages) {
8890            mPackages.remove(ps.name);
8891            final PackageParser.Package pkg = ps.pkg;
8892            if (pkg != null) {
8893                cleanPackageDataStructuresLILPw(pkg, chatty);
8894            }
8895        }
8896    }
8897
8898    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
8899        if (DEBUG_INSTALL) {
8900            if (chatty)
8901                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
8902        }
8903
8904        // writer
8905        synchronized (mPackages) {
8906            // Remove the parent package
8907            mPackages.remove(pkg.applicationInfo.packageName);
8908            cleanPackageDataStructuresLILPw(pkg, chatty);
8909
8910            // Remove the child packages
8911            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8912            for (int i = 0; i < childCount; i++) {
8913                PackageParser.Package childPkg = pkg.childPackages.get(i);
8914                mPackages.remove(childPkg.applicationInfo.packageName);
8915                cleanPackageDataStructuresLILPw(childPkg, chatty);
8916            }
8917        }
8918    }
8919
8920    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
8921        int N = pkg.providers.size();
8922        StringBuilder r = null;
8923        int i;
8924        for (i=0; i<N; i++) {
8925            PackageParser.Provider p = pkg.providers.get(i);
8926            mProviders.removeProvider(p);
8927            if (p.info.authority == null) {
8928
8929                /* There was another ContentProvider with this authority when
8930                 * this app was installed so this authority is null,
8931                 * Ignore it as we don't have to unregister the provider.
8932                 */
8933                continue;
8934            }
8935            String names[] = p.info.authority.split(";");
8936            for (int j = 0; j < names.length; j++) {
8937                if (mProvidersByAuthority.get(names[j]) == p) {
8938                    mProvidersByAuthority.remove(names[j]);
8939                    if (DEBUG_REMOVE) {
8940                        if (chatty)
8941                            Log.d(TAG, "Unregistered content provider: " + names[j]
8942                                    + ", className = " + p.info.name + ", isSyncable = "
8943                                    + p.info.isSyncable);
8944                    }
8945                }
8946            }
8947            if (DEBUG_REMOVE && chatty) {
8948                if (r == null) {
8949                    r = new StringBuilder(256);
8950                } else {
8951                    r.append(' ');
8952                }
8953                r.append(p.info.name);
8954            }
8955        }
8956        if (r != null) {
8957            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
8958        }
8959
8960        N = pkg.services.size();
8961        r = null;
8962        for (i=0; i<N; i++) {
8963            PackageParser.Service s = pkg.services.get(i);
8964            mServices.removeService(s);
8965            if (chatty) {
8966                if (r == null) {
8967                    r = new StringBuilder(256);
8968                } else {
8969                    r.append(' ');
8970                }
8971                r.append(s.info.name);
8972            }
8973        }
8974        if (r != null) {
8975            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
8976        }
8977
8978        N = pkg.receivers.size();
8979        r = null;
8980        for (i=0; i<N; i++) {
8981            PackageParser.Activity a = pkg.receivers.get(i);
8982            mReceivers.removeActivity(a, "receiver");
8983            if (DEBUG_REMOVE && chatty) {
8984                if (r == null) {
8985                    r = new StringBuilder(256);
8986                } else {
8987                    r.append(' ');
8988                }
8989                r.append(a.info.name);
8990            }
8991        }
8992        if (r != null) {
8993            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
8994        }
8995
8996        N = pkg.activities.size();
8997        r = null;
8998        for (i=0; i<N; i++) {
8999            PackageParser.Activity a = pkg.activities.get(i);
9000            mActivities.removeActivity(a, "activity");
9001            if (DEBUG_REMOVE && chatty) {
9002                if (r == null) {
9003                    r = new StringBuilder(256);
9004                } else {
9005                    r.append(' ');
9006                }
9007                r.append(a.info.name);
9008            }
9009        }
9010        if (r != null) {
9011            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9012        }
9013
9014        N = pkg.permissions.size();
9015        r = null;
9016        for (i=0; i<N; i++) {
9017            PackageParser.Permission p = pkg.permissions.get(i);
9018            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9019            if (bp == null) {
9020                bp = mSettings.mPermissionTrees.get(p.info.name);
9021            }
9022            if (bp != null && bp.perm == p) {
9023                bp.perm = null;
9024                if (DEBUG_REMOVE && chatty) {
9025                    if (r == null) {
9026                        r = new StringBuilder(256);
9027                    } else {
9028                        r.append(' ');
9029                    }
9030                    r.append(p.info.name);
9031                }
9032            }
9033            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9034                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9035                if (appOpPkgs != null) {
9036                    appOpPkgs.remove(pkg.packageName);
9037                }
9038            }
9039        }
9040        if (r != null) {
9041            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9042        }
9043
9044        N = pkg.requestedPermissions.size();
9045        r = null;
9046        for (i=0; i<N; i++) {
9047            String perm = pkg.requestedPermissions.get(i);
9048            BasePermission bp = mSettings.mPermissions.get(perm);
9049            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9050                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9051                if (appOpPkgs != null) {
9052                    appOpPkgs.remove(pkg.packageName);
9053                    if (appOpPkgs.isEmpty()) {
9054                        mAppOpPermissionPackages.remove(perm);
9055                    }
9056                }
9057            }
9058        }
9059        if (r != null) {
9060            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9061        }
9062
9063        N = pkg.instrumentation.size();
9064        r = null;
9065        for (i=0; i<N; i++) {
9066            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9067            mInstrumentation.remove(a.getComponentName());
9068            if (DEBUG_REMOVE && chatty) {
9069                if (r == null) {
9070                    r = new StringBuilder(256);
9071                } else {
9072                    r.append(' ');
9073                }
9074                r.append(a.info.name);
9075            }
9076        }
9077        if (r != null) {
9078            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9079        }
9080
9081        r = null;
9082        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9083            // Only system apps can hold shared libraries.
9084            if (pkg.libraryNames != null) {
9085                for (i=0; i<pkg.libraryNames.size(); i++) {
9086                    String name = pkg.libraryNames.get(i);
9087                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9088                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9089                        mSharedLibraries.remove(name);
9090                        if (DEBUG_REMOVE && chatty) {
9091                            if (r == null) {
9092                                r = new StringBuilder(256);
9093                            } else {
9094                                r.append(' ');
9095                            }
9096                            r.append(name);
9097                        }
9098                    }
9099                }
9100            }
9101        }
9102        if (r != null) {
9103            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9104        }
9105    }
9106
9107    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9108        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9109            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9110                return true;
9111            }
9112        }
9113        return false;
9114    }
9115
9116    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9117    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9118    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9119
9120    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9121        // Update the parent permissions
9122        updatePermissionsLPw(pkg.packageName, pkg, flags);
9123        // Update the child permissions
9124        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9125        for (int i = 0; i < childCount; i++) {
9126            PackageParser.Package childPkg = pkg.childPackages.get(i);
9127            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9128        }
9129    }
9130
9131    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9132            int flags) {
9133        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9134        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9135    }
9136
9137    private void updatePermissionsLPw(String changingPkg,
9138            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9139        // Make sure there are no dangling permission trees.
9140        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9141        while (it.hasNext()) {
9142            final BasePermission bp = it.next();
9143            if (bp.packageSetting == null) {
9144                // We may not yet have parsed the package, so just see if
9145                // we still know about its settings.
9146                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9147            }
9148            if (bp.packageSetting == null) {
9149                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9150                        + " from package " + bp.sourcePackage);
9151                it.remove();
9152            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9153                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9154                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9155                            + " from package " + bp.sourcePackage);
9156                    flags |= UPDATE_PERMISSIONS_ALL;
9157                    it.remove();
9158                }
9159            }
9160        }
9161
9162        // Make sure all dynamic permissions have been assigned to a package,
9163        // and make sure there are no dangling permissions.
9164        it = mSettings.mPermissions.values().iterator();
9165        while (it.hasNext()) {
9166            final BasePermission bp = it.next();
9167            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9168                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9169                        + bp.name + " pkg=" + bp.sourcePackage
9170                        + " info=" + bp.pendingInfo);
9171                if (bp.packageSetting == null && bp.pendingInfo != null) {
9172                    final BasePermission tree = findPermissionTreeLP(bp.name);
9173                    if (tree != null && tree.perm != null) {
9174                        bp.packageSetting = tree.packageSetting;
9175                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9176                                new PermissionInfo(bp.pendingInfo));
9177                        bp.perm.info.packageName = tree.perm.info.packageName;
9178                        bp.perm.info.name = bp.name;
9179                        bp.uid = tree.uid;
9180                    }
9181                }
9182            }
9183            if (bp.packageSetting == null) {
9184                // We may not yet have parsed the package, so just see if
9185                // we still know about its settings.
9186                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9187            }
9188            if (bp.packageSetting == null) {
9189                Slog.w(TAG, "Removing dangling permission: " + bp.name
9190                        + " from package " + bp.sourcePackage);
9191                it.remove();
9192            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9193                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9194                    Slog.i(TAG, "Removing old permission: " + bp.name
9195                            + " from package " + bp.sourcePackage);
9196                    flags |= UPDATE_PERMISSIONS_ALL;
9197                    it.remove();
9198                }
9199            }
9200        }
9201
9202        // Now update the permissions for all packages, in particular
9203        // replace the granted permissions of the system packages.
9204        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9205            for (PackageParser.Package pkg : mPackages.values()) {
9206                if (pkg != pkgInfo) {
9207                    // Only replace for packages on requested volume
9208                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9209                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9210                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9211                    grantPermissionsLPw(pkg, replace, changingPkg);
9212                }
9213            }
9214        }
9215
9216        if (pkgInfo != null) {
9217            // Only replace for packages on requested volume
9218            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9219            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9220                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9221            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9222        }
9223    }
9224
9225    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9226            String packageOfInterest) {
9227        // IMPORTANT: There are two types of permissions: install and runtime.
9228        // Install time permissions are granted when the app is installed to
9229        // all device users and users added in the future. Runtime permissions
9230        // are granted at runtime explicitly to specific users. Normal and signature
9231        // protected permissions are install time permissions. Dangerous permissions
9232        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9233        // otherwise they are runtime permissions. This function does not manage
9234        // runtime permissions except for the case an app targeting Lollipop MR1
9235        // being upgraded to target a newer SDK, in which case dangerous permissions
9236        // are transformed from install time to runtime ones.
9237
9238        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9239        if (ps == null) {
9240            return;
9241        }
9242
9243        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9244
9245        PermissionsState permissionsState = ps.getPermissionsState();
9246        PermissionsState origPermissions = permissionsState;
9247
9248        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9249
9250        boolean runtimePermissionsRevoked = false;
9251        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9252
9253        boolean changedInstallPermission = false;
9254
9255        if (replace) {
9256            ps.installPermissionsFixed = false;
9257            if (!ps.isSharedUser()) {
9258                origPermissions = new PermissionsState(permissionsState);
9259                permissionsState.reset();
9260            } else {
9261                // We need to know only about runtime permission changes since the
9262                // calling code always writes the install permissions state but
9263                // the runtime ones are written only if changed. The only cases of
9264                // changed runtime permissions here are promotion of an install to
9265                // runtime and revocation of a runtime from a shared user.
9266                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9267                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9268                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9269                    runtimePermissionsRevoked = true;
9270                }
9271            }
9272        }
9273
9274        permissionsState.setGlobalGids(mGlobalGids);
9275
9276        final int N = pkg.requestedPermissions.size();
9277        for (int i=0; i<N; i++) {
9278            final String name = pkg.requestedPermissions.get(i);
9279            final BasePermission bp = mSettings.mPermissions.get(name);
9280
9281            if (DEBUG_INSTALL) {
9282                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9283            }
9284
9285            if (bp == null || bp.packageSetting == null) {
9286                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9287                    Slog.w(TAG, "Unknown permission " + name
9288                            + " in package " + pkg.packageName);
9289                }
9290                continue;
9291            }
9292
9293            final String perm = bp.name;
9294            boolean allowedSig = false;
9295            int grant = GRANT_DENIED;
9296
9297            // Keep track of app op permissions.
9298            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9299                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9300                if (pkgs == null) {
9301                    pkgs = new ArraySet<>();
9302                    mAppOpPermissionPackages.put(bp.name, pkgs);
9303                }
9304                pkgs.add(pkg.packageName);
9305            }
9306
9307            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9308            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9309                    >= Build.VERSION_CODES.M;
9310            switch (level) {
9311                case PermissionInfo.PROTECTION_NORMAL: {
9312                    // For all apps normal permissions are install time ones.
9313                    grant = GRANT_INSTALL;
9314                } break;
9315
9316                case PermissionInfo.PROTECTION_DANGEROUS: {
9317                    // If a permission review is required for legacy apps we represent
9318                    // their permissions as always granted runtime ones since we need
9319                    // to keep the review required permission flag per user while an
9320                    // install permission's state is shared across all users.
9321                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9322                        // For legacy apps dangerous permissions are install time ones.
9323                        grant = GRANT_INSTALL;
9324                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9325                        // For legacy apps that became modern, install becomes runtime.
9326                        grant = GRANT_UPGRADE;
9327                    } else if (mPromoteSystemApps
9328                            && isSystemApp(ps)
9329                            && mExistingSystemPackages.contains(ps.name)) {
9330                        // For legacy system apps, install becomes runtime.
9331                        // We cannot check hasInstallPermission() for system apps since those
9332                        // permissions were granted implicitly and not persisted pre-M.
9333                        grant = GRANT_UPGRADE;
9334                    } else {
9335                        // For modern apps keep runtime permissions unchanged.
9336                        grant = GRANT_RUNTIME;
9337                    }
9338                } break;
9339
9340                case PermissionInfo.PROTECTION_SIGNATURE: {
9341                    // For all apps signature permissions are install time ones.
9342                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9343                    if (allowedSig) {
9344                        grant = GRANT_INSTALL;
9345                    }
9346                } break;
9347            }
9348
9349            if (DEBUG_INSTALL) {
9350                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9351            }
9352
9353            if (grant != GRANT_DENIED) {
9354                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9355                    // If this is an existing, non-system package, then
9356                    // we can't add any new permissions to it.
9357                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9358                        // Except...  if this is a permission that was added
9359                        // to the platform (note: need to only do this when
9360                        // updating the platform).
9361                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9362                            grant = GRANT_DENIED;
9363                        }
9364                    }
9365                }
9366
9367                switch (grant) {
9368                    case GRANT_INSTALL: {
9369                        // Revoke this as runtime permission to handle the case of
9370                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9371                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9372                            if (origPermissions.getRuntimePermissionState(
9373                                    bp.name, userId) != null) {
9374                                // Revoke the runtime permission and clear the flags.
9375                                origPermissions.revokeRuntimePermission(bp, userId);
9376                                origPermissions.updatePermissionFlags(bp, userId,
9377                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9378                                // If we revoked a permission permission, we have to write.
9379                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9380                                        changedRuntimePermissionUserIds, userId);
9381                            }
9382                        }
9383                        // Grant an install permission.
9384                        if (permissionsState.grantInstallPermission(bp) !=
9385                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9386                            changedInstallPermission = true;
9387                        }
9388                    } break;
9389
9390                    case GRANT_RUNTIME: {
9391                        // Grant previously granted runtime permissions.
9392                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9393                            PermissionState permissionState = origPermissions
9394                                    .getRuntimePermissionState(bp.name, userId);
9395                            int flags = permissionState != null
9396                                    ? permissionState.getFlags() : 0;
9397                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9398                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9399                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9400                                    // If we cannot put the permission as it was, we have to write.
9401                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9402                                            changedRuntimePermissionUserIds, userId);
9403                                }
9404                                // If the app supports runtime permissions no need for a review.
9405                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9406                                        && appSupportsRuntimePermissions
9407                                        && (flags & PackageManager
9408                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9409                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9410                                    // Since we changed the flags, we have to write.
9411                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9412                                            changedRuntimePermissionUserIds, userId);
9413                                }
9414                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9415                                    && !appSupportsRuntimePermissions) {
9416                                // For legacy apps that need a permission review, every new
9417                                // runtime permission is granted but it is pending a review.
9418                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9419                                    permissionsState.grantRuntimePermission(bp, userId);
9420                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9421                                    // We changed the permission and flags, hence have to write.
9422                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9423                                            changedRuntimePermissionUserIds, userId);
9424                                }
9425                            }
9426                            // Propagate the permission flags.
9427                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9428                        }
9429                    } break;
9430
9431                    case GRANT_UPGRADE: {
9432                        // Grant runtime permissions for a previously held install permission.
9433                        PermissionState permissionState = origPermissions
9434                                .getInstallPermissionState(bp.name);
9435                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9436
9437                        if (origPermissions.revokeInstallPermission(bp)
9438                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9439                            // We will be transferring the permission flags, so clear them.
9440                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9441                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9442                            changedInstallPermission = true;
9443                        }
9444
9445                        // If the permission is not to be promoted to runtime we ignore it and
9446                        // also its other flags as they are not applicable to install permissions.
9447                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9448                            for (int userId : currentUserIds) {
9449                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9450                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9451                                    // Transfer the permission flags.
9452                                    permissionsState.updatePermissionFlags(bp, userId,
9453                                            flags, flags);
9454                                    // If we granted the permission, we have to write.
9455                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9456                                            changedRuntimePermissionUserIds, userId);
9457                                }
9458                            }
9459                        }
9460                    } break;
9461
9462                    default: {
9463                        if (packageOfInterest == null
9464                                || packageOfInterest.equals(pkg.packageName)) {
9465                            Slog.w(TAG, "Not granting permission " + perm
9466                                    + " to package " + pkg.packageName
9467                                    + " because it was previously installed without");
9468                        }
9469                    } break;
9470                }
9471            } else {
9472                if (permissionsState.revokeInstallPermission(bp) !=
9473                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9474                    // Also drop the permission flags.
9475                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9476                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9477                    changedInstallPermission = true;
9478                    Slog.i(TAG, "Un-granting permission " + perm
9479                            + " from package " + pkg.packageName
9480                            + " (protectionLevel=" + bp.protectionLevel
9481                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9482                            + ")");
9483                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9484                    // Don't print warning for app op permissions, since it is fine for them
9485                    // not to be granted, there is a UI for the user to decide.
9486                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9487                        Slog.w(TAG, "Not granting permission " + perm
9488                                + " to package " + pkg.packageName
9489                                + " (protectionLevel=" + bp.protectionLevel
9490                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9491                                + ")");
9492                    }
9493                }
9494            }
9495        }
9496
9497        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9498                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9499            // This is the first that we have heard about this package, so the
9500            // permissions we have now selected are fixed until explicitly
9501            // changed.
9502            ps.installPermissionsFixed = true;
9503        }
9504
9505        // Persist the runtime permissions state for users with changes. If permissions
9506        // were revoked because no app in the shared user declares them we have to
9507        // write synchronously to avoid losing runtime permissions state.
9508        for (int userId : changedRuntimePermissionUserIds) {
9509            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9510        }
9511
9512        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9513    }
9514
9515    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9516        boolean allowed = false;
9517        final int NP = PackageParser.NEW_PERMISSIONS.length;
9518        for (int ip=0; ip<NP; ip++) {
9519            final PackageParser.NewPermissionInfo npi
9520                    = PackageParser.NEW_PERMISSIONS[ip];
9521            if (npi.name.equals(perm)
9522                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9523                allowed = true;
9524                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9525                        + pkg.packageName);
9526                break;
9527            }
9528        }
9529        return allowed;
9530    }
9531
9532    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9533            BasePermission bp, PermissionsState origPermissions) {
9534        boolean allowed;
9535        allowed = (compareSignatures(
9536                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9537                        == PackageManager.SIGNATURE_MATCH)
9538                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9539                        == PackageManager.SIGNATURE_MATCH);
9540        if (!allowed && (bp.protectionLevel
9541                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9542            if (isSystemApp(pkg)) {
9543                // For updated system applications, a system permission
9544                // is granted only if it had been defined by the original application.
9545                if (pkg.isUpdatedSystemApp()) {
9546                    final PackageSetting sysPs = mSettings
9547                            .getDisabledSystemPkgLPr(pkg.packageName);
9548                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9549                        // If the original was granted this permission, we take
9550                        // that grant decision as read and propagate it to the
9551                        // update.
9552                        if (sysPs.isPrivileged()) {
9553                            allowed = true;
9554                        }
9555                    } else {
9556                        // The system apk may have been updated with an older
9557                        // version of the one on the data partition, but which
9558                        // granted a new system permission that it didn't have
9559                        // before.  In this case we do want to allow the app to
9560                        // now get the new permission if the ancestral apk is
9561                        // privileged to get it.
9562                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9563                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9564                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9565                                    allowed = true;
9566                                    break;
9567                                }
9568                            }
9569                        }
9570                        // Also if a privileged parent package on the system image or any of
9571                        // its children requested a privileged permission, the updated child
9572                        // packages can also get the permission.
9573                        if (pkg.parentPackage != null) {
9574                            final PackageSetting disabledSysParentPs = mSettings
9575                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9576                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9577                                    && disabledSysParentPs.isPrivileged()) {
9578                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9579                                    allowed = true;
9580                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9581                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9582                                    for (int i = 0; i < count; i++) {
9583                                        PackageParser.Package disabledSysChildPkg =
9584                                                disabledSysParentPs.pkg.childPackages.get(i);
9585                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9586                                                perm)) {
9587                                            allowed = true;
9588                                            break;
9589                                        }
9590                                    }
9591                                }
9592                            }
9593                        }
9594                    }
9595                } else {
9596                    allowed = isPrivilegedApp(pkg);
9597                }
9598            }
9599        }
9600        if (!allowed) {
9601            if (!allowed && (bp.protectionLevel
9602                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9603                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9604                // If this was a previously normal/dangerous permission that got moved
9605                // to a system permission as part of the runtime permission redesign, then
9606                // we still want to blindly grant it to old apps.
9607                allowed = true;
9608            }
9609            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9610                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9611                // If this permission is to be granted to the system installer and
9612                // this app is an installer, then it gets the permission.
9613                allowed = true;
9614            }
9615            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9616                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9617                // If this permission is to be granted to the system verifier and
9618                // this app is a verifier, then it gets the permission.
9619                allowed = true;
9620            }
9621            if (!allowed && (bp.protectionLevel
9622                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9623                    && isSystemApp(pkg)) {
9624                // Any pre-installed system app is allowed to get this permission.
9625                allowed = true;
9626            }
9627            if (!allowed && (bp.protectionLevel
9628                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9629                // For development permissions, a development permission
9630                // is granted only if it was already granted.
9631                allowed = origPermissions.hasInstallPermission(perm);
9632            }
9633        }
9634        return allowed;
9635    }
9636
9637    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9638        final int permCount = pkg.requestedPermissions.size();
9639        for (int j = 0; j < permCount; j++) {
9640            String requestedPermission = pkg.requestedPermissions.get(j);
9641            if (permission.equals(requestedPermission)) {
9642                return true;
9643            }
9644        }
9645        return false;
9646    }
9647
9648    final class ActivityIntentResolver
9649            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9650        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9651                boolean defaultOnly, int userId) {
9652            if (!sUserManager.exists(userId)) return null;
9653            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9654            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9655        }
9656
9657        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9658                int userId) {
9659            if (!sUserManager.exists(userId)) return null;
9660            mFlags = flags;
9661            return super.queryIntent(intent, resolvedType,
9662                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9663        }
9664
9665        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9666                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9667            if (!sUserManager.exists(userId)) return null;
9668            if (packageActivities == null) {
9669                return null;
9670            }
9671            mFlags = flags;
9672            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9673            final int N = packageActivities.size();
9674            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9675                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9676
9677            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9678            for (int i = 0; i < N; ++i) {
9679                intentFilters = packageActivities.get(i).intents;
9680                if (intentFilters != null && intentFilters.size() > 0) {
9681                    PackageParser.ActivityIntentInfo[] array =
9682                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9683                    intentFilters.toArray(array);
9684                    listCut.add(array);
9685                }
9686            }
9687            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9688        }
9689
9690        public final void addActivity(PackageParser.Activity a, String type) {
9691            final boolean systemApp = a.info.applicationInfo.isSystemApp();
9692            mActivities.put(a.getComponentName(), a);
9693            if (DEBUG_SHOW_INFO)
9694                Log.v(
9695                TAG, "  " + type + " " +
9696                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
9697            if (DEBUG_SHOW_INFO)
9698                Log.v(TAG, "    Class=" + a.info.name);
9699            final int NI = a.intents.size();
9700            for (int j=0; j<NI; j++) {
9701                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9702                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
9703                    intent.setPriority(0);
9704                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
9705                            + a.className + " with priority > 0, forcing to 0");
9706                }
9707                if (DEBUG_SHOW_INFO) {
9708                    Log.v(TAG, "    IntentFilter:");
9709                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9710                }
9711                if (!intent.debugCheck()) {
9712                    Log.w(TAG, "==> For Activity " + a.info.name);
9713                }
9714                addFilter(intent);
9715            }
9716        }
9717
9718        public final void removeActivity(PackageParser.Activity a, String type) {
9719            mActivities.remove(a.getComponentName());
9720            if (DEBUG_SHOW_INFO) {
9721                Log.v(TAG, "  " + type + " "
9722                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
9723                                : a.info.name) + ":");
9724                Log.v(TAG, "    Class=" + a.info.name);
9725            }
9726            final int NI = a.intents.size();
9727            for (int j=0; j<NI; j++) {
9728                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
9729                if (DEBUG_SHOW_INFO) {
9730                    Log.v(TAG, "    IntentFilter:");
9731                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9732                }
9733                removeFilter(intent);
9734            }
9735        }
9736
9737        @Override
9738        protected boolean allowFilterResult(
9739                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
9740            ActivityInfo filterAi = filter.activity.info;
9741            for (int i=dest.size()-1; i>=0; i--) {
9742                ActivityInfo destAi = dest.get(i).activityInfo;
9743                if (destAi.name == filterAi.name
9744                        && destAi.packageName == filterAi.packageName) {
9745                    return false;
9746                }
9747            }
9748            return true;
9749        }
9750
9751        @Override
9752        protected ActivityIntentInfo[] newArray(int size) {
9753            return new ActivityIntentInfo[size];
9754        }
9755
9756        @Override
9757        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
9758            if (!sUserManager.exists(userId)) return true;
9759            PackageParser.Package p = filter.activity.owner;
9760            if (p != null) {
9761                PackageSetting ps = (PackageSetting)p.mExtras;
9762                if (ps != null) {
9763                    // System apps are never considered stopped for purposes of
9764                    // filtering, because there may be no way for the user to
9765                    // actually re-launch them.
9766                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
9767                            && ps.getStopped(userId);
9768                }
9769            }
9770            return false;
9771        }
9772
9773        @Override
9774        protected boolean isPackageForFilter(String packageName,
9775                PackageParser.ActivityIntentInfo info) {
9776            return packageName.equals(info.activity.owner.packageName);
9777        }
9778
9779        @Override
9780        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
9781                int match, int userId) {
9782            if (!sUserManager.exists(userId)) return null;
9783            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
9784                return null;
9785            }
9786            final PackageParser.Activity activity = info.activity;
9787            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
9788            if (ps == null) {
9789                return null;
9790            }
9791            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
9792                    ps.readUserState(userId), userId);
9793            if (ai == null) {
9794                return null;
9795            }
9796            final ResolveInfo res = new ResolveInfo();
9797            res.activityInfo = ai;
9798            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
9799                res.filter = info;
9800            }
9801            if (info != null) {
9802                res.handleAllWebDataURI = info.handleAllWebDataURI();
9803            }
9804            res.priority = info.getPriority();
9805            res.preferredOrder = activity.owner.mPreferredOrder;
9806            //System.out.println("Result: " + res.activityInfo.className +
9807            //                   " = " + res.priority);
9808            res.match = match;
9809            res.isDefault = info.hasDefault;
9810            res.labelRes = info.labelRes;
9811            res.nonLocalizedLabel = info.nonLocalizedLabel;
9812            if (userNeedsBadging(userId)) {
9813                res.noResourceId = true;
9814            } else {
9815                res.icon = info.icon;
9816            }
9817            res.iconResourceId = info.icon;
9818            res.system = res.activityInfo.applicationInfo.isSystemApp();
9819            return res;
9820        }
9821
9822        @Override
9823        protected void sortResults(List<ResolveInfo> results) {
9824            Collections.sort(results, mResolvePrioritySorter);
9825        }
9826
9827        @Override
9828        protected void dumpFilter(PrintWriter out, String prefix,
9829                PackageParser.ActivityIntentInfo filter) {
9830            out.print(prefix); out.print(
9831                    Integer.toHexString(System.identityHashCode(filter.activity)));
9832                    out.print(' ');
9833                    filter.activity.printComponentShortName(out);
9834                    out.print(" filter ");
9835                    out.println(Integer.toHexString(System.identityHashCode(filter)));
9836        }
9837
9838        @Override
9839        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
9840            return filter.activity;
9841        }
9842
9843        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
9844            PackageParser.Activity activity = (PackageParser.Activity)label;
9845            out.print(prefix); out.print(
9846                    Integer.toHexString(System.identityHashCode(activity)));
9847                    out.print(' ');
9848                    activity.printComponentShortName(out);
9849            if (count > 1) {
9850                out.print(" ("); out.print(count); out.print(" filters)");
9851            }
9852            out.println();
9853        }
9854
9855//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
9856//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
9857//            final List<ResolveInfo> retList = Lists.newArrayList();
9858//            while (i.hasNext()) {
9859//                final ResolveInfo resolveInfo = i.next();
9860//                if (isEnabledLP(resolveInfo.activityInfo)) {
9861//                    retList.add(resolveInfo);
9862//                }
9863//            }
9864//            return retList;
9865//        }
9866
9867        // Keys are String (activity class name), values are Activity.
9868        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
9869                = new ArrayMap<ComponentName, PackageParser.Activity>();
9870        private int mFlags;
9871    }
9872
9873    private final class ServiceIntentResolver
9874            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
9875        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9876                boolean defaultOnly, int userId) {
9877            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9878            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9879        }
9880
9881        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9882                int userId) {
9883            if (!sUserManager.exists(userId)) return null;
9884            mFlags = flags;
9885            return super.queryIntent(intent, resolvedType,
9886                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9887        }
9888
9889        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9890                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
9891            if (!sUserManager.exists(userId)) return null;
9892            if (packageServices == null) {
9893                return null;
9894            }
9895            mFlags = flags;
9896            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9897            final int N = packageServices.size();
9898            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
9899                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
9900
9901            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
9902            for (int i = 0; i < N; ++i) {
9903                intentFilters = packageServices.get(i).intents;
9904                if (intentFilters != null && intentFilters.size() > 0) {
9905                    PackageParser.ServiceIntentInfo[] array =
9906                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
9907                    intentFilters.toArray(array);
9908                    listCut.add(array);
9909                }
9910            }
9911            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9912        }
9913
9914        public final void addService(PackageParser.Service s) {
9915            mServices.put(s.getComponentName(), s);
9916            if (DEBUG_SHOW_INFO) {
9917                Log.v(TAG, "  "
9918                        + (s.info.nonLocalizedLabel != null
9919                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9920                Log.v(TAG, "    Class=" + s.info.name);
9921            }
9922            final int NI = s.intents.size();
9923            int j;
9924            for (j=0; j<NI; j++) {
9925                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9926                if (DEBUG_SHOW_INFO) {
9927                    Log.v(TAG, "    IntentFilter:");
9928                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9929                }
9930                if (!intent.debugCheck()) {
9931                    Log.w(TAG, "==> For Service " + s.info.name);
9932                }
9933                addFilter(intent);
9934            }
9935        }
9936
9937        public final void removeService(PackageParser.Service s) {
9938            mServices.remove(s.getComponentName());
9939            if (DEBUG_SHOW_INFO) {
9940                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
9941                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
9942                Log.v(TAG, "    Class=" + s.info.name);
9943            }
9944            final int NI = s.intents.size();
9945            int j;
9946            for (j=0; j<NI; j++) {
9947                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
9948                if (DEBUG_SHOW_INFO) {
9949                    Log.v(TAG, "    IntentFilter:");
9950                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
9951                }
9952                removeFilter(intent);
9953            }
9954        }
9955
9956        @Override
9957        protected boolean allowFilterResult(
9958                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
9959            ServiceInfo filterSi = filter.service.info;
9960            for (int i=dest.size()-1; i>=0; i--) {
9961                ServiceInfo destAi = dest.get(i).serviceInfo;
9962                if (destAi.name == filterSi.name
9963                        && destAi.packageName == filterSi.packageName) {
9964                    return false;
9965                }
9966            }
9967            return true;
9968        }
9969
9970        @Override
9971        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
9972            return new PackageParser.ServiceIntentInfo[size];
9973        }
9974
9975        @Override
9976        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
9977            if (!sUserManager.exists(userId)) return true;
9978            PackageParser.Package p = filter.service.owner;
9979            if (p != null) {
9980                PackageSetting ps = (PackageSetting)p.mExtras;
9981                if (ps != null) {
9982                    // System apps are never considered stopped for purposes of
9983                    // filtering, because there may be no way for the user to
9984                    // actually re-launch them.
9985                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
9986                            && ps.getStopped(userId);
9987                }
9988            }
9989            return false;
9990        }
9991
9992        @Override
9993        protected boolean isPackageForFilter(String packageName,
9994                PackageParser.ServiceIntentInfo info) {
9995            return packageName.equals(info.service.owner.packageName);
9996        }
9997
9998        @Override
9999        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10000                int match, int userId) {
10001            if (!sUserManager.exists(userId)) return null;
10002            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10003            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10004                return null;
10005            }
10006            final PackageParser.Service service = info.service;
10007            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10008            if (ps == null) {
10009                return null;
10010            }
10011            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10012                    ps.readUserState(userId), userId);
10013            if (si == null) {
10014                return null;
10015            }
10016            final ResolveInfo res = new ResolveInfo();
10017            res.serviceInfo = si;
10018            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10019                res.filter = filter;
10020            }
10021            res.priority = info.getPriority();
10022            res.preferredOrder = service.owner.mPreferredOrder;
10023            res.match = match;
10024            res.isDefault = info.hasDefault;
10025            res.labelRes = info.labelRes;
10026            res.nonLocalizedLabel = info.nonLocalizedLabel;
10027            res.icon = info.icon;
10028            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10029            return res;
10030        }
10031
10032        @Override
10033        protected void sortResults(List<ResolveInfo> results) {
10034            Collections.sort(results, mResolvePrioritySorter);
10035        }
10036
10037        @Override
10038        protected void dumpFilter(PrintWriter out, String prefix,
10039                PackageParser.ServiceIntentInfo filter) {
10040            out.print(prefix); out.print(
10041                    Integer.toHexString(System.identityHashCode(filter.service)));
10042                    out.print(' ');
10043                    filter.service.printComponentShortName(out);
10044                    out.print(" filter ");
10045                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10046        }
10047
10048        @Override
10049        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10050            return filter.service;
10051        }
10052
10053        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10054            PackageParser.Service service = (PackageParser.Service)label;
10055            out.print(prefix); out.print(
10056                    Integer.toHexString(System.identityHashCode(service)));
10057                    out.print(' ');
10058                    service.printComponentShortName(out);
10059            if (count > 1) {
10060                out.print(" ("); out.print(count); out.print(" filters)");
10061            }
10062            out.println();
10063        }
10064
10065//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10066//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10067//            final List<ResolveInfo> retList = Lists.newArrayList();
10068//            while (i.hasNext()) {
10069//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10070//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10071//                    retList.add(resolveInfo);
10072//                }
10073//            }
10074//            return retList;
10075//        }
10076
10077        // Keys are String (activity class name), values are Activity.
10078        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10079                = new ArrayMap<ComponentName, PackageParser.Service>();
10080        private int mFlags;
10081    };
10082
10083    private final class ProviderIntentResolver
10084            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10085        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10086                boolean defaultOnly, int userId) {
10087            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10088            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10089        }
10090
10091        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10092                int userId) {
10093            if (!sUserManager.exists(userId))
10094                return null;
10095            mFlags = flags;
10096            return super.queryIntent(intent, resolvedType,
10097                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10098        }
10099
10100        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10101                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10102            if (!sUserManager.exists(userId))
10103                return null;
10104            if (packageProviders == null) {
10105                return null;
10106            }
10107            mFlags = flags;
10108            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10109            final int N = packageProviders.size();
10110            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10111                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10112
10113            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10114            for (int i = 0; i < N; ++i) {
10115                intentFilters = packageProviders.get(i).intents;
10116                if (intentFilters != null && intentFilters.size() > 0) {
10117                    PackageParser.ProviderIntentInfo[] array =
10118                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10119                    intentFilters.toArray(array);
10120                    listCut.add(array);
10121                }
10122            }
10123            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10124        }
10125
10126        public final void addProvider(PackageParser.Provider p) {
10127            if (mProviders.containsKey(p.getComponentName())) {
10128                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10129                return;
10130            }
10131
10132            mProviders.put(p.getComponentName(), p);
10133            if (DEBUG_SHOW_INFO) {
10134                Log.v(TAG, "  "
10135                        + (p.info.nonLocalizedLabel != null
10136                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10137                Log.v(TAG, "    Class=" + p.info.name);
10138            }
10139            final int NI = p.intents.size();
10140            int j;
10141            for (j = 0; j < NI; j++) {
10142                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10143                if (DEBUG_SHOW_INFO) {
10144                    Log.v(TAG, "    IntentFilter:");
10145                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10146                }
10147                if (!intent.debugCheck()) {
10148                    Log.w(TAG, "==> For Provider " + p.info.name);
10149                }
10150                addFilter(intent);
10151            }
10152        }
10153
10154        public final void removeProvider(PackageParser.Provider p) {
10155            mProviders.remove(p.getComponentName());
10156            if (DEBUG_SHOW_INFO) {
10157                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10158                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10159                Log.v(TAG, "    Class=" + p.info.name);
10160            }
10161            final int NI = p.intents.size();
10162            int j;
10163            for (j = 0; j < NI; j++) {
10164                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10165                if (DEBUG_SHOW_INFO) {
10166                    Log.v(TAG, "    IntentFilter:");
10167                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10168                }
10169                removeFilter(intent);
10170            }
10171        }
10172
10173        @Override
10174        protected boolean allowFilterResult(
10175                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10176            ProviderInfo filterPi = filter.provider.info;
10177            for (int i = dest.size() - 1; i >= 0; i--) {
10178                ProviderInfo destPi = dest.get(i).providerInfo;
10179                if (destPi.name == filterPi.name
10180                        && destPi.packageName == filterPi.packageName) {
10181                    return false;
10182                }
10183            }
10184            return true;
10185        }
10186
10187        @Override
10188        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10189            return new PackageParser.ProviderIntentInfo[size];
10190        }
10191
10192        @Override
10193        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10194            if (!sUserManager.exists(userId))
10195                return true;
10196            PackageParser.Package p = filter.provider.owner;
10197            if (p != null) {
10198                PackageSetting ps = (PackageSetting) p.mExtras;
10199                if (ps != null) {
10200                    // System apps are never considered stopped for purposes of
10201                    // filtering, because there may be no way for the user to
10202                    // actually re-launch them.
10203                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10204                            && ps.getStopped(userId);
10205                }
10206            }
10207            return false;
10208        }
10209
10210        @Override
10211        protected boolean isPackageForFilter(String packageName,
10212                PackageParser.ProviderIntentInfo info) {
10213            return packageName.equals(info.provider.owner.packageName);
10214        }
10215
10216        @Override
10217        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10218                int match, int userId) {
10219            if (!sUserManager.exists(userId))
10220                return null;
10221            final PackageParser.ProviderIntentInfo info = filter;
10222            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10223                return null;
10224            }
10225            final PackageParser.Provider provider = info.provider;
10226            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10227            if (ps == null) {
10228                return null;
10229            }
10230            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10231                    ps.readUserState(userId), userId);
10232            if (pi == null) {
10233                return null;
10234            }
10235            final ResolveInfo res = new ResolveInfo();
10236            res.providerInfo = pi;
10237            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10238                res.filter = filter;
10239            }
10240            res.priority = info.getPriority();
10241            res.preferredOrder = provider.owner.mPreferredOrder;
10242            res.match = match;
10243            res.isDefault = info.hasDefault;
10244            res.labelRes = info.labelRes;
10245            res.nonLocalizedLabel = info.nonLocalizedLabel;
10246            res.icon = info.icon;
10247            res.system = res.providerInfo.applicationInfo.isSystemApp();
10248            return res;
10249        }
10250
10251        @Override
10252        protected void sortResults(List<ResolveInfo> results) {
10253            Collections.sort(results, mResolvePrioritySorter);
10254        }
10255
10256        @Override
10257        protected void dumpFilter(PrintWriter out, String prefix,
10258                PackageParser.ProviderIntentInfo filter) {
10259            out.print(prefix);
10260            out.print(
10261                    Integer.toHexString(System.identityHashCode(filter.provider)));
10262            out.print(' ');
10263            filter.provider.printComponentShortName(out);
10264            out.print(" filter ");
10265            out.println(Integer.toHexString(System.identityHashCode(filter)));
10266        }
10267
10268        @Override
10269        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10270            return filter.provider;
10271        }
10272
10273        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10274            PackageParser.Provider provider = (PackageParser.Provider)label;
10275            out.print(prefix); out.print(
10276                    Integer.toHexString(System.identityHashCode(provider)));
10277                    out.print(' ');
10278                    provider.printComponentShortName(out);
10279            if (count > 1) {
10280                out.print(" ("); out.print(count); out.print(" filters)");
10281            }
10282            out.println();
10283        }
10284
10285        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10286                = new ArrayMap<ComponentName, PackageParser.Provider>();
10287        private int mFlags;
10288    }
10289
10290    private static final class EphemeralIntentResolver
10291            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10292        @Override
10293        protected EphemeralResolveIntentInfo[] newArray(int size) {
10294            return new EphemeralResolveIntentInfo[size];
10295        }
10296
10297        @Override
10298        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10299            return true;
10300        }
10301
10302        @Override
10303        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10304                int userId) {
10305            if (!sUserManager.exists(userId)) {
10306                return null;
10307            }
10308            return info.getEphemeralResolveInfo();
10309        }
10310    }
10311
10312    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10313            new Comparator<ResolveInfo>() {
10314        public int compare(ResolveInfo r1, ResolveInfo r2) {
10315            int v1 = r1.priority;
10316            int v2 = r2.priority;
10317            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10318            if (v1 != v2) {
10319                return (v1 > v2) ? -1 : 1;
10320            }
10321            v1 = r1.preferredOrder;
10322            v2 = r2.preferredOrder;
10323            if (v1 != v2) {
10324                return (v1 > v2) ? -1 : 1;
10325            }
10326            if (r1.isDefault != r2.isDefault) {
10327                return r1.isDefault ? -1 : 1;
10328            }
10329            v1 = r1.match;
10330            v2 = r2.match;
10331            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10332            if (v1 != v2) {
10333                return (v1 > v2) ? -1 : 1;
10334            }
10335            if (r1.system != r2.system) {
10336                return r1.system ? -1 : 1;
10337            }
10338            if (r1.activityInfo != null) {
10339                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10340            }
10341            if (r1.serviceInfo != null) {
10342                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10343            }
10344            if (r1.providerInfo != null) {
10345                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10346            }
10347            return 0;
10348        }
10349    };
10350
10351    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10352            new Comparator<ProviderInfo>() {
10353        public int compare(ProviderInfo p1, ProviderInfo p2) {
10354            final int v1 = p1.initOrder;
10355            final int v2 = p2.initOrder;
10356            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10357        }
10358    };
10359
10360    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10361            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10362            final int[] userIds) {
10363        mHandler.post(new Runnable() {
10364            @Override
10365            public void run() {
10366                try {
10367                    final IActivityManager am = ActivityManagerNative.getDefault();
10368                    if (am == null) return;
10369                    final int[] resolvedUserIds;
10370                    if (userIds == null) {
10371                        resolvedUserIds = am.getRunningUserIds();
10372                    } else {
10373                        resolvedUserIds = userIds;
10374                    }
10375                    for (int id : resolvedUserIds) {
10376                        final Intent intent = new Intent(action,
10377                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10378                        if (extras != null) {
10379                            intent.putExtras(extras);
10380                        }
10381                        if (targetPkg != null) {
10382                            intent.setPackage(targetPkg);
10383                        }
10384                        // Modify the UID when posting to other users
10385                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10386                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10387                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10388                            intent.putExtra(Intent.EXTRA_UID, uid);
10389                        }
10390                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10391                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10392                        if (DEBUG_BROADCASTS) {
10393                            RuntimeException here = new RuntimeException("here");
10394                            here.fillInStackTrace();
10395                            Slog.d(TAG, "Sending to user " + id + ": "
10396                                    + intent.toShortString(false, true, false, false)
10397                                    + " " + intent.getExtras(), here);
10398                        }
10399                        am.broadcastIntent(null, intent, null, finishedReceiver,
10400                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10401                                null, finishedReceiver != null, false, id);
10402                    }
10403                } catch (RemoteException ex) {
10404                }
10405            }
10406        });
10407    }
10408
10409    /**
10410     * Check if the external storage media is available. This is true if there
10411     * is a mounted external storage medium or if the external storage is
10412     * emulated.
10413     */
10414    private boolean isExternalMediaAvailable() {
10415        return mMediaMounted || Environment.isExternalStorageEmulated();
10416    }
10417
10418    @Override
10419    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10420        // writer
10421        synchronized (mPackages) {
10422            if (!isExternalMediaAvailable()) {
10423                // If the external storage is no longer mounted at this point,
10424                // the caller may not have been able to delete all of this
10425                // packages files and can not delete any more.  Bail.
10426                return null;
10427            }
10428            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10429            if (lastPackage != null) {
10430                pkgs.remove(lastPackage);
10431            }
10432            if (pkgs.size() > 0) {
10433                return pkgs.get(0);
10434            }
10435        }
10436        return null;
10437    }
10438
10439    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10440        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10441                userId, andCode ? 1 : 0, packageName);
10442        if (mSystemReady) {
10443            msg.sendToTarget();
10444        } else {
10445            if (mPostSystemReadyMessages == null) {
10446                mPostSystemReadyMessages = new ArrayList<>();
10447            }
10448            mPostSystemReadyMessages.add(msg);
10449        }
10450    }
10451
10452    void startCleaningPackages() {
10453        // reader
10454        if (!isExternalMediaAvailable()) {
10455            return;
10456        }
10457        synchronized (mPackages) {
10458            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10459                return;
10460            }
10461        }
10462        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10463        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10464        IActivityManager am = ActivityManagerNative.getDefault();
10465        if (am != null) {
10466            try {
10467                am.startService(null, intent, null, mContext.getOpPackageName(),
10468                        UserHandle.USER_SYSTEM);
10469            } catch (RemoteException e) {
10470            }
10471        }
10472    }
10473
10474    @Override
10475    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10476            int installFlags, String installerPackageName, int userId) {
10477        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10478
10479        final int callingUid = Binder.getCallingUid();
10480        enforceCrossUserPermission(callingUid, userId,
10481                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
10482
10483        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10484            try {
10485                if (observer != null) {
10486                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10487                }
10488            } catch (RemoteException re) {
10489            }
10490            return;
10491        }
10492
10493        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10494            installFlags |= PackageManager.INSTALL_FROM_ADB;
10495
10496        } else {
10497            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10498            // about installerPackageName.
10499
10500            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10501            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10502        }
10503
10504        UserHandle user;
10505        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10506            user = UserHandle.ALL;
10507        } else {
10508            user = new UserHandle(userId);
10509        }
10510
10511        // Only system components can circumvent runtime permissions when installing.
10512        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10513                && mContext.checkCallingOrSelfPermission(Manifest.permission
10514                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10515            throw new SecurityException("You need the "
10516                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10517                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10518        }
10519
10520        final File originFile = new File(originPath);
10521        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10522
10523        final Message msg = mHandler.obtainMessage(INIT_COPY);
10524        final VerificationInfo verificationInfo = new VerificationInfo(
10525                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
10526        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
10527                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
10528                null /*packageAbiOverride*/, null /*grantedPermissions*/);
10529        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10530        msg.obj = params;
10531
10532        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10533                System.identityHashCode(msg.obj));
10534        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10535                System.identityHashCode(msg.obj));
10536
10537        mHandler.sendMessage(msg);
10538    }
10539
10540    void installStage(String packageName, File stagedDir, String stagedCid,
10541            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10542            String installerPackageName, int installerUid, UserHandle user) {
10543        if (DEBUG_EPHEMERAL) {
10544            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10545                Slog.d(TAG, "Ephemeral install of " + packageName);
10546            }
10547        }
10548        final VerificationInfo verificationInfo = new VerificationInfo(
10549                sessionParams.originatingUri, sessionParams.referrerUri,
10550                sessionParams.originatingUid, installerUid);
10551
10552        final OriginInfo origin;
10553        if (stagedDir != null) {
10554            origin = OriginInfo.fromStagedFile(stagedDir);
10555        } else {
10556            origin = OriginInfo.fromStagedContainer(stagedCid);
10557        }
10558
10559        final Message msg = mHandler.obtainMessage(INIT_COPY);
10560        final InstallParams params = new InstallParams(origin, null, observer,
10561                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10562                verificationInfo, user, sessionParams.abiOverride,
10563                sessionParams.grantedRuntimePermissions);
10564        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10565        msg.obj = params;
10566
10567        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10568                System.identityHashCode(msg.obj));
10569        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10570                System.identityHashCode(msg.obj));
10571
10572        mHandler.sendMessage(msg);
10573    }
10574
10575    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
10576            int userId) {
10577        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
10578        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
10579    }
10580
10581    private void sendPackageAddedForUser(String packageName, boolean isSystem,
10582            int appId, int userId) {
10583        Bundle extras = new Bundle(1);
10584        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
10585
10586        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
10587                packageName, extras, 0, null, null, new int[] {userId});
10588        try {
10589            IActivityManager am = ActivityManagerNative.getDefault();
10590            if (isSystem && am.isUserRunning(userId, 0)) {
10591                // The just-installed/enabled app is bundled on the system, so presumed
10592                // to be able to run automatically without needing an explicit launch.
10593                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
10594                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
10595                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
10596                        .setPackage(packageName);
10597                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
10598                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
10599            }
10600        } catch (RemoteException e) {
10601            // shouldn't happen
10602            Slog.w(TAG, "Unable to bootstrap installed package", e);
10603        }
10604    }
10605
10606    @Override
10607    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
10608            int userId) {
10609        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10610        PackageSetting pkgSetting;
10611        final int uid = Binder.getCallingUid();
10612        enforceCrossUserPermission(uid, userId,
10613                true /* requireFullPermission */, true /* checkShell */,
10614                "setApplicationHiddenSetting for user " + userId);
10615
10616        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
10617            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
10618            return false;
10619        }
10620
10621        long callingId = Binder.clearCallingIdentity();
10622        try {
10623            boolean sendAdded = false;
10624            boolean sendRemoved = false;
10625            // writer
10626            synchronized (mPackages) {
10627                pkgSetting = mSettings.mPackages.get(packageName);
10628                if (pkgSetting == null) {
10629                    return false;
10630                }
10631                if (pkgSetting.getHidden(userId) != hidden) {
10632                    pkgSetting.setHidden(hidden, userId);
10633                    mSettings.writePackageRestrictionsLPr(userId);
10634                    if (hidden) {
10635                        sendRemoved = true;
10636                    } else {
10637                        sendAdded = true;
10638                    }
10639                }
10640            }
10641            if (sendAdded) {
10642                sendPackageAddedForUser(packageName, pkgSetting, userId);
10643                return true;
10644            }
10645            if (sendRemoved) {
10646                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
10647                        "hiding pkg");
10648                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
10649                return true;
10650            }
10651        } finally {
10652            Binder.restoreCallingIdentity(callingId);
10653        }
10654        return false;
10655    }
10656
10657    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
10658            int userId) {
10659        final PackageRemovedInfo info = new PackageRemovedInfo();
10660        info.removedPackage = packageName;
10661        info.removedUsers = new int[] {userId};
10662        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
10663        info.sendPackageRemovedBroadcasts(true /*killApp*/);
10664    }
10665
10666    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
10667        if (pkgList.length > 0) {
10668            Bundle extras = new Bundle(1);
10669            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
10670
10671            sendPackageBroadcast(
10672                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
10673                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
10674                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
10675                    new int[] {userId});
10676        }
10677    }
10678
10679    /**
10680     * Returns true if application is not found or there was an error. Otherwise it returns
10681     * the hidden state of the package for the given user.
10682     */
10683    @Override
10684    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
10685        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10686        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10687                true /* requireFullPermission */, false /* checkShell */,
10688                "getApplicationHidden for user " + userId);
10689        PackageSetting pkgSetting;
10690        long callingId = Binder.clearCallingIdentity();
10691        try {
10692            // writer
10693            synchronized (mPackages) {
10694                pkgSetting = mSettings.mPackages.get(packageName);
10695                if (pkgSetting == null) {
10696                    return true;
10697                }
10698                return pkgSetting.getHidden(userId);
10699            }
10700        } finally {
10701            Binder.restoreCallingIdentity(callingId);
10702        }
10703    }
10704
10705    /**
10706     * @hide
10707     */
10708    @Override
10709    public int installExistingPackageAsUser(String packageName, int userId) {
10710        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
10711                null);
10712        PackageSetting pkgSetting;
10713        final int uid = Binder.getCallingUid();
10714        enforceCrossUserPermission(uid, userId,
10715                true /* requireFullPermission */, true /* checkShell */,
10716                "installExistingPackage for user " + userId);
10717        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10718            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
10719        }
10720
10721        long callingId = Binder.clearCallingIdentity();
10722        try {
10723            boolean installed = false;
10724
10725            // writer
10726            synchronized (mPackages) {
10727                pkgSetting = mSettings.mPackages.get(packageName);
10728                if (pkgSetting == null) {
10729                    return PackageManager.INSTALL_FAILED_INVALID_URI;
10730                }
10731                if (!pkgSetting.getInstalled(userId)) {
10732                    pkgSetting.setInstalled(true, userId);
10733                    pkgSetting.setHidden(false, userId);
10734                    mSettings.writePackageRestrictionsLPr(userId);
10735                    installed = true;
10736                }
10737            }
10738
10739            if (installed) {
10740                if (pkgSetting.pkg != null) {
10741                    prepareAppDataAfterInstall(pkgSetting.pkg);
10742                }
10743                sendPackageAddedForUser(packageName, pkgSetting, userId);
10744            }
10745        } finally {
10746            Binder.restoreCallingIdentity(callingId);
10747        }
10748
10749        return PackageManager.INSTALL_SUCCEEDED;
10750    }
10751
10752    boolean isUserRestricted(int userId, String restrictionKey) {
10753        Bundle restrictions = sUserManager.getUserRestrictions(userId);
10754        if (restrictions.getBoolean(restrictionKey, false)) {
10755            Log.w(TAG, "User is restricted: " + restrictionKey);
10756            return true;
10757        }
10758        return false;
10759    }
10760
10761    @Override
10762    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
10763            int userId) {
10764        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
10765        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10766                true /* requireFullPermission */, true /* checkShell */,
10767                "setPackagesSuspended for user " + userId);
10768
10769        if (ArrayUtils.isEmpty(packageNames)) {
10770            return packageNames;
10771        }
10772
10773        // List of package names for whom the suspended state has changed.
10774        List<String> changedPackages = new ArrayList<>(packageNames.length);
10775        // List of package names for whom the suspended state is not set as requested in this
10776        // method.
10777        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
10778        for (int i = 0; i < packageNames.length; i++) {
10779            String packageName = packageNames[i];
10780            long callingId = Binder.clearCallingIdentity();
10781            try {
10782                boolean changed = false;
10783                final int appId;
10784                synchronized (mPackages) {
10785                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10786                    if (pkgSetting == null) {
10787                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
10788                                + "\". Skipping suspending/un-suspending.");
10789                        unactionedPackages.add(packageName);
10790                        continue;
10791                    }
10792                    appId = pkgSetting.appId;
10793                    if (pkgSetting.getSuspended(userId) != suspended) {
10794                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
10795                            unactionedPackages.add(packageName);
10796                            continue;
10797                        }
10798                        pkgSetting.setSuspended(suspended, userId);
10799                        mSettings.writePackageRestrictionsLPr(userId);
10800                        changed = true;
10801                        changedPackages.add(packageName);
10802                    }
10803                }
10804
10805                if (changed && suspended) {
10806                    killApplication(packageName, UserHandle.getUid(userId, appId),
10807                            "suspending package");
10808                }
10809            } finally {
10810                Binder.restoreCallingIdentity(callingId);
10811            }
10812        }
10813
10814        if (!changedPackages.isEmpty()) {
10815            sendPackagesSuspendedForUser(changedPackages.toArray(
10816                    new String[changedPackages.size()]), userId, suspended);
10817        }
10818
10819        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
10820    }
10821
10822    @Override
10823    public boolean isPackageSuspendedForUser(String packageName, int userId) {
10824        enforceCrossUserPermission(Binder.getCallingUid(), userId,
10825                true /* requireFullPermission */, false /* checkShell */,
10826                "isPackageSuspendedForUser for user " + userId);
10827        synchronized (mPackages) {
10828            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
10829            return pkgSetting != null && pkgSetting.getSuspended(userId);
10830        }
10831    }
10832
10833    /**
10834     * TODO: cache and disallow blocking the active dialer.
10835     *
10836     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
10837     */
10838    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
10839        if (isPackageDeviceAdmin(packageName, userId)) {
10840            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10841                    + "\": has an active device admin");
10842            return false;
10843        }
10844
10845        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
10846        if (packageName.equals(activeLauncherPackageName)) {
10847            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10848                    + "\": contains the active launcher");
10849            return false;
10850        }
10851
10852        if (packageName.equals(mRequiredInstallerPackage)) {
10853            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10854                    + "\": required for package installation");
10855            return false;
10856        }
10857
10858        if (packageName.equals(mRequiredVerifierPackage)) {
10859            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10860                    + "\": required for package verification");
10861            return false;
10862        }
10863
10864        final PackageParser.Package pkg = mPackages.get(packageName);
10865        if (pkg != null && isPrivilegedApp(pkg)) {
10866            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
10867                    + "\": is a privileged app");
10868            return false;
10869        }
10870
10871        return true;
10872    }
10873
10874    private String getActiveLauncherPackageName(int userId) {
10875        Intent intent = new Intent(Intent.ACTION_MAIN);
10876        intent.addCategory(Intent.CATEGORY_HOME);
10877        ResolveInfo resolveInfo = resolveIntent(
10878                intent,
10879                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
10880                PackageManager.MATCH_DEFAULT_ONLY,
10881                userId);
10882
10883        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
10884    }
10885
10886    @Override
10887    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
10888        mContext.enforceCallingOrSelfPermission(
10889                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10890                "Only package verification agents can verify applications");
10891
10892        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10893        final PackageVerificationResponse response = new PackageVerificationResponse(
10894                verificationCode, Binder.getCallingUid());
10895        msg.arg1 = id;
10896        msg.obj = response;
10897        mHandler.sendMessage(msg);
10898    }
10899
10900    @Override
10901    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
10902            long millisecondsToDelay) {
10903        mContext.enforceCallingOrSelfPermission(
10904                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
10905                "Only package verification agents can extend verification timeouts");
10906
10907        final PackageVerificationState state = mPendingVerification.get(id);
10908        final PackageVerificationResponse response = new PackageVerificationResponse(
10909                verificationCodeAtTimeout, Binder.getCallingUid());
10910
10911        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
10912            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
10913        }
10914        if (millisecondsToDelay < 0) {
10915            millisecondsToDelay = 0;
10916        }
10917        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
10918                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
10919            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
10920        }
10921
10922        if ((state != null) && !state.timeoutExtended()) {
10923            state.extendTimeout();
10924
10925            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
10926            msg.arg1 = id;
10927            msg.obj = response;
10928            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
10929        }
10930    }
10931
10932    private void broadcastPackageVerified(int verificationId, Uri packageUri,
10933            int verificationCode, UserHandle user) {
10934        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
10935        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
10936        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
10937        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
10938        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
10939
10940        mContext.sendBroadcastAsUser(intent, user,
10941                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
10942    }
10943
10944    private ComponentName matchComponentForVerifier(String packageName,
10945            List<ResolveInfo> receivers) {
10946        ActivityInfo targetReceiver = null;
10947
10948        final int NR = receivers.size();
10949        for (int i = 0; i < NR; i++) {
10950            final ResolveInfo info = receivers.get(i);
10951            if (info.activityInfo == null) {
10952                continue;
10953            }
10954
10955            if (packageName.equals(info.activityInfo.packageName)) {
10956                targetReceiver = info.activityInfo;
10957                break;
10958            }
10959        }
10960
10961        if (targetReceiver == null) {
10962            return null;
10963        }
10964
10965        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
10966    }
10967
10968    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
10969            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
10970        if (pkgInfo.verifiers.length == 0) {
10971            return null;
10972        }
10973
10974        final int N = pkgInfo.verifiers.length;
10975        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
10976        for (int i = 0; i < N; i++) {
10977            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
10978
10979            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
10980                    receivers);
10981            if (comp == null) {
10982                continue;
10983            }
10984
10985            final int verifierUid = getUidForVerifier(verifierInfo);
10986            if (verifierUid == -1) {
10987                continue;
10988            }
10989
10990            if (DEBUG_VERIFY) {
10991                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
10992                        + " with the correct signature");
10993            }
10994            sufficientVerifiers.add(comp);
10995            verificationState.addSufficientVerifier(verifierUid);
10996        }
10997
10998        return sufficientVerifiers;
10999    }
11000
11001    private int getUidForVerifier(VerifierInfo verifierInfo) {
11002        synchronized (mPackages) {
11003            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11004            if (pkg == null) {
11005                return -1;
11006            } else if (pkg.mSignatures.length != 1) {
11007                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11008                        + " has more than one signature; ignoring");
11009                return -1;
11010            }
11011
11012            /*
11013             * If the public key of the package's signature does not match
11014             * our expected public key, then this is a different package and
11015             * we should skip.
11016             */
11017
11018            final byte[] expectedPublicKey;
11019            try {
11020                final Signature verifierSig = pkg.mSignatures[0];
11021                final PublicKey publicKey = verifierSig.getPublicKey();
11022                expectedPublicKey = publicKey.getEncoded();
11023            } catch (CertificateException e) {
11024                return -1;
11025            }
11026
11027            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11028
11029            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11030                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11031                        + " does not have the expected public key; ignoring");
11032                return -1;
11033            }
11034
11035            return pkg.applicationInfo.uid;
11036        }
11037    }
11038
11039    @Override
11040    public void finishPackageInstall(int token) {
11041        enforceSystemOrRoot("Only the system is allowed to finish installs");
11042
11043        if (DEBUG_INSTALL) {
11044            Slog.v(TAG, "BM finishing package install for " + token);
11045        }
11046        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11047
11048        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11049        mHandler.sendMessage(msg);
11050    }
11051
11052    /**
11053     * Get the verification agent timeout.
11054     *
11055     * @return verification timeout in milliseconds
11056     */
11057    private long getVerificationTimeout() {
11058        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11059                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11060                DEFAULT_VERIFICATION_TIMEOUT);
11061    }
11062
11063    /**
11064     * Get the default verification agent response code.
11065     *
11066     * @return default verification response code
11067     */
11068    private int getDefaultVerificationResponse() {
11069        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11070                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11071                DEFAULT_VERIFICATION_RESPONSE);
11072    }
11073
11074    /**
11075     * Check whether or not package verification has been enabled.
11076     *
11077     * @return true if verification should be performed
11078     */
11079    private boolean isVerificationEnabled(int userId, int installFlags) {
11080        if (!DEFAULT_VERIFY_ENABLE) {
11081            return false;
11082        }
11083        // Ephemeral apps don't get the full verification treatment
11084        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11085            if (DEBUG_EPHEMERAL) {
11086                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11087            }
11088            return false;
11089        }
11090
11091        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11092
11093        // Check if installing from ADB
11094        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11095            // Do not run verification in a test harness environment
11096            if (ActivityManager.isRunningInTestHarness()) {
11097                return false;
11098            }
11099            if (ensureVerifyAppsEnabled) {
11100                return true;
11101            }
11102            // Check if the developer does not want package verification for ADB installs
11103            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11104                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11105                return false;
11106            }
11107        }
11108
11109        if (ensureVerifyAppsEnabled) {
11110            return true;
11111        }
11112
11113        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11114                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11115    }
11116
11117    @Override
11118    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11119            throws RemoteException {
11120        mContext.enforceCallingOrSelfPermission(
11121                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11122                "Only intentfilter verification agents can verify applications");
11123
11124        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11125        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11126                Binder.getCallingUid(), verificationCode, failedDomains);
11127        msg.arg1 = id;
11128        msg.obj = response;
11129        mHandler.sendMessage(msg);
11130    }
11131
11132    @Override
11133    public int getIntentVerificationStatus(String packageName, int userId) {
11134        synchronized (mPackages) {
11135            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11136        }
11137    }
11138
11139    @Override
11140    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11141        mContext.enforceCallingOrSelfPermission(
11142                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11143
11144        boolean result = false;
11145        synchronized (mPackages) {
11146            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11147        }
11148        if (result) {
11149            scheduleWritePackageRestrictionsLocked(userId);
11150        }
11151        return result;
11152    }
11153
11154    @Override
11155    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11156            String packageName) {
11157        synchronized (mPackages) {
11158            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11159        }
11160    }
11161
11162    @Override
11163    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11164        if (TextUtils.isEmpty(packageName)) {
11165            return ParceledListSlice.emptyList();
11166        }
11167        synchronized (mPackages) {
11168            PackageParser.Package pkg = mPackages.get(packageName);
11169            if (pkg == null || pkg.activities == null) {
11170                return ParceledListSlice.emptyList();
11171            }
11172            final int count = pkg.activities.size();
11173            ArrayList<IntentFilter> result = new ArrayList<>();
11174            for (int n=0; n<count; n++) {
11175                PackageParser.Activity activity = pkg.activities.get(n);
11176                if (activity.intents != null && activity.intents.size() > 0) {
11177                    result.addAll(activity.intents);
11178                }
11179            }
11180            return new ParceledListSlice<>(result);
11181        }
11182    }
11183
11184    @Override
11185    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11186        mContext.enforceCallingOrSelfPermission(
11187                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11188
11189        synchronized (mPackages) {
11190            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11191            if (packageName != null) {
11192                result |= updateIntentVerificationStatus(packageName,
11193                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11194                        userId);
11195                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11196                        packageName, userId);
11197            }
11198            return result;
11199        }
11200    }
11201
11202    @Override
11203    public String getDefaultBrowserPackageName(int userId) {
11204        synchronized (mPackages) {
11205            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11206        }
11207    }
11208
11209    /**
11210     * Get the "allow unknown sources" setting.
11211     *
11212     * @return the current "allow unknown sources" setting
11213     */
11214    private int getUnknownSourcesSettings() {
11215        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11216                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
11217                -1);
11218    }
11219
11220    @Override
11221    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11222        final int uid = Binder.getCallingUid();
11223        // writer
11224        synchronized (mPackages) {
11225            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11226            if (targetPackageSetting == null) {
11227                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11228            }
11229
11230            PackageSetting installerPackageSetting;
11231            if (installerPackageName != null) {
11232                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11233                if (installerPackageSetting == null) {
11234                    throw new IllegalArgumentException("Unknown installer package: "
11235                            + installerPackageName);
11236                }
11237            } else {
11238                installerPackageSetting = null;
11239            }
11240
11241            Signature[] callerSignature;
11242            Object obj = mSettings.getUserIdLPr(uid);
11243            if (obj != null) {
11244                if (obj instanceof SharedUserSetting) {
11245                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11246                } else if (obj instanceof PackageSetting) {
11247                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11248                } else {
11249                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11250                }
11251            } else {
11252                throw new SecurityException("Unknown calling UID: " + uid);
11253            }
11254
11255            // Verify: can't set installerPackageName to a package that is
11256            // not signed with the same cert as the caller.
11257            if (installerPackageSetting != null) {
11258                if (compareSignatures(callerSignature,
11259                        installerPackageSetting.signatures.mSignatures)
11260                        != PackageManager.SIGNATURE_MATCH) {
11261                    throw new SecurityException(
11262                            "Caller does not have same cert as new installer package "
11263                            + installerPackageName);
11264                }
11265            }
11266
11267            // Verify: if target already has an installer package, it must
11268            // be signed with the same cert as the caller.
11269            if (targetPackageSetting.installerPackageName != null) {
11270                PackageSetting setting = mSettings.mPackages.get(
11271                        targetPackageSetting.installerPackageName);
11272                // If the currently set package isn't valid, then it's always
11273                // okay to change it.
11274                if (setting != null) {
11275                    if (compareSignatures(callerSignature,
11276                            setting.signatures.mSignatures)
11277                            != PackageManager.SIGNATURE_MATCH) {
11278                        throw new SecurityException(
11279                                "Caller does not have same cert as old installer package "
11280                                + targetPackageSetting.installerPackageName);
11281                    }
11282                }
11283            }
11284
11285            // Okay!
11286            targetPackageSetting.installerPackageName = installerPackageName;
11287            scheduleWriteSettingsLocked();
11288        }
11289    }
11290
11291    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11292        // Queue up an async operation since the package installation may take a little while.
11293        mHandler.post(new Runnable() {
11294            public void run() {
11295                mHandler.removeCallbacks(this);
11296                 // Result object to be returned
11297                PackageInstalledInfo res = new PackageInstalledInfo();
11298                res.setReturnCode(currentStatus);
11299                res.uid = -1;
11300                res.pkg = null;
11301                res.removedInfo = null;
11302                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11303                    args.doPreInstall(res.returnCode);
11304                    synchronized (mInstallLock) {
11305                        installPackageTracedLI(args, res);
11306                    }
11307                    args.doPostInstall(res.returnCode, res.uid);
11308                }
11309
11310                // A restore should be performed at this point if (a) the install
11311                // succeeded, (b) the operation is not an update, and (c) the new
11312                // package has not opted out of backup participation.
11313                final boolean update = res.removedInfo != null
11314                        && res.removedInfo.removedPackage != null;
11315                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11316                boolean doRestore = !update
11317                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11318
11319                // Set up the post-install work request bookkeeping.  This will be used
11320                // and cleaned up by the post-install event handling regardless of whether
11321                // there's a restore pass performed.  Token values are >= 1.
11322                int token;
11323                if (mNextInstallToken < 0) mNextInstallToken = 1;
11324                token = mNextInstallToken++;
11325
11326                PostInstallData data = new PostInstallData(args, res);
11327                mRunningInstalls.put(token, data);
11328                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11329
11330                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11331                    // Pass responsibility to the Backup Manager.  It will perform a
11332                    // restore if appropriate, then pass responsibility back to the
11333                    // Package Manager to run the post-install observer callbacks
11334                    // and broadcasts.
11335                    IBackupManager bm = IBackupManager.Stub.asInterface(
11336                            ServiceManager.getService(Context.BACKUP_SERVICE));
11337                    if (bm != null) {
11338                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11339                                + " to BM for possible restore");
11340                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11341                        try {
11342                            // TODO: http://b/22388012
11343                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11344                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11345                            } else {
11346                                doRestore = false;
11347                            }
11348                        } catch (RemoteException e) {
11349                            // can't happen; the backup manager is local
11350                        } catch (Exception e) {
11351                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11352                            doRestore = false;
11353                        }
11354                    } else {
11355                        Slog.e(TAG, "Backup Manager not found!");
11356                        doRestore = false;
11357                    }
11358                }
11359
11360                if (!doRestore) {
11361                    // No restore possible, or the Backup Manager was mysteriously not
11362                    // available -- just fire the post-install work request directly.
11363                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11364
11365                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11366
11367                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11368                    mHandler.sendMessage(msg);
11369                }
11370            }
11371        });
11372    }
11373
11374    private abstract class HandlerParams {
11375        private static final int MAX_RETRIES = 4;
11376
11377        /**
11378         * Number of times startCopy() has been attempted and had a non-fatal
11379         * error.
11380         */
11381        private int mRetries = 0;
11382
11383        /** User handle for the user requesting the information or installation. */
11384        private final UserHandle mUser;
11385        String traceMethod;
11386        int traceCookie;
11387
11388        HandlerParams(UserHandle user) {
11389            mUser = user;
11390        }
11391
11392        UserHandle getUser() {
11393            return mUser;
11394        }
11395
11396        HandlerParams setTraceMethod(String traceMethod) {
11397            this.traceMethod = traceMethod;
11398            return this;
11399        }
11400
11401        HandlerParams setTraceCookie(int traceCookie) {
11402            this.traceCookie = traceCookie;
11403            return this;
11404        }
11405
11406        final boolean startCopy() {
11407            boolean res;
11408            try {
11409                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11410
11411                if (++mRetries > MAX_RETRIES) {
11412                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11413                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11414                    handleServiceError();
11415                    return false;
11416                } else {
11417                    handleStartCopy();
11418                    res = true;
11419                }
11420            } catch (RemoteException e) {
11421                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11422                mHandler.sendEmptyMessage(MCS_RECONNECT);
11423                res = false;
11424            }
11425            handleReturnCode();
11426            return res;
11427        }
11428
11429        final void serviceError() {
11430            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11431            handleServiceError();
11432            handleReturnCode();
11433        }
11434
11435        abstract void handleStartCopy() throws RemoteException;
11436        abstract void handleServiceError();
11437        abstract void handleReturnCode();
11438    }
11439
11440    class MeasureParams extends HandlerParams {
11441        private final PackageStats mStats;
11442        private boolean mSuccess;
11443
11444        private final IPackageStatsObserver mObserver;
11445
11446        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11447            super(new UserHandle(stats.userHandle));
11448            mObserver = observer;
11449            mStats = stats;
11450        }
11451
11452        @Override
11453        public String toString() {
11454            return "MeasureParams{"
11455                + Integer.toHexString(System.identityHashCode(this))
11456                + " " + mStats.packageName + "}";
11457        }
11458
11459        @Override
11460        void handleStartCopy() throws RemoteException {
11461            synchronized (mInstallLock) {
11462                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11463            }
11464
11465            if (mSuccess) {
11466                final boolean mounted;
11467                if (Environment.isExternalStorageEmulated()) {
11468                    mounted = true;
11469                } else {
11470                    final String status = Environment.getExternalStorageState();
11471                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11472                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11473                }
11474
11475                if (mounted) {
11476                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11477
11478                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11479                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11480
11481                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11482                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11483
11484                    // Always subtract cache size, since it's a subdirectory
11485                    mStats.externalDataSize -= mStats.externalCacheSize;
11486
11487                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11488                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11489
11490                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11491                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11492                }
11493            }
11494        }
11495
11496        @Override
11497        void handleReturnCode() {
11498            if (mObserver != null) {
11499                try {
11500                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11501                } catch (RemoteException e) {
11502                    Slog.i(TAG, "Observer no longer exists.");
11503                }
11504            }
11505        }
11506
11507        @Override
11508        void handleServiceError() {
11509            Slog.e(TAG, "Could not measure application " + mStats.packageName
11510                            + " external storage");
11511        }
11512    }
11513
11514    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11515            throws RemoteException {
11516        long result = 0;
11517        for (File path : paths) {
11518            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11519        }
11520        return result;
11521    }
11522
11523    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11524        for (File path : paths) {
11525            try {
11526                mcs.clearDirectory(path.getAbsolutePath());
11527            } catch (RemoteException e) {
11528            }
11529        }
11530    }
11531
11532    static class OriginInfo {
11533        /**
11534         * Location where install is coming from, before it has been
11535         * copied/renamed into place. This could be a single monolithic APK
11536         * file, or a cluster directory. This location may be untrusted.
11537         */
11538        final File file;
11539        final String cid;
11540
11541        /**
11542         * Flag indicating that {@link #file} or {@link #cid} has already been
11543         * staged, meaning downstream users don't need to defensively copy the
11544         * contents.
11545         */
11546        final boolean staged;
11547
11548        /**
11549         * Flag indicating that {@link #file} or {@link #cid} is an already
11550         * installed app that is being moved.
11551         */
11552        final boolean existing;
11553
11554        final String resolvedPath;
11555        final File resolvedFile;
11556
11557        static OriginInfo fromNothing() {
11558            return new OriginInfo(null, null, false, false);
11559        }
11560
11561        static OriginInfo fromUntrustedFile(File file) {
11562            return new OriginInfo(file, null, false, false);
11563        }
11564
11565        static OriginInfo fromExistingFile(File file) {
11566            return new OriginInfo(file, null, false, true);
11567        }
11568
11569        static OriginInfo fromStagedFile(File file) {
11570            return new OriginInfo(file, null, true, false);
11571        }
11572
11573        static OriginInfo fromStagedContainer(String cid) {
11574            return new OriginInfo(null, cid, true, false);
11575        }
11576
11577        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
11578            this.file = file;
11579            this.cid = cid;
11580            this.staged = staged;
11581            this.existing = existing;
11582
11583            if (cid != null) {
11584                resolvedPath = PackageHelper.getSdDir(cid);
11585                resolvedFile = new File(resolvedPath);
11586            } else if (file != null) {
11587                resolvedPath = file.getAbsolutePath();
11588                resolvedFile = file;
11589            } else {
11590                resolvedPath = null;
11591                resolvedFile = null;
11592            }
11593        }
11594    }
11595
11596    static class MoveInfo {
11597        final int moveId;
11598        final String fromUuid;
11599        final String toUuid;
11600        final String packageName;
11601        final String dataAppName;
11602        final int appId;
11603        final String seinfo;
11604        final int targetSdkVersion;
11605
11606        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
11607                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
11608            this.moveId = moveId;
11609            this.fromUuid = fromUuid;
11610            this.toUuid = toUuid;
11611            this.packageName = packageName;
11612            this.dataAppName = dataAppName;
11613            this.appId = appId;
11614            this.seinfo = seinfo;
11615            this.targetSdkVersion = targetSdkVersion;
11616        }
11617    }
11618
11619    static class VerificationInfo {
11620        /** A constant used to indicate that a uid value is not present. */
11621        public static final int NO_UID = -1;
11622
11623        /** URI referencing where the package was downloaded from. */
11624        final Uri originatingUri;
11625
11626        /** HTTP referrer URI associated with the originatingURI. */
11627        final Uri referrer;
11628
11629        /** UID of the application that the install request originated from. */
11630        final int originatingUid;
11631
11632        /** UID of application requesting the install */
11633        final int installerUid;
11634
11635        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
11636            this.originatingUri = originatingUri;
11637            this.referrer = referrer;
11638            this.originatingUid = originatingUid;
11639            this.installerUid = installerUid;
11640        }
11641    }
11642
11643    class InstallParams extends HandlerParams {
11644        final OriginInfo origin;
11645        final MoveInfo move;
11646        final IPackageInstallObserver2 observer;
11647        int installFlags;
11648        final String installerPackageName;
11649        final String volumeUuid;
11650        private InstallArgs mArgs;
11651        private int mRet;
11652        final String packageAbiOverride;
11653        final String[] grantedRuntimePermissions;
11654        final VerificationInfo verificationInfo;
11655
11656        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
11657                int installFlags, String installerPackageName, String volumeUuid,
11658                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
11659                String[] grantedPermissions) {
11660            super(user);
11661            this.origin = origin;
11662            this.move = move;
11663            this.observer = observer;
11664            this.installFlags = installFlags;
11665            this.installerPackageName = installerPackageName;
11666            this.volumeUuid = volumeUuid;
11667            this.verificationInfo = verificationInfo;
11668            this.packageAbiOverride = packageAbiOverride;
11669            this.grantedRuntimePermissions = grantedPermissions;
11670        }
11671
11672        @Override
11673        public String toString() {
11674            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
11675                    + " file=" + origin.file + " cid=" + origin.cid + "}";
11676        }
11677
11678        private int installLocationPolicy(PackageInfoLite pkgLite) {
11679            String packageName = pkgLite.packageName;
11680            int installLocation = pkgLite.installLocation;
11681            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11682            // reader
11683            synchronized (mPackages) {
11684                // Currently installed package which the new package is attempting to replace or
11685                // null if no such package is installed.
11686                PackageParser.Package installedPkg = mPackages.get(packageName);
11687                // Package which currently owns the data which the new package will own if installed.
11688                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
11689                // will be null whereas dataOwnerPkg will contain information about the package
11690                // which was uninstalled while keeping its data.
11691                PackageParser.Package dataOwnerPkg = installedPkg;
11692                if (dataOwnerPkg  == null) {
11693                    PackageSetting ps = mSettings.mPackages.get(packageName);
11694                    if (ps != null) {
11695                        dataOwnerPkg = ps.pkg;
11696                    }
11697                }
11698
11699                if (dataOwnerPkg != null) {
11700                    // If installed, the package will get access to data left on the device by its
11701                    // predecessor. As a security measure, this is permited only if this is not a
11702                    // version downgrade or if the predecessor package is marked as debuggable and
11703                    // a downgrade is explicitly requested.
11704                    if (((dataOwnerPkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0)
11705                            || ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0)) {
11706                        try {
11707                            checkDowngrade(dataOwnerPkg, pkgLite);
11708                        } catch (PackageManagerException e) {
11709                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
11710                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
11711                        }
11712                    }
11713                }
11714
11715                if (installedPkg != null) {
11716                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11717                        // Check for updated system application.
11718                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11719                            if (onSd) {
11720                                Slog.w(TAG, "Cannot install update to system app on sdcard");
11721                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
11722                            }
11723                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11724                        } else {
11725                            if (onSd) {
11726                                // Install flag overrides everything.
11727                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11728                            }
11729                            // If current upgrade specifies particular preference
11730                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
11731                                // Application explicitly specified internal.
11732                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11733                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
11734                                // App explictly prefers external. Let policy decide
11735                            } else {
11736                                // Prefer previous location
11737                                if (isExternal(installedPkg)) {
11738                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11739                                }
11740                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
11741                            }
11742                        }
11743                    } else {
11744                        // Invalid install. Return error code
11745                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
11746                    }
11747                }
11748            }
11749            // All the special cases have been taken care of.
11750            // Return result based on recommended install location.
11751            if (onSd) {
11752                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
11753            }
11754            return pkgLite.recommendedInstallLocation;
11755        }
11756
11757        /*
11758         * Invoke remote method to get package information and install
11759         * location values. Override install location based on default
11760         * policy if needed and then create install arguments based
11761         * on the install location.
11762         */
11763        public void handleStartCopy() throws RemoteException {
11764            int ret = PackageManager.INSTALL_SUCCEEDED;
11765
11766            // If we're already staged, we've firmly committed to an install location
11767            if (origin.staged) {
11768                if (origin.file != null) {
11769                    installFlags |= PackageManager.INSTALL_INTERNAL;
11770                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11771                } else if (origin.cid != null) {
11772                    installFlags |= PackageManager.INSTALL_EXTERNAL;
11773                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
11774                } else {
11775                    throw new IllegalStateException("Invalid stage location");
11776                }
11777            }
11778
11779            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
11780            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
11781            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
11782            PackageInfoLite pkgLite = null;
11783
11784            if (onInt && onSd) {
11785                // Check if both bits are set.
11786                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
11787                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11788            } else if (onSd && ephemeral) {
11789                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
11790                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11791            } else {
11792                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
11793                        packageAbiOverride);
11794
11795                if (DEBUG_EPHEMERAL && ephemeral) {
11796                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
11797                }
11798
11799                /*
11800                 * If we have too little free space, try to free cache
11801                 * before giving up.
11802                 */
11803                if (!origin.staged && pkgLite.recommendedInstallLocation
11804                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11805                    // TODO: focus freeing disk space on the target device
11806                    final StorageManager storage = StorageManager.from(mContext);
11807                    final long lowThreshold = storage.getStorageLowBytes(
11808                            Environment.getDataDirectory());
11809
11810                    final long sizeBytes = mContainerService.calculateInstalledSize(
11811                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
11812
11813                    try {
11814                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
11815                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
11816                                installFlags, packageAbiOverride);
11817                    } catch (InstallerException e) {
11818                        Slog.w(TAG, "Failed to free cache", e);
11819                    }
11820
11821                    /*
11822                     * The cache free must have deleted the file we
11823                     * downloaded to install.
11824                     *
11825                     * TODO: fix the "freeCache" call to not delete
11826                     *       the file we care about.
11827                     */
11828                    if (pkgLite.recommendedInstallLocation
11829                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11830                        pkgLite.recommendedInstallLocation
11831                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
11832                    }
11833                }
11834            }
11835
11836            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11837                int loc = pkgLite.recommendedInstallLocation;
11838                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
11839                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
11840                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
11841                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
11842                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
11843                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
11844                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
11845                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
11846                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
11847                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
11848                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
11849                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
11850                } else {
11851                    // Override with defaults if needed.
11852                    loc = installLocationPolicy(pkgLite);
11853                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
11854                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
11855                    } else if (!onSd && !onInt) {
11856                        // Override install location with flags
11857                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
11858                            // Set the flag to install on external media.
11859                            installFlags |= PackageManager.INSTALL_EXTERNAL;
11860                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
11861                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
11862                            if (DEBUG_EPHEMERAL) {
11863                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
11864                            }
11865                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
11866                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
11867                                    |PackageManager.INSTALL_INTERNAL);
11868                        } else {
11869                            // Make sure the flag for installing on external
11870                            // media is unset
11871                            installFlags |= PackageManager.INSTALL_INTERNAL;
11872                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
11873                        }
11874                    }
11875                }
11876            }
11877
11878            final InstallArgs args = createInstallArgs(this);
11879            mArgs = args;
11880
11881            if (ret == PackageManager.INSTALL_SUCCEEDED) {
11882                // TODO: http://b/22976637
11883                // Apps installed for "all" users use the device owner to verify the app
11884                UserHandle verifierUser = getUser();
11885                if (verifierUser == UserHandle.ALL) {
11886                    verifierUser = UserHandle.SYSTEM;
11887                }
11888
11889                /*
11890                 * Determine if we have any installed package verifiers. If we
11891                 * do, then we'll defer to them to verify the packages.
11892                 */
11893                final int requiredUid = mRequiredVerifierPackage == null ? -1
11894                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
11895                                verifierUser.getIdentifier());
11896                if (!origin.existing && requiredUid != -1
11897                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
11898                    final Intent verification = new Intent(
11899                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
11900                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
11901                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
11902                            PACKAGE_MIME_TYPE);
11903                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11904
11905                    // Query all live verifiers based on current user state
11906                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
11907                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
11908
11909                    if (DEBUG_VERIFY) {
11910                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
11911                                + verification.toString() + " with " + pkgLite.verifiers.length
11912                                + " optional verifiers");
11913                    }
11914
11915                    final int verificationId = mPendingVerificationToken++;
11916
11917                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11918
11919                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
11920                            installerPackageName);
11921
11922                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
11923                            installFlags);
11924
11925                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
11926                            pkgLite.packageName);
11927
11928                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
11929                            pkgLite.versionCode);
11930
11931                    if (verificationInfo != null) {
11932                        if (verificationInfo.originatingUri != null) {
11933                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
11934                                    verificationInfo.originatingUri);
11935                        }
11936                        if (verificationInfo.referrer != null) {
11937                            verification.putExtra(Intent.EXTRA_REFERRER,
11938                                    verificationInfo.referrer);
11939                        }
11940                        if (verificationInfo.originatingUid >= 0) {
11941                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
11942                                    verificationInfo.originatingUid);
11943                        }
11944                        if (verificationInfo.installerUid >= 0) {
11945                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
11946                                    verificationInfo.installerUid);
11947                        }
11948                    }
11949
11950                    final PackageVerificationState verificationState = new PackageVerificationState(
11951                            requiredUid, args);
11952
11953                    mPendingVerification.append(verificationId, verificationState);
11954
11955                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
11956                            receivers, verificationState);
11957
11958                    /*
11959                     * If any sufficient verifiers were listed in the package
11960                     * manifest, attempt to ask them.
11961                     */
11962                    if (sufficientVerifiers != null) {
11963                        final int N = sufficientVerifiers.size();
11964                        if (N == 0) {
11965                            Slog.i(TAG, "Additional verifiers required, but none installed.");
11966                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
11967                        } else {
11968                            for (int i = 0; i < N; i++) {
11969                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
11970
11971                                final Intent sufficientIntent = new Intent(verification);
11972                                sufficientIntent.setComponent(verifierComponent);
11973                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
11974                            }
11975                        }
11976                    }
11977
11978                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
11979                            mRequiredVerifierPackage, receivers);
11980                    if (ret == PackageManager.INSTALL_SUCCEEDED
11981                            && mRequiredVerifierPackage != null) {
11982                        Trace.asyncTraceBegin(
11983                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
11984                        /*
11985                         * Send the intent to the required verification agent,
11986                         * but only start the verification timeout after the
11987                         * target BroadcastReceivers have run.
11988                         */
11989                        verification.setComponent(requiredVerifierComponent);
11990                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
11991                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11992                                new BroadcastReceiver() {
11993                                    @Override
11994                                    public void onReceive(Context context, Intent intent) {
11995                                        final Message msg = mHandler
11996                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
11997                                        msg.arg1 = verificationId;
11998                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
11999                                    }
12000                                }, null, 0, null, null);
12001
12002                        /*
12003                         * We don't want the copy to proceed until verification
12004                         * succeeds, so null out this field.
12005                         */
12006                        mArgs = null;
12007                    }
12008                } else {
12009                    /*
12010                     * No package verification is enabled, so immediately start
12011                     * the remote call to initiate copy using temporary file.
12012                     */
12013                    ret = args.copyApk(mContainerService, true);
12014                }
12015            }
12016
12017            mRet = ret;
12018        }
12019
12020        @Override
12021        void handleReturnCode() {
12022            // If mArgs is null, then MCS couldn't be reached. When it
12023            // reconnects, it will try again to install. At that point, this
12024            // will succeed.
12025            if (mArgs != null) {
12026                processPendingInstall(mArgs, mRet);
12027            }
12028        }
12029
12030        @Override
12031        void handleServiceError() {
12032            mArgs = createInstallArgs(this);
12033            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12034        }
12035
12036        public boolean isForwardLocked() {
12037            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12038        }
12039    }
12040
12041    /**
12042     * Used during creation of InstallArgs
12043     *
12044     * @param installFlags package installation flags
12045     * @return true if should be installed on external storage
12046     */
12047    private static boolean installOnExternalAsec(int installFlags) {
12048        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12049            return false;
12050        }
12051        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12052            return true;
12053        }
12054        return false;
12055    }
12056
12057    /**
12058     * Used during creation of InstallArgs
12059     *
12060     * @param installFlags package installation flags
12061     * @return true if should be installed as forward locked
12062     */
12063    private static boolean installForwardLocked(int installFlags) {
12064        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12065    }
12066
12067    private InstallArgs createInstallArgs(InstallParams params) {
12068        if (params.move != null) {
12069            return new MoveInstallArgs(params);
12070        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12071            return new AsecInstallArgs(params);
12072        } else {
12073            return new FileInstallArgs(params);
12074        }
12075    }
12076
12077    /**
12078     * Create args that describe an existing installed package. Typically used
12079     * when cleaning up old installs, or used as a move source.
12080     */
12081    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12082            String resourcePath, String[] instructionSets) {
12083        final boolean isInAsec;
12084        if (installOnExternalAsec(installFlags)) {
12085            /* Apps on SD card are always in ASEC containers. */
12086            isInAsec = true;
12087        } else if (installForwardLocked(installFlags)
12088                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12089            /*
12090             * Forward-locked apps are only in ASEC containers if they're the
12091             * new style
12092             */
12093            isInAsec = true;
12094        } else {
12095            isInAsec = false;
12096        }
12097
12098        if (isInAsec) {
12099            return new AsecInstallArgs(codePath, instructionSets,
12100                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12101        } else {
12102            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12103        }
12104    }
12105
12106    static abstract class InstallArgs {
12107        /** @see InstallParams#origin */
12108        final OriginInfo origin;
12109        /** @see InstallParams#move */
12110        final MoveInfo move;
12111
12112        final IPackageInstallObserver2 observer;
12113        // Always refers to PackageManager flags only
12114        final int installFlags;
12115        final String installerPackageName;
12116        final String volumeUuid;
12117        final UserHandle user;
12118        final String abiOverride;
12119        final String[] installGrantPermissions;
12120        /** If non-null, drop an async trace when the install completes */
12121        final String traceMethod;
12122        final int traceCookie;
12123
12124        // The list of instruction sets supported by this app. This is currently
12125        // only used during the rmdex() phase to clean up resources. We can get rid of this
12126        // if we move dex files under the common app path.
12127        /* nullable */ String[] instructionSets;
12128
12129        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12130                int installFlags, String installerPackageName, String volumeUuid,
12131                UserHandle user, String[] instructionSets,
12132                String abiOverride, String[] installGrantPermissions,
12133                String traceMethod, int traceCookie) {
12134            this.origin = origin;
12135            this.move = move;
12136            this.installFlags = installFlags;
12137            this.observer = observer;
12138            this.installerPackageName = installerPackageName;
12139            this.volumeUuid = volumeUuid;
12140            this.user = user;
12141            this.instructionSets = instructionSets;
12142            this.abiOverride = abiOverride;
12143            this.installGrantPermissions = installGrantPermissions;
12144            this.traceMethod = traceMethod;
12145            this.traceCookie = traceCookie;
12146        }
12147
12148        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12149        abstract int doPreInstall(int status);
12150
12151        /**
12152         * Rename package into final resting place. All paths on the given
12153         * scanned package should be updated to reflect the rename.
12154         */
12155        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12156        abstract int doPostInstall(int status, int uid);
12157
12158        /** @see PackageSettingBase#codePathString */
12159        abstract String getCodePath();
12160        /** @see PackageSettingBase#resourcePathString */
12161        abstract String getResourcePath();
12162
12163        // Need installer lock especially for dex file removal.
12164        abstract void cleanUpResourcesLI();
12165        abstract boolean doPostDeleteLI(boolean delete);
12166
12167        /**
12168         * Called before the source arguments are copied. This is used mostly
12169         * for MoveParams when it needs to read the source file to put it in the
12170         * destination.
12171         */
12172        int doPreCopy() {
12173            return PackageManager.INSTALL_SUCCEEDED;
12174        }
12175
12176        /**
12177         * Called after the source arguments are copied. This is used mostly for
12178         * MoveParams when it needs to read the source file to put it in the
12179         * destination.
12180         *
12181         * @return
12182         */
12183        int doPostCopy(int uid) {
12184            return PackageManager.INSTALL_SUCCEEDED;
12185        }
12186
12187        protected boolean isFwdLocked() {
12188            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12189        }
12190
12191        protected boolean isExternalAsec() {
12192            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12193        }
12194
12195        protected boolean isEphemeral() {
12196            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12197        }
12198
12199        UserHandle getUser() {
12200            return user;
12201        }
12202    }
12203
12204    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12205        if (!allCodePaths.isEmpty()) {
12206            if (instructionSets == null) {
12207                throw new IllegalStateException("instructionSet == null");
12208            }
12209            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12210            for (String codePath : allCodePaths) {
12211                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12212                    try {
12213                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12214                    } catch (InstallerException ignored) {
12215                    }
12216                }
12217            }
12218        }
12219    }
12220
12221    /**
12222     * Logic to handle installation of non-ASEC applications, including copying
12223     * and renaming logic.
12224     */
12225    class FileInstallArgs extends InstallArgs {
12226        private File codeFile;
12227        private File resourceFile;
12228
12229        // Example topology:
12230        // /data/app/com.example/base.apk
12231        // /data/app/com.example/split_foo.apk
12232        // /data/app/com.example/lib/arm/libfoo.so
12233        // /data/app/com.example/lib/arm64/libfoo.so
12234        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12235
12236        /** New install */
12237        FileInstallArgs(InstallParams params) {
12238            super(params.origin, params.move, params.observer, params.installFlags,
12239                    params.installerPackageName, params.volumeUuid,
12240                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12241                    params.grantedRuntimePermissions,
12242                    params.traceMethod, params.traceCookie);
12243            if (isFwdLocked()) {
12244                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12245            }
12246        }
12247
12248        /** Existing install */
12249        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12250            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12251                    null, null, null, 0);
12252            this.codeFile = (codePath != null) ? new File(codePath) : null;
12253            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12254        }
12255
12256        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12257            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12258            try {
12259                return doCopyApk(imcs, temp);
12260            } finally {
12261                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12262            }
12263        }
12264
12265        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12266            if (origin.staged) {
12267                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12268                codeFile = origin.file;
12269                resourceFile = origin.file;
12270                return PackageManager.INSTALL_SUCCEEDED;
12271            }
12272
12273            try {
12274                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12275                final File tempDir =
12276                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12277                codeFile = tempDir;
12278                resourceFile = tempDir;
12279            } catch (IOException e) {
12280                Slog.w(TAG, "Failed to create copy file: " + e);
12281                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12282            }
12283
12284            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12285                @Override
12286                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12287                    if (!FileUtils.isValidExtFilename(name)) {
12288                        throw new IllegalArgumentException("Invalid filename: " + name);
12289                    }
12290                    try {
12291                        final File file = new File(codeFile, name);
12292                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12293                                O_RDWR | O_CREAT, 0644);
12294                        Os.chmod(file.getAbsolutePath(), 0644);
12295                        return new ParcelFileDescriptor(fd);
12296                    } catch (ErrnoException e) {
12297                        throw new RemoteException("Failed to open: " + e.getMessage());
12298                    }
12299                }
12300            };
12301
12302            int ret = PackageManager.INSTALL_SUCCEEDED;
12303            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12304            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12305                Slog.e(TAG, "Failed to copy package");
12306                return ret;
12307            }
12308
12309            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12310            NativeLibraryHelper.Handle handle = null;
12311            try {
12312                handle = NativeLibraryHelper.Handle.create(codeFile);
12313                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12314                        abiOverride);
12315            } catch (IOException e) {
12316                Slog.e(TAG, "Copying native libraries failed", e);
12317                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12318            } finally {
12319                IoUtils.closeQuietly(handle);
12320            }
12321
12322            return ret;
12323        }
12324
12325        int doPreInstall(int status) {
12326            if (status != PackageManager.INSTALL_SUCCEEDED) {
12327                cleanUp();
12328            }
12329            return status;
12330        }
12331
12332        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12333            if (status != PackageManager.INSTALL_SUCCEEDED) {
12334                cleanUp();
12335                return false;
12336            }
12337
12338            final File targetDir = codeFile.getParentFile();
12339            final File beforeCodeFile = codeFile;
12340            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12341
12342            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12343            try {
12344                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12345            } catch (ErrnoException e) {
12346                Slog.w(TAG, "Failed to rename", e);
12347                return false;
12348            }
12349
12350            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12351                Slog.w(TAG, "Failed to restorecon");
12352                return false;
12353            }
12354
12355            // Reflect the rename internally
12356            codeFile = afterCodeFile;
12357            resourceFile = afterCodeFile;
12358
12359            // Reflect the rename in scanned details
12360            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12361            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12362                    afterCodeFile, pkg.baseCodePath));
12363            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12364                    afterCodeFile, pkg.splitCodePaths));
12365
12366            // Reflect the rename in app info
12367            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12368            pkg.setApplicationInfoCodePath(pkg.codePath);
12369            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12370            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12371            pkg.setApplicationInfoResourcePath(pkg.codePath);
12372            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12373            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12374
12375            return true;
12376        }
12377
12378        int doPostInstall(int status, int uid) {
12379            if (status != PackageManager.INSTALL_SUCCEEDED) {
12380                cleanUp();
12381            }
12382            return status;
12383        }
12384
12385        @Override
12386        String getCodePath() {
12387            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12388        }
12389
12390        @Override
12391        String getResourcePath() {
12392            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12393        }
12394
12395        private boolean cleanUp() {
12396            if (codeFile == null || !codeFile.exists()) {
12397                return false;
12398            }
12399
12400            removeCodePathLI(codeFile);
12401
12402            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12403                resourceFile.delete();
12404            }
12405
12406            return true;
12407        }
12408
12409        void cleanUpResourcesLI() {
12410            // Try enumerating all code paths before deleting
12411            List<String> allCodePaths = Collections.EMPTY_LIST;
12412            if (codeFile != null && codeFile.exists()) {
12413                try {
12414                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12415                    allCodePaths = pkg.getAllCodePaths();
12416                } catch (PackageParserException e) {
12417                    // Ignored; we tried our best
12418                }
12419            }
12420
12421            cleanUp();
12422            removeDexFiles(allCodePaths, instructionSets);
12423        }
12424
12425        boolean doPostDeleteLI(boolean delete) {
12426            // XXX err, shouldn't we respect the delete flag?
12427            cleanUpResourcesLI();
12428            return true;
12429        }
12430    }
12431
12432    private boolean isAsecExternal(String cid) {
12433        final String asecPath = PackageHelper.getSdFilesystem(cid);
12434        return !asecPath.startsWith(mAsecInternalPath);
12435    }
12436
12437    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12438            PackageManagerException {
12439        if (copyRet < 0) {
12440            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12441                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12442                throw new PackageManagerException(copyRet, message);
12443            }
12444        }
12445    }
12446
12447    /**
12448     * Extract the MountService "container ID" from the full code path of an
12449     * .apk.
12450     */
12451    static String cidFromCodePath(String fullCodePath) {
12452        int eidx = fullCodePath.lastIndexOf("/");
12453        String subStr1 = fullCodePath.substring(0, eidx);
12454        int sidx = subStr1.lastIndexOf("/");
12455        return subStr1.substring(sidx+1, eidx);
12456    }
12457
12458    /**
12459     * Logic to handle installation of ASEC applications, including copying and
12460     * renaming logic.
12461     */
12462    class AsecInstallArgs extends InstallArgs {
12463        static final String RES_FILE_NAME = "pkg.apk";
12464        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12465
12466        String cid;
12467        String packagePath;
12468        String resourcePath;
12469
12470        /** New install */
12471        AsecInstallArgs(InstallParams params) {
12472            super(params.origin, params.move, params.observer, params.installFlags,
12473                    params.installerPackageName, params.volumeUuid,
12474                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12475                    params.grantedRuntimePermissions,
12476                    params.traceMethod, params.traceCookie);
12477        }
12478
12479        /** Existing install */
12480        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12481                        boolean isExternal, boolean isForwardLocked) {
12482            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12483                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12484                    instructionSets, null, null, null, 0);
12485            // Hackily pretend we're still looking at a full code path
12486            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12487                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12488            }
12489
12490            // Extract cid from fullCodePath
12491            int eidx = fullCodePath.lastIndexOf("/");
12492            String subStr1 = fullCodePath.substring(0, eidx);
12493            int sidx = subStr1.lastIndexOf("/");
12494            cid = subStr1.substring(sidx+1, eidx);
12495            setMountPath(subStr1);
12496        }
12497
12498        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12499            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12500                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12501                    instructionSets, null, null, null, 0);
12502            this.cid = cid;
12503            setMountPath(PackageHelper.getSdDir(cid));
12504        }
12505
12506        void createCopyFile() {
12507            cid = mInstallerService.allocateExternalStageCidLegacy();
12508        }
12509
12510        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12511            if (origin.staged && origin.cid != null) {
12512                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12513                cid = origin.cid;
12514                setMountPath(PackageHelper.getSdDir(cid));
12515                return PackageManager.INSTALL_SUCCEEDED;
12516            }
12517
12518            if (temp) {
12519                createCopyFile();
12520            } else {
12521                /*
12522                 * Pre-emptively destroy the container since it's destroyed if
12523                 * copying fails due to it existing anyway.
12524                 */
12525                PackageHelper.destroySdDir(cid);
12526            }
12527
12528            final String newMountPath = imcs.copyPackageToContainer(
12529                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12530                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12531
12532            if (newMountPath != null) {
12533                setMountPath(newMountPath);
12534                return PackageManager.INSTALL_SUCCEEDED;
12535            } else {
12536                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12537            }
12538        }
12539
12540        @Override
12541        String getCodePath() {
12542            return packagePath;
12543        }
12544
12545        @Override
12546        String getResourcePath() {
12547            return resourcePath;
12548        }
12549
12550        int doPreInstall(int status) {
12551            if (status != PackageManager.INSTALL_SUCCEEDED) {
12552                // Destroy container
12553                PackageHelper.destroySdDir(cid);
12554            } else {
12555                boolean mounted = PackageHelper.isContainerMounted(cid);
12556                if (!mounted) {
12557                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
12558                            Process.SYSTEM_UID);
12559                    if (newMountPath != null) {
12560                        setMountPath(newMountPath);
12561                    } else {
12562                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12563                    }
12564                }
12565            }
12566            return status;
12567        }
12568
12569        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12570            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
12571            String newMountPath = null;
12572            if (PackageHelper.isContainerMounted(cid)) {
12573                // Unmount the container
12574                if (!PackageHelper.unMountSdDir(cid)) {
12575                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
12576                    return false;
12577                }
12578            }
12579            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12580                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
12581                        " which might be stale. Will try to clean up.");
12582                // Clean up the stale container and proceed to recreate.
12583                if (!PackageHelper.destroySdDir(newCacheId)) {
12584                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
12585                    return false;
12586                }
12587                // Successfully cleaned up stale container. Try to rename again.
12588                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
12589                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
12590                            + " inspite of cleaning it up.");
12591                    return false;
12592                }
12593            }
12594            if (!PackageHelper.isContainerMounted(newCacheId)) {
12595                Slog.w(TAG, "Mounting container " + newCacheId);
12596                newMountPath = PackageHelper.mountSdDir(newCacheId,
12597                        getEncryptKey(), Process.SYSTEM_UID);
12598            } else {
12599                newMountPath = PackageHelper.getSdDir(newCacheId);
12600            }
12601            if (newMountPath == null) {
12602                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
12603                return false;
12604            }
12605            Log.i(TAG, "Succesfully renamed " + cid +
12606                    " to " + newCacheId +
12607                    " at new path: " + newMountPath);
12608            cid = newCacheId;
12609
12610            final File beforeCodeFile = new File(packagePath);
12611            setMountPath(newMountPath);
12612            final File afterCodeFile = new File(packagePath);
12613
12614            // Reflect the rename in scanned details
12615            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12616            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12617                    afterCodeFile, pkg.baseCodePath));
12618            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12619                    afterCodeFile, pkg.splitCodePaths));
12620
12621            // Reflect the rename in app info
12622            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12623            pkg.setApplicationInfoCodePath(pkg.codePath);
12624            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12625            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12626            pkg.setApplicationInfoResourcePath(pkg.codePath);
12627            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12628            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12629
12630            return true;
12631        }
12632
12633        private void setMountPath(String mountPath) {
12634            final File mountFile = new File(mountPath);
12635
12636            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
12637            if (monolithicFile.exists()) {
12638                packagePath = monolithicFile.getAbsolutePath();
12639                if (isFwdLocked()) {
12640                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
12641                } else {
12642                    resourcePath = packagePath;
12643                }
12644            } else {
12645                packagePath = mountFile.getAbsolutePath();
12646                resourcePath = packagePath;
12647            }
12648        }
12649
12650        int doPostInstall(int status, int uid) {
12651            if (status != PackageManager.INSTALL_SUCCEEDED) {
12652                cleanUp();
12653            } else {
12654                final int groupOwner;
12655                final String protectedFile;
12656                if (isFwdLocked()) {
12657                    groupOwner = UserHandle.getSharedAppGid(uid);
12658                    protectedFile = RES_FILE_NAME;
12659                } else {
12660                    groupOwner = -1;
12661                    protectedFile = null;
12662                }
12663
12664                if (uid < Process.FIRST_APPLICATION_UID
12665                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
12666                    Slog.e(TAG, "Failed to finalize " + cid);
12667                    PackageHelper.destroySdDir(cid);
12668                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12669                }
12670
12671                boolean mounted = PackageHelper.isContainerMounted(cid);
12672                if (!mounted) {
12673                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
12674                }
12675            }
12676            return status;
12677        }
12678
12679        private void cleanUp() {
12680            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
12681
12682            // Destroy secure container
12683            PackageHelper.destroySdDir(cid);
12684        }
12685
12686        private List<String> getAllCodePaths() {
12687            final File codeFile = new File(getCodePath());
12688            if (codeFile != null && codeFile.exists()) {
12689                try {
12690                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12691                    return pkg.getAllCodePaths();
12692                } catch (PackageParserException e) {
12693                    // Ignored; we tried our best
12694                }
12695            }
12696            return Collections.EMPTY_LIST;
12697        }
12698
12699        void cleanUpResourcesLI() {
12700            // Enumerate all code paths before deleting
12701            cleanUpResourcesLI(getAllCodePaths());
12702        }
12703
12704        private void cleanUpResourcesLI(List<String> allCodePaths) {
12705            cleanUp();
12706            removeDexFiles(allCodePaths, instructionSets);
12707        }
12708
12709        String getPackageName() {
12710            return getAsecPackageName(cid);
12711        }
12712
12713        boolean doPostDeleteLI(boolean delete) {
12714            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
12715            final List<String> allCodePaths = getAllCodePaths();
12716            boolean mounted = PackageHelper.isContainerMounted(cid);
12717            if (mounted) {
12718                // Unmount first
12719                if (PackageHelper.unMountSdDir(cid)) {
12720                    mounted = false;
12721                }
12722            }
12723            if (!mounted && delete) {
12724                cleanUpResourcesLI(allCodePaths);
12725            }
12726            return !mounted;
12727        }
12728
12729        @Override
12730        int doPreCopy() {
12731            if (isFwdLocked()) {
12732                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
12733                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
12734                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12735                }
12736            }
12737
12738            return PackageManager.INSTALL_SUCCEEDED;
12739        }
12740
12741        @Override
12742        int doPostCopy(int uid) {
12743            if (isFwdLocked()) {
12744                if (uid < Process.FIRST_APPLICATION_UID
12745                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
12746                                RES_FILE_NAME)) {
12747                    Slog.e(TAG, "Failed to finalize " + cid);
12748                    PackageHelper.destroySdDir(cid);
12749                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12750                }
12751            }
12752
12753            return PackageManager.INSTALL_SUCCEEDED;
12754        }
12755    }
12756
12757    /**
12758     * Logic to handle movement of existing installed applications.
12759     */
12760    class MoveInstallArgs extends InstallArgs {
12761        private File codeFile;
12762        private File resourceFile;
12763
12764        /** New install */
12765        MoveInstallArgs(InstallParams params) {
12766            super(params.origin, params.move, params.observer, params.installFlags,
12767                    params.installerPackageName, params.volumeUuid,
12768                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12769                    params.grantedRuntimePermissions,
12770                    params.traceMethod, params.traceCookie);
12771        }
12772
12773        int copyApk(IMediaContainerService imcs, boolean temp) {
12774            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
12775                    + move.fromUuid + " to " + move.toUuid);
12776            synchronized (mInstaller) {
12777                try {
12778                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
12779                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
12780                } catch (InstallerException e) {
12781                    Slog.w(TAG, "Failed to move app", e);
12782                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12783                }
12784            }
12785
12786            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
12787            resourceFile = codeFile;
12788            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
12789
12790            return PackageManager.INSTALL_SUCCEEDED;
12791        }
12792
12793        int doPreInstall(int status) {
12794            if (status != PackageManager.INSTALL_SUCCEEDED) {
12795                cleanUp(move.toUuid);
12796            }
12797            return status;
12798        }
12799
12800        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12801            if (status != PackageManager.INSTALL_SUCCEEDED) {
12802                cleanUp(move.toUuid);
12803                return false;
12804            }
12805
12806            // Reflect the move in app info
12807            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12808            pkg.setApplicationInfoCodePath(pkg.codePath);
12809            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12810            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12811            pkg.setApplicationInfoResourcePath(pkg.codePath);
12812            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12813            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12814
12815            return true;
12816        }
12817
12818        int doPostInstall(int status, int uid) {
12819            if (status == PackageManager.INSTALL_SUCCEEDED) {
12820                cleanUp(move.fromUuid);
12821            } else {
12822                cleanUp(move.toUuid);
12823            }
12824            return status;
12825        }
12826
12827        @Override
12828        String getCodePath() {
12829            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12830        }
12831
12832        @Override
12833        String getResourcePath() {
12834            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12835        }
12836
12837        private boolean cleanUp(String volumeUuid) {
12838            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
12839                    move.dataAppName);
12840            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
12841            synchronized (mInstallLock) {
12842                // Clean up both app data and code
12843                removeDataDirsLI(volumeUuid, move.packageName);
12844                removeCodePathLI(codeFile);
12845            }
12846            return true;
12847        }
12848
12849        void cleanUpResourcesLI() {
12850            throw new UnsupportedOperationException();
12851        }
12852
12853        boolean doPostDeleteLI(boolean delete) {
12854            throw new UnsupportedOperationException();
12855        }
12856    }
12857
12858    static String getAsecPackageName(String packageCid) {
12859        int idx = packageCid.lastIndexOf("-");
12860        if (idx == -1) {
12861            return packageCid;
12862        }
12863        return packageCid.substring(0, idx);
12864    }
12865
12866    // Utility method used to create code paths based on package name and available index.
12867    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
12868        String idxStr = "";
12869        int idx = 1;
12870        // Fall back to default value of idx=1 if prefix is not
12871        // part of oldCodePath
12872        if (oldCodePath != null) {
12873            String subStr = oldCodePath;
12874            // Drop the suffix right away
12875            if (suffix != null && subStr.endsWith(suffix)) {
12876                subStr = subStr.substring(0, subStr.length() - suffix.length());
12877            }
12878            // If oldCodePath already contains prefix find out the
12879            // ending index to either increment or decrement.
12880            int sidx = subStr.lastIndexOf(prefix);
12881            if (sidx != -1) {
12882                subStr = subStr.substring(sidx + prefix.length());
12883                if (subStr != null) {
12884                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
12885                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
12886                    }
12887                    try {
12888                        idx = Integer.parseInt(subStr);
12889                        if (idx <= 1) {
12890                            idx++;
12891                        } else {
12892                            idx--;
12893                        }
12894                    } catch(NumberFormatException e) {
12895                    }
12896                }
12897            }
12898        }
12899        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
12900        return prefix + idxStr;
12901    }
12902
12903    private File getNextCodePath(File targetDir, String packageName) {
12904        int suffix = 1;
12905        File result;
12906        do {
12907            result = new File(targetDir, packageName + "-" + suffix);
12908            suffix++;
12909        } while (result.exists());
12910        return result;
12911    }
12912
12913    // Utility method that returns the relative package path with respect
12914    // to the installation directory. Like say for /data/data/com.test-1.apk
12915    // string com.test-1 is returned.
12916    static String deriveCodePathName(String codePath) {
12917        if (codePath == null) {
12918            return null;
12919        }
12920        final File codeFile = new File(codePath);
12921        final String name = codeFile.getName();
12922        if (codeFile.isDirectory()) {
12923            return name;
12924        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
12925            final int lastDot = name.lastIndexOf('.');
12926            return name.substring(0, lastDot);
12927        } else {
12928            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
12929            return null;
12930        }
12931    }
12932
12933    static class PackageInstalledInfo {
12934        String name;
12935        int uid;
12936        // The set of users that originally had this package installed.
12937        int[] origUsers;
12938        // The set of users that now have this package installed.
12939        int[] newUsers;
12940        PackageParser.Package pkg;
12941        int returnCode;
12942        String returnMsg;
12943        PackageRemovedInfo removedInfo;
12944        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
12945
12946        public void setError(int code, String msg) {
12947            setReturnCode(code);
12948            setReturnMessage(msg);
12949            Slog.w(TAG, msg);
12950        }
12951
12952        public void setError(String msg, PackageParserException e) {
12953            setReturnCode(e.error);
12954            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12955            Slog.w(TAG, msg, e);
12956        }
12957
12958        public void setError(String msg, PackageManagerException e) {
12959            returnCode = e.error;
12960            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
12961            Slog.w(TAG, msg, e);
12962        }
12963
12964        public void setReturnCode(int returnCode) {
12965            this.returnCode = returnCode;
12966            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12967            for (int i = 0; i < childCount; i++) {
12968                addedChildPackages.valueAt(i).returnCode = returnCode;
12969            }
12970        }
12971
12972        private void setReturnMessage(String returnMsg) {
12973            this.returnMsg = returnMsg;
12974            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
12975            for (int i = 0; i < childCount; i++) {
12976                addedChildPackages.valueAt(i).returnMsg = returnMsg;
12977            }
12978        }
12979
12980        // In some error cases we want to convey more info back to the observer
12981        String origPackage;
12982        String origPermission;
12983    }
12984
12985    /*
12986     * Install a non-existing package.
12987     */
12988    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
12989            UserHandle user, String installerPackageName, String volumeUuid,
12990            PackageInstalledInfo res) {
12991        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
12992
12993        // Remember this for later, in case we need to rollback this install
12994        String pkgName = pkg.packageName;
12995
12996        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
12997
12998        synchronized(mPackages) {
12999            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13000                // A package with the same name is already installed, though
13001                // it has been renamed to an older name.  The package we
13002                // are trying to install should be installed as an update to
13003                // the existing one, but that has not been requested, so bail.
13004                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13005                        + " without first uninstalling package running as "
13006                        + mSettings.mRenamedPackages.get(pkgName));
13007                return;
13008            }
13009            if (mPackages.containsKey(pkgName)) {
13010                // Don't allow installation over an existing package with the same name.
13011                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13012                        + " without first uninstalling.");
13013                return;
13014            }
13015        }
13016
13017        try {
13018            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
13019                    System.currentTimeMillis(), user);
13020
13021            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13022
13023            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13024                prepareAppDataAfterInstall(newPackage);
13025
13026            } else {
13027                // Remove package from internal structures, but keep around any
13028                // data that might have already existed
13029                deletePackageLI(pkgName, UserHandle.ALL, false, null,
13030                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13031            }
13032        } catch (PackageManagerException e) {
13033            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13034        }
13035
13036        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13037    }
13038
13039    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13040        // Can't rotate keys during boot or if sharedUser.
13041        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13042                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13043            return false;
13044        }
13045        // app is using upgradeKeySets; make sure all are valid
13046        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13047        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13048        for (int i = 0; i < upgradeKeySets.length; i++) {
13049            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13050                Slog.wtf(TAG, "Package "
13051                         + (oldPs.name != null ? oldPs.name : "<null>")
13052                         + " contains upgrade-key-set reference to unknown key-set: "
13053                         + upgradeKeySets[i]
13054                         + " reverting to signatures check.");
13055                return false;
13056            }
13057        }
13058        return true;
13059    }
13060
13061    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13062        // Upgrade keysets are being used.  Determine if new package has a superset of the
13063        // required keys.
13064        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13065        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13066        for (int i = 0; i < upgradeKeySets.length; i++) {
13067            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13068            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13069                return true;
13070            }
13071        }
13072        return false;
13073    }
13074
13075    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
13076            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13077        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13078
13079        final PackageParser.Package oldPackage;
13080        final String pkgName = pkg.packageName;
13081        final int[] allUsers;
13082
13083        // First find the old package info and check signatures
13084        synchronized(mPackages) {
13085            oldPackage = mPackages.get(pkgName);
13086            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13087            if (isEphemeral && !oldIsEphemeral) {
13088                // can't downgrade from full to ephemeral
13089                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13090                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13091                return;
13092            }
13093            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13094            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13095            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13096                if (!checkUpgradeKeySetLP(ps, pkg)) {
13097                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13098                            "New package not signed by keys specified by upgrade-keysets: "
13099                                    + pkgName);
13100                    return;
13101                }
13102            } else {
13103                // default to original signature matching
13104                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13105                        != PackageManager.SIGNATURE_MATCH) {
13106                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13107                            "New package has a different signature: " + pkgName);
13108                    return;
13109                }
13110            }
13111
13112            // In case of rollback, remember per-user/profile install state
13113            allUsers = sUserManager.getUserIds();
13114        }
13115
13116        // Update what is removed
13117        res.removedInfo = new PackageRemovedInfo();
13118        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13119        res.removedInfo.removedPackage = oldPackage.packageName;
13120        res.removedInfo.isUpdate = true;
13121        final int childCount = (oldPackage.childPackages != null)
13122                ? oldPackage.childPackages.size() : 0;
13123        for (int i = 0; i < childCount; i++) {
13124            boolean childPackageUpdated = false;
13125            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13126            if (res.addedChildPackages != null) {
13127                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13128                if (childRes != null) {
13129                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13130                    childRes.removedInfo.removedPackage = childPkg.packageName;
13131                    childRes.removedInfo.isUpdate = true;
13132                    childPackageUpdated = true;
13133                }
13134            }
13135            if (!childPackageUpdated) {
13136                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13137                childRemovedRes.removedPackage = childPkg.packageName;
13138                childRemovedRes.isUpdate = false;
13139                childRemovedRes.dataRemoved = true;
13140                synchronized (mPackages) {
13141                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13142                    if (childPs != null) {
13143                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13144                    }
13145                }
13146                if (res.removedInfo.removedChildPackages == null) {
13147                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13148                }
13149                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13150            }
13151        }
13152
13153        boolean sysPkg = (isSystemApp(oldPackage));
13154        if (sysPkg) {
13155            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13156                    user, allUsers, installerPackageName, res);
13157        } else {
13158            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13159                    user, allUsers, installerPackageName, res);
13160        }
13161    }
13162
13163    public List<String> getPreviousCodePaths(String packageName) {
13164        final PackageSetting ps = mSettings.mPackages.get(packageName);
13165        final List<String> result = new ArrayList<String>();
13166        if (ps != null && ps.oldCodePaths != null) {
13167            result.addAll(ps.oldCodePaths);
13168        }
13169        return result;
13170    }
13171
13172    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
13173            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13174            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13175        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13176                + deletedPackage);
13177
13178        String pkgName = deletedPackage.packageName;
13179        boolean deletedPkg = true;
13180        boolean addedPkg = false;
13181        boolean updatedSettings = false;
13182        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13183        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13184                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13185
13186        final long origUpdateTime = (pkg.mExtras != null)
13187                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13188
13189        // First delete the existing package while retaining the data directory
13190        if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13191                res.removedInfo, true, pkg)) {
13192            // If the existing package wasn't successfully deleted
13193            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13194            deletedPkg = false;
13195        } else {
13196            // Successfully deleted the old package; proceed with replace.
13197
13198            // If deleted package lived in a container, give users a chance to
13199            // relinquish resources before killing.
13200            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13201                if (DEBUG_INSTALL) {
13202                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13203                }
13204                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13205                final ArrayList<String> pkgList = new ArrayList<String>(1);
13206                pkgList.add(deletedPackage.applicationInfo.packageName);
13207                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13208            }
13209
13210            deleteCodeCacheDirsLI(pkg);
13211
13212            try {
13213                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13214                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13215                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13216
13217                // Update the in-memory copy of the previous code paths.
13218                PackageSetting ps = mSettings.mPackages.get(pkgName);
13219                if (!killApp) {
13220                    if (ps.oldCodePaths == null) {
13221                        ps.oldCodePaths = new ArraySet<>();
13222                    }
13223                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13224                    if (deletedPackage.splitCodePaths != null) {
13225                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13226                    }
13227                } else {
13228                    ps.oldCodePaths = null;
13229                }
13230                if (ps.childPackageNames != null) {
13231                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13232                        final String childPkgName = ps.childPackageNames.get(i);
13233                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13234                        childPs.oldCodePaths = ps.oldCodePaths;
13235                    }
13236                }
13237                prepareAppDataAfterInstall(newPackage);
13238                addedPkg = true;
13239            } catch (PackageManagerException e) {
13240                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13241            }
13242        }
13243
13244        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13245            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13246
13247            // Revert all internal state mutations and added folders for the failed install
13248            if (addedPkg) {
13249                deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13250                        res.removedInfo, true, null);
13251            }
13252
13253            // Restore the old package
13254            if (deletedPkg) {
13255                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13256                File restoreFile = new File(deletedPackage.codePath);
13257                // Parse old package
13258                boolean oldExternal = isExternal(deletedPackage);
13259                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13260                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13261                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13262                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13263                try {
13264                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13265                            null);
13266                } catch (PackageManagerException e) {
13267                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13268                            + e.getMessage());
13269                    return;
13270                }
13271
13272                synchronized (mPackages) {
13273                    // Ensure the installer package name up to date
13274                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13275
13276                    // Update permissions for restored package
13277                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13278
13279                    mSettings.writeLPr();
13280                }
13281
13282                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13283            }
13284        } else {
13285            synchronized (mPackages) {
13286                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13287                if (ps != null) {
13288                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13289                    if (res.removedInfo.removedChildPackages != null) {
13290                        final int childCount = res.removedInfo.removedChildPackages.size();
13291                        // Iterate in reverse as we may modify the collection
13292                        for (int i = childCount - 1; i >= 0; i--) {
13293                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13294                            if (res.addedChildPackages.containsKey(childPackageName)) {
13295                                res.removedInfo.removedChildPackages.removeAt(i);
13296                            } else {
13297                                PackageRemovedInfo childInfo = res.removedInfo
13298                                        .removedChildPackages.valueAt(i);
13299                                childInfo.removedForAllUsers = mPackages.get(
13300                                        childInfo.removedPackage) == null;
13301                            }
13302                        }
13303                    }
13304                }
13305            }
13306        }
13307    }
13308
13309    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
13310            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13311            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13312        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13313                + ", old=" + deletedPackage);
13314
13315        final boolean disabledSystem;
13316
13317        // Set the system/privileged flags as needed
13318        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13319        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13320                != 0) {
13321            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13322        }
13323
13324        // Kill package processes including services, providers, etc.
13325        killPackage(deletedPackage, "replace sys pkg");
13326
13327        // Remove existing system package
13328        removePackageLI(deletedPackage, true);
13329
13330        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13331        if (!disabledSystem) {
13332            // We didn't need to disable the .apk as a current system package,
13333            // which means we are replacing another update that is already
13334            // installed.  We need to make sure to delete the older one's .apk.
13335            res.removedInfo.args = createInstallArgsForExisting(0,
13336                    deletedPackage.applicationInfo.getCodePath(),
13337                    deletedPackage.applicationInfo.getResourcePath(),
13338                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13339        } else {
13340            res.removedInfo.args = null;
13341        }
13342
13343        // Successfully disabled the old package. Now proceed with re-installation
13344        deleteCodeCacheDirsLI(pkg);
13345
13346        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13347        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13348                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13349
13350        PackageParser.Package newPackage = null;
13351        try {
13352            // Add the package to the internal data structures
13353            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13354
13355            // Set the update and install times
13356            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13357            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13358                    System.currentTimeMillis());
13359
13360            // Check for shared user id changes
13361            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13362                    deletedPackage, newPackage);
13363            if (invalidPackageName != null) {
13364                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13365                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13366                                + " to " + invalidPackageName);
13367            }
13368
13369            // Update the package dynamic state if succeeded
13370            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13371                // Now that the install succeeded make sure we remove data
13372                // directories for any child package the update removed.
13373                final int deletedChildCount = (deletedPackage.childPackages != null)
13374                        ? deletedPackage.childPackages.size() : 0;
13375                final int newChildCount = (newPackage.childPackages != null)
13376                        ? newPackage.childPackages.size() : 0;
13377                for (int i = 0; i < deletedChildCount; i++) {
13378                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13379                    boolean childPackageDeleted = true;
13380                    for (int j = 0; j < newChildCount; j++) {
13381                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13382                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13383                            childPackageDeleted = false;
13384                            break;
13385                        }
13386                    }
13387                    if (childPackageDeleted) {
13388                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13389                                deletedChildPkg.packageName);
13390                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13391                            PackageRemovedInfo removedChildRes = res.removedInfo
13392                                    .removedChildPackages.get(deletedChildPkg.packageName);
13393                            removePackageDataLI(ps, allUsers, removedChildRes, 0, false);
13394                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13395                        }
13396                    }
13397                }
13398
13399                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13400                prepareAppDataAfterInstall(newPackage);
13401            }
13402        } catch (PackageManagerException e) {
13403            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13404            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13405        }
13406
13407        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13408            // Re installation failed. Restore old information
13409            // Remove new pkg information
13410            if (newPackage != null) {
13411                removeInstalledPackageLI(newPackage, true);
13412            }
13413            // Add back the old system package
13414            try {
13415                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13416            } catch (PackageManagerException e) {
13417                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13418            }
13419
13420            synchronized (mPackages) {
13421                if (disabledSystem) {
13422                    enableSystemPackageLPw(deletedPackage);
13423                }
13424
13425                // Ensure the installer package name up to date
13426                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13427
13428                // Update permissions for restored package
13429                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13430
13431                mSettings.writeLPr();
13432            }
13433
13434            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13435                    + " after failed upgrade");
13436        }
13437    }
13438
13439    /**
13440     * Checks whether the parent or any of the child packages have a change shared
13441     * user. For a package to be a valid update the shred users of the parent and
13442     * the children should match. We may later support changing child shared users.
13443     * @param oldPkg The updated package.
13444     * @param newPkg The update package.
13445     * @return The shared user that change between the versions.
13446     */
13447    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13448            PackageParser.Package newPkg) {
13449        // Check parent shared user
13450        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13451            return newPkg.packageName;
13452        }
13453        // Check child shared users
13454        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13455        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13456        for (int i = 0; i < newChildCount; i++) {
13457            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13458            // If this child was present, did it have the same shared user?
13459            for (int j = 0; j < oldChildCount; j++) {
13460                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13461                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13462                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13463                    return newChildPkg.packageName;
13464                }
13465            }
13466        }
13467        return null;
13468    }
13469
13470    private void removeNativeBinariesLI(PackageSetting ps) {
13471        // Remove the lib path for the parent package
13472        if (ps != null) {
13473            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13474            // Remove the lib path for the child packages
13475            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
13476            for (int i = 0; i < childCount; i++) {
13477                PackageSetting childPs = null;
13478                synchronized (mPackages) {
13479                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
13480                }
13481                if (childPs != null) {
13482                    NativeLibraryHelper.removeNativeBinariesLI(childPs
13483                            .legacyNativeLibraryPathString);
13484                }
13485            }
13486        }
13487    }
13488
13489    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13490        // Enable the parent package
13491        mSettings.enableSystemPackageLPw(pkg.packageName);
13492        // Enable the child packages
13493        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13494        for (int i = 0; i < childCount; i++) {
13495            PackageParser.Package childPkg = pkg.childPackages.get(i);
13496            mSettings.enableSystemPackageLPw(childPkg.packageName);
13497        }
13498    }
13499
13500    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13501            PackageParser.Package newPkg) {
13502        // Disable the parent package (parent always replaced)
13503        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13504        // Disable the child packages
13505        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13506        for (int i = 0; i < childCount; i++) {
13507            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13508            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13509            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13510        }
13511        return disabled;
13512    }
13513
13514    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13515            String installerPackageName) {
13516        // Enable the parent package
13517        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13518        // Enable the child packages
13519        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13520        for (int i = 0; i < childCount; i++) {
13521            PackageParser.Package childPkg = pkg.childPackages.get(i);
13522            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13523        }
13524    }
13525
13526    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
13527        // Collect all used permissions in the UID
13528        ArraySet<String> usedPermissions = new ArraySet<>();
13529        final int packageCount = su.packages.size();
13530        for (int i = 0; i < packageCount; i++) {
13531            PackageSetting ps = su.packages.valueAt(i);
13532            if (ps.pkg == null) {
13533                continue;
13534            }
13535            final int requestedPermCount = ps.pkg.requestedPermissions.size();
13536            for (int j = 0; j < requestedPermCount; j++) {
13537                String permission = ps.pkg.requestedPermissions.get(j);
13538                BasePermission bp = mSettings.mPermissions.get(permission);
13539                if (bp != null) {
13540                    usedPermissions.add(permission);
13541                }
13542            }
13543        }
13544
13545        PermissionsState permissionsState = su.getPermissionsState();
13546        // Prune install permissions
13547        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
13548        final int installPermCount = installPermStates.size();
13549        for (int i = installPermCount - 1; i >= 0;  i--) {
13550            PermissionState permissionState = installPermStates.get(i);
13551            if (!usedPermissions.contains(permissionState.getName())) {
13552                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13553                if (bp != null) {
13554                    permissionsState.revokeInstallPermission(bp);
13555                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
13556                            PackageManager.MASK_PERMISSION_FLAGS, 0);
13557                }
13558            }
13559        }
13560
13561        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
13562
13563        // Prune runtime permissions
13564        for (int userId : allUserIds) {
13565            List<PermissionState> runtimePermStates = permissionsState
13566                    .getRuntimePermissionStates(userId);
13567            final int runtimePermCount = runtimePermStates.size();
13568            for (int i = runtimePermCount - 1; i >= 0; i--) {
13569                PermissionState permissionState = runtimePermStates.get(i);
13570                if (!usedPermissions.contains(permissionState.getName())) {
13571                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
13572                    if (bp != null) {
13573                        permissionsState.revokeRuntimePermission(bp, userId);
13574                        permissionsState.updatePermissionFlags(bp, userId,
13575                                PackageManager.MASK_PERMISSION_FLAGS, 0);
13576                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
13577                                runtimePermissionChangedUserIds, userId);
13578                    }
13579                }
13580            }
13581        }
13582
13583        return runtimePermissionChangedUserIds;
13584    }
13585
13586    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
13587            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
13588        // Update the parent package setting
13589        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
13590                res, user);
13591        // Update the child packages setting
13592        final int childCount = (newPackage.childPackages != null)
13593                ? newPackage.childPackages.size() : 0;
13594        for (int i = 0; i < childCount; i++) {
13595            PackageParser.Package childPackage = newPackage.childPackages.get(i);
13596            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
13597            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
13598                    childRes.origUsers, childRes, user);
13599        }
13600    }
13601
13602    private void updateSettingsInternalLI(PackageParser.Package newPackage,
13603            String installerPackageName, int[] allUsers, int[] installedForUsers,
13604            PackageInstalledInfo res, UserHandle user) {
13605        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
13606
13607        String pkgName = newPackage.packageName;
13608        synchronized (mPackages) {
13609            //write settings. the installStatus will be incomplete at this stage.
13610            //note that the new package setting would have already been
13611            //added to mPackages. It hasn't been persisted yet.
13612            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
13613            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13614            mSettings.writeLPr();
13615            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13616        }
13617
13618        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
13619        synchronized (mPackages) {
13620            updatePermissionsLPw(newPackage.packageName, newPackage,
13621                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
13622                            ? UPDATE_PERMISSIONS_ALL : 0));
13623            // For system-bundled packages, we assume that installing an upgraded version
13624            // of the package implies that the user actually wants to run that new code,
13625            // so we enable the package.
13626            PackageSetting ps = mSettings.mPackages.get(pkgName);
13627            final int userId = user.getIdentifier();
13628            if (ps != null) {
13629                if (isSystemApp(newPackage)) {
13630                    if (DEBUG_INSTALL) {
13631                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
13632                    }
13633                    // Enable system package for requested users
13634                    if (res.origUsers != null) {
13635                        for (int origUserId : res.origUsers) {
13636                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
13637                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
13638                                        origUserId, installerPackageName);
13639                            }
13640                        }
13641                    }
13642                    // Also convey the prior install/uninstall state
13643                    if (allUsers != null && installedForUsers != null) {
13644                        for (int currentUserId : allUsers) {
13645                            final boolean installed = ArrayUtils.contains(
13646                                    installedForUsers, currentUserId);
13647                            if (DEBUG_INSTALL) {
13648                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
13649                            }
13650                            ps.setInstalled(installed, currentUserId);
13651                        }
13652                        // these install state changes will be persisted in the
13653                        // upcoming call to mSettings.writeLPr().
13654                    }
13655                }
13656                // It's implied that when a user requests installation, they want the app to be
13657                // installed and enabled.
13658                if (userId != UserHandle.USER_ALL) {
13659                    ps.setInstalled(true, userId);
13660                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
13661                }
13662            }
13663            res.name = pkgName;
13664            res.uid = newPackage.applicationInfo.uid;
13665            res.pkg = newPackage;
13666            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
13667            mSettings.setInstallerPackageName(pkgName, installerPackageName);
13668            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13669            //to update install status
13670            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
13671            mSettings.writeLPr();
13672            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13673        }
13674
13675        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13676    }
13677
13678    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
13679        try {
13680            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
13681            installPackageLI(args, res);
13682        } finally {
13683            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13684        }
13685    }
13686
13687    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
13688        final int installFlags = args.installFlags;
13689        final String installerPackageName = args.installerPackageName;
13690        final String volumeUuid = args.volumeUuid;
13691        final File tmpPackageFile = new File(args.getCodePath());
13692        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
13693        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
13694                || (args.volumeUuid != null));
13695        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
13696        boolean replace = false;
13697        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
13698        if (args.move != null) {
13699            // moving a complete application; perform an initial scan on the new install location
13700            scanFlags |= SCAN_INITIAL;
13701        }
13702        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
13703            scanFlags |= SCAN_DONT_KILL_APP;
13704        }
13705
13706        // Result object to be returned
13707        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13708
13709        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
13710
13711        // Sanity check
13712        if (ephemeral && (forwardLocked || onExternal)) {
13713            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
13714                    + " external=" + onExternal);
13715            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13716            return;
13717        }
13718
13719        // Retrieve PackageSettings and parse package
13720        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
13721                | PackageParser.PARSE_ENFORCE_CODE
13722                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
13723                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
13724                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
13725        PackageParser pp = new PackageParser();
13726        pp.setSeparateProcesses(mSeparateProcesses);
13727        pp.setDisplayMetrics(mMetrics);
13728
13729        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
13730        final PackageParser.Package pkg;
13731        try {
13732            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
13733        } catch (PackageParserException e) {
13734            res.setError("Failed parse during installPackageLI", e);
13735            return;
13736        } finally {
13737            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13738        }
13739
13740        // If we are installing a clustered package add results for the children
13741        if (pkg.childPackages != null) {
13742            synchronized (mPackages) {
13743                final int childCount = pkg.childPackages.size();
13744                for (int i = 0; i < childCount; i++) {
13745                    PackageParser.Package childPkg = pkg.childPackages.get(i);
13746                    PackageInstalledInfo childRes = new PackageInstalledInfo();
13747                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13748                    childRes.pkg = childPkg;
13749                    childRes.name = childPkg.packageName;
13750                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13751                    if (childPs != null) {
13752                        childRes.origUsers = childPs.queryInstalledUsers(
13753                                sUserManager.getUserIds(), true);
13754                    }
13755                    if ((mPackages.containsKey(childPkg.packageName))) {
13756                        childRes.removedInfo = new PackageRemovedInfo();
13757                        childRes.removedInfo.removedPackage = childPkg.packageName;
13758                    }
13759                    if (res.addedChildPackages == null) {
13760                        res.addedChildPackages = new ArrayMap<>();
13761                    }
13762                    res.addedChildPackages.put(childPkg.packageName, childRes);
13763                }
13764            }
13765        }
13766
13767        // If package doesn't declare API override, mark that we have an install
13768        // time CPU ABI override.
13769        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
13770            pkg.cpuAbiOverride = args.abiOverride;
13771        }
13772
13773        String pkgName = res.name = pkg.packageName;
13774        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
13775            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
13776                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
13777                return;
13778            }
13779        }
13780
13781        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
13782        try {
13783            PackageParser.collectCertificates(pkg, parseFlags);
13784        } catch (PackageParserException e) {
13785            res.setError("Failed collect during installPackageLI", e);
13786            return;
13787        } finally {
13788            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13789        }
13790
13791        // Get rid of all references to package scan path via parser.
13792        pp = null;
13793        String oldCodePath = null;
13794        boolean systemApp = false;
13795        synchronized (mPackages) {
13796            // Check if installing already existing package
13797            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
13798                String oldName = mSettings.mRenamedPackages.get(pkgName);
13799                if (pkg.mOriginalPackages != null
13800                        && pkg.mOriginalPackages.contains(oldName)
13801                        && mPackages.containsKey(oldName)) {
13802                    // This package is derived from an original package,
13803                    // and this device has been updating from that original
13804                    // name.  We must continue using the original name, so
13805                    // rename the new package here.
13806                    pkg.setPackageName(oldName);
13807                    pkgName = pkg.packageName;
13808                    replace = true;
13809                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
13810                            + oldName + " pkgName=" + pkgName);
13811                } else if (mPackages.containsKey(pkgName)) {
13812                    // This package, under its official name, already exists
13813                    // on the device; we should replace it.
13814                    replace = true;
13815                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
13816                }
13817
13818                // Child packages are installed through the parent package
13819                if (pkg.parentPackage != null) {
13820                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13821                            "Package " + pkg.packageName + " is child of package "
13822                                    + pkg.parentPackage.parentPackage + ". Child packages "
13823                                    + "can be updated only through the parent package.");
13824                    return;
13825                }
13826
13827                if (replace) {
13828                    // Prevent apps opting out from runtime permissions
13829                    PackageParser.Package oldPackage = mPackages.get(pkgName);
13830                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
13831                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
13832                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
13833                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
13834                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
13835                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
13836                                        + " doesn't support runtime permissions but the old"
13837                                        + " target SDK " + oldTargetSdk + " does.");
13838                        return;
13839                    }
13840
13841                    // Prevent installing of child packages
13842                    if (oldPackage.parentPackage != null) {
13843                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
13844                                "Package " + pkg.packageName + " is child of package "
13845                                        + oldPackage.parentPackage + ". Child packages "
13846                                        + "can be updated only through the parent package.");
13847                        return;
13848                    }
13849                }
13850            }
13851
13852            PackageSetting ps = mSettings.mPackages.get(pkgName);
13853            if (ps != null) {
13854                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
13855
13856                // Quick sanity check that we're signed correctly if updating;
13857                // we'll check this again later when scanning, but we want to
13858                // bail early here before tripping over redefined permissions.
13859                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13860                    if (!checkUpgradeKeySetLP(ps, pkg)) {
13861                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
13862                                + pkg.packageName + " upgrade keys do not match the "
13863                                + "previously installed version");
13864                        return;
13865                    }
13866                } else {
13867                    try {
13868                        verifySignaturesLP(ps, pkg);
13869                    } catch (PackageManagerException e) {
13870                        res.setError(e.error, e.getMessage());
13871                        return;
13872                    }
13873                }
13874
13875                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
13876                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
13877                    systemApp = (ps.pkg.applicationInfo.flags &
13878                            ApplicationInfo.FLAG_SYSTEM) != 0;
13879                }
13880                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
13881            }
13882
13883            // Check whether the newly-scanned package wants to define an already-defined perm
13884            int N = pkg.permissions.size();
13885            for (int i = N-1; i >= 0; i--) {
13886                PackageParser.Permission perm = pkg.permissions.get(i);
13887                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
13888                if (bp != null) {
13889                    // If the defining package is signed with our cert, it's okay.  This
13890                    // also includes the "updating the same package" case, of course.
13891                    // "updating same package" could also involve key-rotation.
13892                    final boolean sigsOk;
13893                    if (bp.sourcePackage.equals(pkg.packageName)
13894                            && (bp.packageSetting instanceof PackageSetting)
13895                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
13896                                    scanFlags))) {
13897                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
13898                    } else {
13899                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
13900                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
13901                    }
13902                    if (!sigsOk) {
13903                        // If the owning package is the system itself, we log but allow
13904                        // install to proceed; we fail the install on all other permission
13905                        // redefinitions.
13906                        if (!bp.sourcePackage.equals("android")) {
13907                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
13908                                    + pkg.packageName + " attempting to redeclare permission "
13909                                    + perm.info.name + " already owned by " + bp.sourcePackage);
13910                            res.origPermission = perm.info.name;
13911                            res.origPackage = bp.sourcePackage;
13912                            return;
13913                        } else {
13914                            Slog.w(TAG, "Package " + pkg.packageName
13915                                    + " attempting to redeclare system permission "
13916                                    + perm.info.name + "; ignoring new declaration");
13917                            pkg.permissions.remove(i);
13918                        }
13919                    }
13920                }
13921            }
13922        }
13923
13924        if (systemApp) {
13925            if (onExternal) {
13926                // Abort update; system app can't be replaced with app on sdcard
13927                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
13928                        "Cannot install updates to system apps on sdcard");
13929                return;
13930            } else if (ephemeral) {
13931                // Abort update; system app can't be replaced with an ephemeral app
13932                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
13933                        "Cannot update a system app with an ephemeral app");
13934                return;
13935            }
13936        }
13937
13938        if (args.move != null) {
13939            // We did an in-place move, so dex is ready to roll
13940            scanFlags |= SCAN_NO_DEX;
13941            scanFlags |= SCAN_MOVE;
13942
13943            synchronized (mPackages) {
13944                final PackageSetting ps = mSettings.mPackages.get(pkgName);
13945                if (ps == null) {
13946                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
13947                            "Missing settings for moved package " + pkgName);
13948                }
13949
13950                // We moved the entire application as-is, so bring over the
13951                // previously derived ABI information.
13952                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
13953                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
13954            }
13955
13956        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
13957            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
13958            scanFlags |= SCAN_NO_DEX;
13959
13960            try {
13961                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
13962                    args.abiOverride : pkg.cpuAbiOverride);
13963                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
13964                        true /* extract libs */);
13965            } catch (PackageManagerException pme) {
13966                Slog.e(TAG, "Error deriving application ABI", pme);
13967                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
13968                return;
13969            }
13970
13971
13972            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
13973            // Do not run PackageDexOptimizer through the local performDexOpt
13974            // method because `pkg` is not in `mPackages` yet.
13975            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
13976                    false /* useProfiles */, true /* extractOnly */);
13977            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13978            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
13979                String msg = "Extracking package failed for " + pkgName;
13980                res.setError(INSTALL_FAILED_DEXOPT, msg);
13981                return;
13982            }
13983        }
13984
13985        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
13986            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
13987            return;
13988        }
13989
13990        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
13991
13992        if (replace) {
13993            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
13994                    installerPackageName, res);
13995        } else {
13996            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
13997                    args.user, installerPackageName, volumeUuid, res);
13998        }
13999        synchronized (mPackages) {
14000            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14001            if (ps != null) {
14002                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14003            }
14004
14005            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14006            for (int i = 0; i < childCount; i++) {
14007                PackageParser.Package childPkg = pkg.childPackages.get(i);
14008                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14009                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14010                if (childPs != null) {
14011                    childRes.newUsers = childPs.queryInstalledUsers(
14012                            sUserManager.getUserIds(), true);
14013                }
14014            }
14015        }
14016    }
14017
14018    private void startIntentFilterVerifications(int userId, boolean replacing,
14019            PackageParser.Package pkg) {
14020        if (mIntentFilterVerifierComponent == null) {
14021            Slog.w(TAG, "No IntentFilter verification will not be done as "
14022                    + "there is no IntentFilterVerifier available!");
14023            return;
14024        }
14025
14026        final int verifierUid = getPackageUid(
14027                mIntentFilterVerifierComponent.getPackageName(),
14028                MATCH_DEBUG_TRIAGED_MISSING,
14029                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14030
14031        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14032        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14033        mHandler.sendMessage(msg);
14034
14035        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14036        for (int i = 0; i < childCount; i++) {
14037            PackageParser.Package childPkg = pkg.childPackages.get(i);
14038            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14039            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14040            mHandler.sendMessage(msg);
14041        }
14042    }
14043
14044    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14045            PackageParser.Package pkg) {
14046        int size = pkg.activities.size();
14047        if (size == 0) {
14048            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14049                    "No activity, so no need to verify any IntentFilter!");
14050            return;
14051        }
14052
14053        final boolean hasDomainURLs = hasDomainURLs(pkg);
14054        if (!hasDomainURLs) {
14055            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14056                    "No domain URLs, so no need to verify any IntentFilter!");
14057            return;
14058        }
14059
14060        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14061                + " if any IntentFilter from the " + size
14062                + " Activities needs verification ...");
14063
14064        int count = 0;
14065        final String packageName = pkg.packageName;
14066
14067        synchronized (mPackages) {
14068            // If this is a new install and we see that we've already run verification for this
14069            // package, we have nothing to do: it means the state was restored from backup.
14070            if (!replacing) {
14071                IntentFilterVerificationInfo ivi =
14072                        mSettings.getIntentFilterVerificationLPr(packageName);
14073                if (ivi != null) {
14074                    if (DEBUG_DOMAIN_VERIFICATION) {
14075                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14076                                + ivi.getStatusString());
14077                    }
14078                    return;
14079                }
14080            }
14081
14082            // If any filters need to be verified, then all need to be.
14083            boolean needToVerify = false;
14084            for (PackageParser.Activity a : pkg.activities) {
14085                for (ActivityIntentInfo filter : a.intents) {
14086                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14087                        if (DEBUG_DOMAIN_VERIFICATION) {
14088                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14089                        }
14090                        needToVerify = true;
14091                        break;
14092                    }
14093                }
14094            }
14095
14096            if (needToVerify) {
14097                final int verificationId = mIntentFilterVerificationToken++;
14098                for (PackageParser.Activity a : pkg.activities) {
14099                    for (ActivityIntentInfo filter : a.intents) {
14100                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14101                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14102                                    "Verification needed for IntentFilter:" + filter.toString());
14103                            mIntentFilterVerifier.addOneIntentFilterVerification(
14104                                    verifierUid, userId, verificationId, filter, packageName);
14105                            count++;
14106                        }
14107                    }
14108                }
14109            }
14110        }
14111
14112        if (count > 0) {
14113            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14114                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14115                    +  " for userId:" + userId);
14116            mIntentFilterVerifier.startVerifications(userId);
14117        } else {
14118            if (DEBUG_DOMAIN_VERIFICATION) {
14119                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14120            }
14121        }
14122    }
14123
14124    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14125        final ComponentName cn  = filter.activity.getComponentName();
14126        final String packageName = cn.getPackageName();
14127
14128        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14129                packageName);
14130        if (ivi == null) {
14131            return true;
14132        }
14133        int status = ivi.getStatus();
14134        switch (status) {
14135            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14136            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14137                return true;
14138
14139            default:
14140                // Nothing to do
14141                return false;
14142        }
14143    }
14144
14145    private static boolean isMultiArch(ApplicationInfo info) {
14146        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14147    }
14148
14149    private static boolean isExternal(PackageParser.Package pkg) {
14150        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14151    }
14152
14153    private static boolean isExternal(PackageSetting ps) {
14154        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14155    }
14156
14157    private static boolean isEphemeral(PackageParser.Package pkg) {
14158        return pkg.applicationInfo.isEphemeralApp();
14159    }
14160
14161    private static boolean isEphemeral(PackageSetting ps) {
14162        return ps.pkg != null && isEphemeral(ps.pkg);
14163    }
14164
14165    private static boolean isSystemApp(PackageParser.Package pkg) {
14166        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14167    }
14168
14169    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14170        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14171    }
14172
14173    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14174        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14175    }
14176
14177    private static boolean isSystemApp(PackageSetting ps) {
14178        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14179    }
14180
14181    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14182        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14183    }
14184
14185    private int packageFlagsToInstallFlags(PackageSetting ps) {
14186        int installFlags = 0;
14187        if (isEphemeral(ps)) {
14188            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14189        }
14190        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14191            // This existing package was an external ASEC install when we have
14192            // the external flag without a UUID
14193            installFlags |= PackageManager.INSTALL_EXTERNAL;
14194        }
14195        if (ps.isForwardLocked()) {
14196            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14197        }
14198        return installFlags;
14199    }
14200
14201    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14202        if (isExternal(pkg)) {
14203            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14204                return StorageManager.UUID_PRIMARY_PHYSICAL;
14205            } else {
14206                return pkg.volumeUuid;
14207            }
14208        } else {
14209            return StorageManager.UUID_PRIVATE_INTERNAL;
14210        }
14211    }
14212
14213    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14214        if (isExternal(pkg)) {
14215            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14216                return mSettings.getExternalVersion();
14217            } else {
14218                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14219            }
14220        } else {
14221            return mSettings.getInternalVersion();
14222        }
14223    }
14224
14225    private void deleteTempPackageFiles() {
14226        final FilenameFilter filter = new FilenameFilter() {
14227            public boolean accept(File dir, String name) {
14228                return name.startsWith("vmdl") && name.endsWith(".tmp");
14229            }
14230        };
14231        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14232            file.delete();
14233        }
14234    }
14235
14236    @Override
14237    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14238            int flags) {
14239        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14240                flags);
14241    }
14242
14243    @Override
14244    public void deletePackage(final String packageName,
14245            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
14246        mContext.enforceCallingOrSelfPermission(
14247                android.Manifest.permission.DELETE_PACKAGES, null);
14248        Preconditions.checkNotNull(packageName);
14249        Preconditions.checkNotNull(observer);
14250        final int uid = Binder.getCallingUid();
14251        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
14252        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14253        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14254            mContext.enforceCallingOrSelfPermission(
14255                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14256                    "deletePackage for user " + userId);
14257        }
14258
14259        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14260            try {
14261                observer.onPackageDeleted(packageName,
14262                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14263            } catch (RemoteException re) {
14264            }
14265            return;
14266        }
14267
14268        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
14269            try {
14270                observer.onPackageDeleted(packageName,
14271                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14272            } catch (RemoteException re) {
14273            }
14274            return;
14275        }
14276
14277        if (DEBUG_REMOVE) {
14278            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
14279                    + " deleteAllUsers: " + deleteAllUsers );
14280        }
14281        // Queue up an async operation since the package deletion may take a little while.
14282        mHandler.post(new Runnable() {
14283            public void run() {
14284                mHandler.removeCallbacks(this);
14285                int returnCode;
14286                if (!deleteAllUsers) {
14287                    returnCode = deletePackageX(packageName, userId, flags);
14288                } else {
14289                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
14290                    // If nobody is blocking uninstall, proceed with delete for all users
14291                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
14292                        returnCode = deletePackageX(packageName, userId, flags);
14293                    } else {
14294                        // Otherwise uninstall individually for users with blockUninstalls=false
14295                        final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS;
14296                        for (int userId : users) {
14297                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
14298                                returnCode = deletePackageX(packageName, userId, userFlags);
14299                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
14300                                    Slog.w(TAG, "Package delete failed for user " + userId
14301                                            + ", returnCode " + returnCode);
14302                                }
14303                            }
14304                        }
14305                        // The app has only been marked uninstalled for certain users.
14306                        // We still need to report that delete was blocked
14307                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
14308                    }
14309                }
14310                try {
14311                    observer.onPackageDeleted(packageName, returnCode, null);
14312                } catch (RemoteException e) {
14313                    Log.i(TAG, "Observer no longer exists.");
14314                } //end catch
14315            } //end run
14316        });
14317    }
14318
14319    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
14320        int[] result = EMPTY_INT_ARRAY;
14321        for (int userId : userIds) {
14322            if (getBlockUninstallForUser(packageName, userId)) {
14323                result = ArrayUtils.appendInt(result, userId);
14324            }
14325        }
14326        return result;
14327    }
14328
14329    @Override
14330    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14331        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14332    }
14333
14334    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14335        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14336                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14337        try {
14338            if (dpm != null) {
14339                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14340                        /* callingUserOnly =*/ false);
14341                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14342                        : deviceOwnerComponentName.getPackageName();
14343                // Does the package contains the device owner?
14344                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14345                // this check is probably not needed, since DO should be registered as a device
14346                // admin on some user too. (Original bug for this: b/17657954)
14347                if (packageName.equals(deviceOwnerPackageName)) {
14348                    return true;
14349                }
14350                // Does it contain a device admin for any user?
14351                int[] users;
14352                if (userId == UserHandle.USER_ALL) {
14353                    users = sUserManager.getUserIds();
14354                } else {
14355                    users = new int[]{userId};
14356                }
14357                for (int i = 0; i < users.length; ++i) {
14358                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14359                        return true;
14360                    }
14361                }
14362            }
14363        } catch (RemoteException e) {
14364        }
14365        return false;
14366    }
14367
14368    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14369        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14370    }
14371
14372    /**
14373     *  This method is an internal method that could be get invoked either
14374     *  to delete an installed package or to clean up a failed installation.
14375     *  After deleting an installed package, a broadcast is sent to notify any
14376     *  listeners that the package has been installed. For cleaning up a failed
14377     *  installation, the broadcast is not necessary since the package's
14378     *  installation wouldn't have sent the initial broadcast either
14379     *  The key steps in deleting a package are
14380     *  deleting the package information in internal structures like mPackages,
14381     *  deleting the packages base directories through installd
14382     *  updating mSettings to reflect current status
14383     *  persisting settings for later use
14384     *  sending a broadcast if necessary
14385     */
14386    private int deletePackageX(String packageName, int userId, int flags) {
14387        final PackageRemovedInfo info = new PackageRemovedInfo();
14388        final boolean res;
14389
14390        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
14391                ? UserHandle.ALL : new UserHandle(userId);
14392
14393        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14394            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14395            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14396        }
14397
14398        PackageSetting uninstalledPs = null;
14399
14400        // for the uninstall-updates case and restricted profiles, remember the per-
14401        // user handle installed state
14402        int[] allUsers;
14403        synchronized (mPackages) {
14404            uninstalledPs = mSettings.mPackages.get(packageName);
14405            if (uninstalledPs == null) {
14406                Slog.w(TAG, "Not removing non-existent package " + packageName);
14407                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14408            }
14409            allUsers = sUserManager.getUserIds();
14410            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14411        }
14412
14413        synchronized (mInstallLock) {
14414            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14415            res = deletePackageLI(packageName, removeForUser, true, allUsers,
14416                    flags | REMOVE_CHATTY, info, true, null);
14417            synchronized (mPackages) {
14418                if (res) {
14419                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14420                }
14421            }
14422        }
14423
14424        if (res) {
14425            final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0;
14426            info.sendPackageRemovedBroadcasts(killApp);
14427            info.sendSystemPackageUpdatedBroadcasts();
14428            info.sendSystemPackageAppearedBroadcasts();
14429        }
14430        // Force a gc here.
14431        Runtime.getRuntime().gc();
14432        // Delete the resources here after sending the broadcast to let
14433        // other processes clean up before deleting resources.
14434        if (info.args != null) {
14435            synchronized (mInstallLock) {
14436                info.args.doPostDeleteLI(true);
14437            }
14438        }
14439
14440        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14441    }
14442
14443    class PackageRemovedInfo {
14444        String removedPackage;
14445        int uid = -1;
14446        int removedAppId = -1;
14447        int[] origUsers;
14448        int[] removedUsers = null;
14449        boolean isRemovedPackageSystemUpdate = false;
14450        boolean isUpdate;
14451        boolean dataRemoved;
14452        boolean removedForAllUsers;
14453        // Clean up resources deleted packages.
14454        InstallArgs args = null;
14455        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
14456        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
14457
14458        void sendPackageRemovedBroadcasts(boolean killApp) {
14459            sendPackageRemovedBroadcastInternal(killApp);
14460            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
14461            for (int i = 0; i < childCount; i++) {
14462                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14463                childInfo.sendPackageRemovedBroadcastInternal(killApp);
14464            }
14465        }
14466
14467        void sendSystemPackageUpdatedBroadcasts() {
14468            if (isRemovedPackageSystemUpdate) {
14469                sendSystemPackageUpdatedBroadcastsInternal();
14470                final int childCount = (removedChildPackages != null)
14471                        ? removedChildPackages.size() : 0;
14472                for (int i = 0; i < childCount; i++) {
14473                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14474                    if (childInfo.isRemovedPackageSystemUpdate) {
14475                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
14476                    }
14477                }
14478            }
14479        }
14480
14481        void sendSystemPackageAppearedBroadcasts() {
14482            final int packageCount = (appearedChildPackages != null)
14483                    ? appearedChildPackages.size() : 0;
14484            for (int i = 0; i < packageCount; i++) {
14485                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
14486                for (int userId : installedInfo.newUsers) {
14487                    sendPackageAddedForUser(installedInfo.name, true,
14488                            UserHandle.getAppId(installedInfo.uid), userId);
14489                }
14490            }
14491        }
14492
14493        private void sendSystemPackageUpdatedBroadcastsInternal() {
14494            Bundle extras = new Bundle(2);
14495            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14496            extras.putBoolean(Intent.EXTRA_REPLACING, true);
14497            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
14498                    extras, 0, null, null, null);
14499            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
14500                    extras, 0, null, null, null);
14501            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14502                    null, 0, removedPackage, null, null);
14503        }
14504
14505        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
14506            Bundle extras = new Bundle(2);
14507            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
14508            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
14509            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
14510            if (isUpdate || isRemovedPackageSystemUpdate) {
14511                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14512            }
14513            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14514            if (removedPackage != null) {
14515                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14516                        extras, 0, null, null, removedUsers);
14517                if (dataRemoved && !isRemovedPackageSystemUpdate) {
14518                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
14519                            removedPackage, extras, 0, null, null, removedUsers);
14520                }
14521            }
14522            if (removedAppId >= 0) {
14523                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14524                        removedUsers);
14525            }
14526        }
14527    }
14528
14529    /*
14530     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
14531     * flag is not set, the data directory is removed as well.
14532     * make sure this flag is set for partially installed apps. If not its meaningless to
14533     * delete a partially installed application.
14534     */
14535    private void removePackageDataLI(PackageSetting ps, int[] allUserHandles,
14536            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
14537        String packageName = ps.name;
14538        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
14539        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
14540        // Retrieve object to delete permissions for shared user later on
14541        final PackageSetting deletedPs;
14542        // reader
14543        synchronized (mPackages) {
14544            deletedPs = mSettings.mPackages.get(packageName);
14545            if (outInfo != null) {
14546                outInfo.removedPackage = packageName;
14547                outInfo.removedUsers = deletedPs != null
14548                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
14549                        : null;
14550            }
14551        }
14552        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14553            removeDataDirsLI(ps.volumeUuid, packageName);
14554            if (outInfo != null) {
14555                outInfo.dataRemoved = true;
14556            }
14557            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
14558        }
14559        // writer
14560        synchronized (mPackages) {
14561            if (deletedPs != null) {
14562                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
14563                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
14564                    clearDefaultBrowserIfNeeded(packageName);
14565                    if (outInfo != null) {
14566                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
14567                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
14568                    }
14569                    updatePermissionsLPw(deletedPs.name, null, 0);
14570                    if (deletedPs.sharedUser != null) {
14571                        // Remove permissions associated with package. Since runtime
14572                        // permissions are per user we have to kill the removed package
14573                        // or packages running under the shared user of the removed
14574                        // package if revoking the permissions requested only by the removed
14575                        // package is successful and this causes a change in gids.
14576                        for (int userId : UserManagerService.getInstance().getUserIds()) {
14577                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
14578                                    userId);
14579                            if (userIdToKill == UserHandle.USER_ALL
14580                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
14581                                // If gids changed for this user, kill all affected packages.
14582                                mHandler.post(new Runnable() {
14583                                    @Override
14584                                    public void run() {
14585                                        // This has to happen with no lock held.
14586                                        killApplication(deletedPs.name, deletedPs.appId,
14587                                                KILL_APP_REASON_GIDS_CHANGED);
14588                                    }
14589                                });
14590                                break;
14591                            }
14592                        }
14593                    }
14594                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
14595                }
14596                // make sure to preserve per-user disabled state if this removal was just
14597                // a downgrade of a system app to the factory package
14598                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
14599                    if (DEBUG_REMOVE) {
14600                        Slog.d(TAG, "Propagating install state across downgrade");
14601                    }
14602                    for (int userId : allUserHandles) {
14603                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14604                        if (DEBUG_REMOVE) {
14605                            Slog.d(TAG, "    user " + userId + " => " + installed);
14606                        }
14607                        ps.setInstalled(installed, userId);
14608                    }
14609                }
14610            }
14611            // can downgrade to reader
14612            if (writeSettings) {
14613                // Save settings now
14614                mSettings.writeLPr();
14615            }
14616        }
14617        if (outInfo != null) {
14618            // A user ID was deleted here. Go through all users and remove it
14619            // from KeyStore.
14620            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
14621        }
14622    }
14623
14624    static boolean locationIsPrivileged(File path) {
14625        try {
14626            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
14627                    .getCanonicalPath();
14628            return path.getCanonicalPath().startsWith(privilegedAppDir);
14629        } catch (IOException e) {
14630            Slog.e(TAG, "Unable to access code path " + path);
14631        }
14632        return false;
14633    }
14634
14635    /*
14636     * Tries to delete system package.
14637     */
14638    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
14639            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
14640            boolean writeSettings) {
14641        if (deletedPs.parentPackageName != null) {
14642            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
14643            return false;
14644        }
14645
14646        final boolean applyUserRestrictions
14647                = (allUserHandles != null) && (outInfo.origUsers != null);
14648        final PackageSetting disabledPs;
14649        // Confirm if the system package has been updated
14650        // An updated system app can be deleted. This will also have to restore
14651        // the system pkg from system partition
14652        // reader
14653        synchronized (mPackages) {
14654            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
14655        }
14656
14657        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
14658                + " disabledPs=" + disabledPs);
14659
14660        if (disabledPs == null) {
14661            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
14662            return false;
14663        } else if (DEBUG_REMOVE) {
14664            Slog.d(TAG, "Deleting system pkg from data partition");
14665        }
14666
14667        if (DEBUG_REMOVE) {
14668            if (applyUserRestrictions) {
14669                Slog.d(TAG, "Remembering install states:");
14670                for (int userId : allUserHandles) {
14671                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
14672                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
14673                }
14674            }
14675        }
14676
14677        // Delete the updated package
14678        outInfo.isRemovedPackageSystemUpdate = true;
14679        if (outInfo.removedChildPackages != null) {
14680            final int childCount = (deletedPs.childPackageNames != null)
14681                    ? deletedPs.childPackageNames.size() : 0;
14682            for (int i = 0; i < childCount; i++) {
14683                String childPackageName = deletedPs.childPackageNames.get(i);
14684                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
14685                        .contains(childPackageName)) {
14686                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14687                            childPackageName);
14688                    if (childInfo != null) {
14689                        childInfo.isRemovedPackageSystemUpdate = true;
14690                    }
14691                }
14692            }
14693        }
14694
14695        if (disabledPs.versionCode < deletedPs.versionCode) {
14696            // Delete data for downgrades
14697            flags &= ~PackageManager.DELETE_KEEP_DATA;
14698        } else {
14699            // Preserve data by setting flag
14700            flags |= PackageManager.DELETE_KEEP_DATA;
14701        }
14702
14703        boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles,
14704                outInfo, writeSettings, disabledPs.pkg);
14705        if (!ret) {
14706            return false;
14707        }
14708
14709        // writer
14710        synchronized (mPackages) {
14711            // Reinstate the old system package
14712            enableSystemPackageLPw(disabledPs.pkg);
14713            // Remove any native libraries from the upgraded package.
14714            removeNativeBinariesLI(deletedPs);
14715        }
14716
14717        // Install the system package
14718        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
14719        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
14720        if (locationIsPrivileged(disabledPs.codePath)) {
14721            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
14722        }
14723
14724        final PackageParser.Package newPkg;
14725        try {
14726            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
14727        } catch (PackageManagerException e) {
14728            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
14729                    + e.getMessage());
14730            return false;
14731        }
14732
14733        prepareAppDataAfterInstall(newPkg);
14734
14735        // writer
14736        synchronized (mPackages) {
14737            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
14738
14739            // Propagate the permissions state as we do not want to drop on the floor
14740            // runtime permissions. The update permissions method below will take
14741            // care of removing obsolete permissions and grant install permissions.
14742            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
14743            updatePermissionsLPw(newPkg.packageName, newPkg,
14744                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
14745
14746            if (applyUserRestrictions) {
14747                if (DEBUG_REMOVE) {
14748                    Slog.d(TAG, "Propagating install state across reinstall");
14749                }
14750                for (int userId : allUserHandles) {
14751                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
14752                    if (DEBUG_REMOVE) {
14753                        Slog.d(TAG, "    user " + userId + " => " + installed);
14754                    }
14755                    ps.setInstalled(installed, userId);
14756
14757                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
14758                }
14759                // Regardless of writeSettings we need to ensure that this restriction
14760                // state propagation is persisted
14761                mSettings.writeAllUsersPackageRestrictionsLPr();
14762            }
14763            // can downgrade to reader here
14764            if (writeSettings) {
14765                mSettings.writeLPr();
14766            }
14767        }
14768        return true;
14769    }
14770
14771    private boolean deleteInstalledPackageLI(PackageSetting ps,
14772            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
14773            PackageRemovedInfo outInfo, boolean writeSettings,
14774            PackageParser.Package replacingPackage) {
14775        synchronized (mPackages) {
14776            if (outInfo != null) {
14777                outInfo.uid = ps.appId;
14778            }
14779
14780            if (outInfo != null && outInfo.removedChildPackages != null) {
14781                final int childCount = (ps.childPackageNames != null)
14782                        ? ps.childPackageNames.size() : 0;
14783                for (int i = 0; i < childCount; i++) {
14784                    String childPackageName = ps.childPackageNames.get(i);
14785                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
14786                    if (childPs == null) {
14787                        return false;
14788                    }
14789                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
14790                            childPackageName);
14791                    if (childInfo != null) {
14792                        childInfo.uid = childPs.appId;
14793                    }
14794                }
14795            }
14796        }
14797
14798        // Delete package data from internal structures and also remove data if flag is set
14799        removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings);
14800
14801        // Delete the child packages data
14802        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
14803        for (int i = 0; i < childCount; i++) {
14804            PackageSetting childPs;
14805            synchronized (mPackages) {
14806                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
14807            }
14808            if (childPs != null) {
14809                PackageRemovedInfo childOutInfo = (outInfo != null
14810                        && outInfo.removedChildPackages != null)
14811                        ? outInfo.removedChildPackages.get(childPs.name) : null;
14812                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
14813                        && (replacingPackage != null
14814                        && !replacingPackage.hasChildPackage(childPs.name))
14815                        ? flags & ~DELETE_KEEP_DATA : flags;
14816                removePackageDataLI(childPs, allUserHandles, childOutInfo,
14817                        deleteFlags, writeSettings);
14818            }
14819        }
14820
14821        // Delete application code and resources only for parent packages
14822        if (ps.parentPackageName == null) {
14823            if (deleteCodeAndResources && (outInfo != null)) {
14824                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
14825                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
14826                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
14827            }
14828        }
14829
14830        return true;
14831    }
14832
14833    @Override
14834    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
14835            int userId) {
14836        mContext.enforceCallingOrSelfPermission(
14837                android.Manifest.permission.DELETE_PACKAGES, null);
14838        synchronized (mPackages) {
14839            PackageSetting ps = mSettings.mPackages.get(packageName);
14840            if (ps == null) {
14841                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
14842                return false;
14843            }
14844            if (!ps.getInstalled(userId)) {
14845                // Can't block uninstall for an app that is not installed or enabled.
14846                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
14847                return false;
14848            }
14849            ps.setBlockUninstall(blockUninstall, userId);
14850            mSettings.writePackageRestrictionsLPr(userId);
14851        }
14852        return true;
14853    }
14854
14855    @Override
14856    public boolean getBlockUninstallForUser(String packageName, int userId) {
14857        synchronized (mPackages) {
14858            PackageSetting ps = mSettings.mPackages.get(packageName);
14859            if (ps == null) {
14860                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
14861                return false;
14862            }
14863            return ps.getBlockUninstall(userId);
14864        }
14865    }
14866
14867    @Override
14868    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
14869        int callingUid = Binder.getCallingUid();
14870        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
14871            throw new SecurityException(
14872                    "setRequiredForSystemUser can only be run by the system or root");
14873        }
14874        synchronized (mPackages) {
14875            PackageSetting ps = mSettings.mPackages.get(packageName);
14876            if (ps == null) {
14877                Log.w(TAG, "Package doesn't exist: " + packageName);
14878                return false;
14879            }
14880            if (systemUserApp) {
14881                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14882            } else {
14883                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
14884            }
14885            mSettings.writeLPr();
14886        }
14887        return true;
14888    }
14889
14890    /*
14891     * This method handles package deletion in general
14892     */
14893    private boolean deletePackageLI(String packageName, UserHandle user,
14894            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
14895            PackageRemovedInfo outInfo, boolean writeSettings,
14896            PackageParser.Package replacingPackage) {
14897        if (packageName == null) {
14898            Slog.w(TAG, "Attempt to delete null packageName.");
14899            return false;
14900        }
14901
14902        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
14903
14904        PackageSetting ps;
14905
14906        synchronized (mPackages) {
14907            ps = mSettings.mPackages.get(packageName);
14908            if (ps == null) {
14909                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
14910                return false;
14911            }
14912
14913            if (ps.parentPackageName != null && (!isSystemApp(ps)
14914                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
14915                if (DEBUG_REMOVE) {
14916                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
14917                            + ((user == null) ? UserHandle.USER_ALL : user));
14918                }
14919                final int removedUserId = (user != null) ? user.getIdentifier()
14920                        : UserHandle.USER_ALL;
14921                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
14922                    return false;
14923                }
14924                markPackageUninstalledForUserLPw(ps, user);
14925                scheduleWritePackageRestrictionsLocked(user);
14926                return true;
14927            }
14928        }
14929
14930        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
14931                && user.getIdentifier() != UserHandle.USER_ALL)) {
14932            // The caller is asking that the package only be deleted for a single
14933            // user.  To do this, we just mark its uninstalled state and delete
14934            // its data. If this is a system app, we only allow this to happen if
14935            // they have set the special DELETE_SYSTEM_APP which requests different
14936            // semantics than normal for uninstalling system apps.
14937            markPackageUninstalledForUserLPw(ps, user);
14938
14939            if (!isSystemApp(ps)) {
14940                // Do not uninstall the APK if an app should be cached
14941                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
14942                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
14943                    // Other user still have this package installed, so all
14944                    // we need to do is clear this user's data and save that
14945                    // it is uninstalled.
14946                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
14947                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14948                        return false;
14949                    }
14950                    scheduleWritePackageRestrictionsLocked(user);
14951                    return true;
14952                } else {
14953                    // We need to set it back to 'installed' so the uninstall
14954                    // broadcasts will be sent correctly.
14955                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
14956                    ps.setInstalled(true, user.getIdentifier());
14957                }
14958            } else {
14959                // This is a system app, so we assume that the
14960                // other users still have this package installed, so all
14961                // we need to do is clear this user's data and save that
14962                // it is uninstalled.
14963                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
14964                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
14965                    return false;
14966                }
14967                scheduleWritePackageRestrictionsLocked(user);
14968                return true;
14969            }
14970        }
14971
14972        // If we are deleting a composite package for all users, keep track
14973        // of result for each child.
14974        if (ps.childPackageNames != null && outInfo != null) {
14975            synchronized (mPackages) {
14976                final int childCount = ps.childPackageNames.size();
14977                outInfo.removedChildPackages = new ArrayMap<>(childCount);
14978                for (int i = 0; i < childCount; i++) {
14979                    String childPackageName = ps.childPackageNames.get(i);
14980                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
14981                    childInfo.removedPackage = childPackageName;
14982                    outInfo.removedChildPackages.put(childPackageName, childInfo);
14983                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
14984                    if (childPs != null) {
14985                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
14986                    }
14987                }
14988            }
14989        }
14990
14991        boolean ret = false;
14992        if (isSystemApp(ps)) {
14993            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
14994            // When an updated system application is deleted we delete the existing resources
14995            // as well and fall back to existing code in system partition
14996            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
14997        } else {
14998            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
14999            // Kill application pre-emptively especially for apps on sd.
15000            final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15001            if (killApp) {
15002                killApplication(packageName, ps.appId, "uninstall pkg");
15003            }
15004            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles,
15005                    outInfo, writeSettings, replacingPackage);
15006        }
15007
15008        // Take a note whether we deleted the package for all users
15009        if (outInfo != null) {
15010            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15011            if (outInfo.removedChildPackages != null) {
15012                synchronized (mPackages) {
15013                    final int childCount = outInfo.removedChildPackages.size();
15014                    for (int i = 0; i < childCount; i++) {
15015                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15016                        if (childInfo != null) {
15017                            childInfo.removedForAllUsers = mPackages.get(
15018                                    childInfo.removedPackage) == null;
15019                        }
15020                    }
15021                }
15022            }
15023            // If we uninstalled an update to a system app there may be some
15024            // child packages that appeared as they are declared in the system
15025            // app but were not declared in the update.
15026            if (isSystemApp(ps)) {
15027                synchronized (mPackages) {
15028                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15029                    final int childCount = (updatedPs.childPackageNames != null)
15030                            ? updatedPs.childPackageNames.size() : 0;
15031                    for (int i = 0; i < childCount; i++) {
15032                        String childPackageName = updatedPs.childPackageNames.get(i);
15033                        if (outInfo.removedChildPackages == null
15034                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15035                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15036                            if (childPs == null) {
15037                                continue;
15038                            }
15039                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15040                            installRes.name = childPackageName;
15041                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15042                            installRes.pkg = mPackages.get(childPackageName);
15043                            installRes.uid = childPs.pkg.applicationInfo.uid;
15044                            if (outInfo.appearedChildPackages == null) {
15045                                outInfo.appearedChildPackages = new ArrayMap<>();
15046                            }
15047                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15048                        }
15049                    }
15050                }
15051            }
15052        }
15053
15054        return ret;
15055    }
15056
15057    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15058        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15059                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15060        for (int nextUserId : userIds) {
15061            if (DEBUG_REMOVE) {
15062                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15063            }
15064            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
15065                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15066                    false /*hidden*/, false /*suspended*/, null, null, null,
15067                    false /*blockUninstall*/,
15068                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15069        }
15070    }
15071
15072    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
15073            PackageRemovedInfo outInfo) {
15074        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15075                : new int[] {userId};
15076        for (int nextUserId : userIds) {
15077            if (DEBUG_REMOVE) {
15078                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15079                        + nextUserId);
15080            }
15081            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
15082            try {
15083                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
15084            } catch (InstallerException e) {
15085                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
15086                return false;
15087            }
15088            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15089            schedulePackageCleaning(ps.name, nextUserId, false);
15090            synchronized (mPackages) {
15091                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15092                    scheduleWritePackageRestrictionsLocked(nextUserId);
15093                }
15094                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15095            }
15096        }
15097
15098        if (outInfo != null) {
15099            outInfo.removedPackage = ps.name;
15100            outInfo.removedAppId = ps.appId;
15101            outInfo.removedUsers = userIds;
15102        }
15103
15104        return true;
15105    }
15106
15107    private final class ClearStorageConnection implements ServiceConnection {
15108        IMediaContainerService mContainerService;
15109
15110        @Override
15111        public void onServiceConnected(ComponentName name, IBinder service) {
15112            synchronized (this) {
15113                mContainerService = IMediaContainerService.Stub.asInterface(service);
15114                notifyAll();
15115            }
15116        }
15117
15118        @Override
15119        public void onServiceDisconnected(ComponentName name) {
15120        }
15121    }
15122
15123    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15124        final boolean mounted;
15125        if (Environment.isExternalStorageEmulated()) {
15126            mounted = true;
15127        } else {
15128            final String status = Environment.getExternalStorageState();
15129
15130            mounted = status.equals(Environment.MEDIA_MOUNTED)
15131                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15132        }
15133
15134        if (!mounted) {
15135            return;
15136        }
15137
15138        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15139        int[] users;
15140        if (userId == UserHandle.USER_ALL) {
15141            users = sUserManager.getUserIds();
15142        } else {
15143            users = new int[] { userId };
15144        }
15145        final ClearStorageConnection conn = new ClearStorageConnection();
15146        if (mContext.bindServiceAsUser(
15147                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15148            try {
15149                for (int curUser : users) {
15150                    long timeout = SystemClock.uptimeMillis() + 5000;
15151                    synchronized (conn) {
15152                        long now = SystemClock.uptimeMillis();
15153                        while (conn.mContainerService == null && now < timeout) {
15154                            try {
15155                                conn.wait(timeout - now);
15156                            } catch (InterruptedException e) {
15157                            }
15158                        }
15159                    }
15160                    if (conn.mContainerService == null) {
15161                        return;
15162                    }
15163
15164                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15165                    clearDirectory(conn.mContainerService,
15166                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15167                    if (allData) {
15168                        clearDirectory(conn.mContainerService,
15169                                userEnv.buildExternalStorageAppDataDirs(packageName));
15170                        clearDirectory(conn.mContainerService,
15171                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15172                    }
15173                }
15174            } finally {
15175                mContext.unbindService(conn);
15176            }
15177        }
15178    }
15179
15180    @Override
15181    public void clearApplicationProfileData(String packageName) {
15182        enforceSystemOrRoot("Only the system can clear all profile data");
15183        try {
15184            mInstaller.rmProfiles(packageName);
15185        } catch (InstallerException ex) {
15186            Log.e(TAG, "Could not clear profile data of package " + packageName);
15187        }
15188    }
15189
15190    @Override
15191    public void clearApplicationUserData(final String packageName,
15192            final IPackageDataObserver observer, final int userId) {
15193        mContext.enforceCallingOrSelfPermission(
15194                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15195
15196        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15197                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15198
15199        final DevicePolicyManagerInternal dpmi = LocalServices
15200                .getService(DevicePolicyManagerInternal.class);
15201        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15202            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15203        }
15204        // Queue up an async operation since the package deletion may take a little while.
15205        mHandler.post(new Runnable() {
15206            public void run() {
15207                mHandler.removeCallbacks(this);
15208                final boolean succeeded;
15209                synchronized (mInstallLock) {
15210                    succeeded = clearApplicationUserDataLI(packageName, userId);
15211                }
15212                clearExternalStorageDataSync(packageName, userId, true);
15213                if (succeeded) {
15214                    // invoke DeviceStorageMonitor's update method to clear any notifications
15215                    DeviceStorageMonitorInternal dsm = LocalServices
15216                            .getService(DeviceStorageMonitorInternal.class);
15217                    if (dsm != null) {
15218                        dsm.checkMemory();
15219                    }
15220                }
15221                if(observer != null) {
15222                    try {
15223                        observer.onRemoveCompleted(packageName, succeeded);
15224                    } catch (RemoteException e) {
15225                        Log.i(TAG, "Observer no longer exists.");
15226                    }
15227                } //end if observer
15228            } //end run
15229        });
15230    }
15231
15232    private boolean clearApplicationUserDataLI(String packageName, int userId) {
15233        if (packageName == null) {
15234            Slog.w(TAG, "Attempt to delete null packageName.");
15235            return false;
15236        }
15237
15238        // Try finding details about the requested package
15239        PackageParser.Package pkg;
15240        synchronized (mPackages) {
15241            pkg = mPackages.get(packageName);
15242            if (pkg == null) {
15243                final PackageSetting ps = mSettings.mPackages.get(packageName);
15244                if (ps != null) {
15245                    pkg = ps.pkg;
15246                }
15247            }
15248
15249            if (pkg == null) {
15250                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15251                return false;
15252            }
15253
15254            PackageSetting ps = (PackageSetting) pkg.mExtras;
15255            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15256        }
15257
15258        // Always delete data directories for package, even if we found no other
15259        // record of app. This helps users recover from UID mismatches without
15260        // resorting to a full data wipe.
15261        // TODO: triage flags as part of 26466827
15262        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15263        try {
15264            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
15265        } catch (InstallerException e) {
15266            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
15267            return false;
15268        }
15269
15270        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15271        removeKeystoreDataIfNeeded(userId, appId);
15272
15273        // Create a native library symlink only if we have native libraries
15274        // and if the native libraries are 32 bit libraries. We do not provide
15275        // this symlink for 64 bit libraries.
15276        if (pkg.applicationInfo.primaryCpuAbi != null &&
15277                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
15278            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
15279            try {
15280                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
15281                        nativeLibPath, userId);
15282            } catch (InstallerException e) {
15283                Slog.w(TAG, "Failed linking native library dir", e);
15284                return false;
15285            }
15286        }
15287
15288        return true;
15289    }
15290
15291    /**
15292     * Reverts user permission state changes (permissions and flags) in
15293     * all packages for a given user.
15294     *
15295     * @param userId The device user for which to do a reset.
15296     */
15297    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15298        final int packageCount = mPackages.size();
15299        for (int i = 0; i < packageCount; i++) {
15300            PackageParser.Package pkg = mPackages.valueAt(i);
15301            PackageSetting ps = (PackageSetting) pkg.mExtras;
15302            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15303        }
15304    }
15305
15306    /**
15307     * Reverts user permission state changes (permissions and flags).
15308     *
15309     * @param ps The package for which to reset.
15310     * @param userId The device user for which to do a reset.
15311     */
15312    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15313            final PackageSetting ps, final int userId) {
15314        if (ps.pkg == null) {
15315            return;
15316        }
15317
15318        // These are flags that can change base on user actions.
15319        final int userSettableMask = FLAG_PERMISSION_USER_SET
15320                | FLAG_PERMISSION_USER_FIXED
15321                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15322                | FLAG_PERMISSION_REVIEW_REQUIRED;
15323
15324        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15325                | FLAG_PERMISSION_POLICY_FIXED;
15326
15327        boolean writeInstallPermissions = false;
15328        boolean writeRuntimePermissions = false;
15329
15330        final int permissionCount = ps.pkg.requestedPermissions.size();
15331        for (int i = 0; i < permissionCount; i++) {
15332            String permission = ps.pkg.requestedPermissions.get(i);
15333
15334            BasePermission bp = mSettings.mPermissions.get(permission);
15335            if (bp == null) {
15336                continue;
15337            }
15338
15339            // If shared user we just reset the state to which only this app contributed.
15340            if (ps.sharedUser != null) {
15341                boolean used = false;
15342                final int packageCount = ps.sharedUser.packages.size();
15343                for (int j = 0; j < packageCount; j++) {
15344                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15345                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15346                            && pkg.pkg.requestedPermissions.contains(permission)) {
15347                        used = true;
15348                        break;
15349                    }
15350                }
15351                if (used) {
15352                    continue;
15353                }
15354            }
15355
15356            PermissionsState permissionsState = ps.getPermissionsState();
15357
15358            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15359
15360            // Always clear the user settable flags.
15361            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15362                    bp.name) != null;
15363            // If permission review is enabled and this is a legacy app, mark the
15364            // permission as requiring a review as this is the initial state.
15365            int flags = 0;
15366            if (Build.PERMISSIONS_REVIEW_REQUIRED
15367                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15368                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15369            }
15370            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15371                if (hasInstallState) {
15372                    writeInstallPermissions = true;
15373                } else {
15374                    writeRuntimePermissions = true;
15375                }
15376            }
15377
15378            // Below is only runtime permission handling.
15379            if (!bp.isRuntime()) {
15380                continue;
15381            }
15382
15383            // Never clobber system or policy.
15384            if ((oldFlags & policyOrSystemFlags) != 0) {
15385                continue;
15386            }
15387
15388            // If this permission was granted by default, make sure it is.
15389            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15390                if (permissionsState.grantRuntimePermission(bp, userId)
15391                        != PERMISSION_OPERATION_FAILURE) {
15392                    writeRuntimePermissions = true;
15393                }
15394            // If permission review is enabled the permissions for a legacy apps
15395            // are represented as constantly granted runtime ones, so don't revoke.
15396            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15397                // Otherwise, reset the permission.
15398                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15399                switch (revokeResult) {
15400                    case PERMISSION_OPERATION_SUCCESS: {
15401                        writeRuntimePermissions = true;
15402                    } break;
15403
15404                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15405                        writeRuntimePermissions = true;
15406                        final int appId = ps.appId;
15407                        mHandler.post(new Runnable() {
15408                            @Override
15409                            public void run() {
15410                                killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
15411                            }
15412                        });
15413                    } break;
15414                }
15415            }
15416        }
15417
15418        // Synchronously write as we are taking permissions away.
15419        if (writeRuntimePermissions) {
15420            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15421        }
15422
15423        // Synchronously write as we are taking permissions away.
15424        if (writeInstallPermissions) {
15425            mSettings.writeLPr();
15426        }
15427    }
15428
15429    /**
15430     * Remove entries from the keystore daemon. Will only remove it if the
15431     * {@code appId} is valid.
15432     */
15433    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15434        if (appId < 0) {
15435            return;
15436        }
15437
15438        final KeyStore keyStore = KeyStore.getInstance();
15439        if (keyStore != null) {
15440            if (userId == UserHandle.USER_ALL) {
15441                for (final int individual : sUserManager.getUserIds()) {
15442                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15443                }
15444            } else {
15445                keyStore.clearUid(UserHandle.getUid(userId, appId));
15446            }
15447        } else {
15448            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15449        }
15450    }
15451
15452    @Override
15453    public void deleteApplicationCacheFiles(final String packageName,
15454            final IPackageDataObserver observer) {
15455        mContext.enforceCallingOrSelfPermission(
15456                android.Manifest.permission.DELETE_CACHE_FILES, null);
15457        // Queue up an async operation since the package deletion may take a little while.
15458        final int userId = UserHandle.getCallingUserId();
15459        mHandler.post(new Runnable() {
15460            public void run() {
15461                mHandler.removeCallbacks(this);
15462                final boolean succeded;
15463                synchronized (mInstallLock) {
15464                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
15465                }
15466                clearExternalStorageDataSync(packageName, userId, false);
15467                if (observer != null) {
15468                    try {
15469                        observer.onRemoveCompleted(packageName, succeded);
15470                    } catch (RemoteException e) {
15471                        Log.i(TAG, "Observer no longer exists.");
15472                    }
15473                } //end if observer
15474            } //end run
15475        });
15476    }
15477
15478    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
15479        if (packageName == null) {
15480            Slog.w(TAG, "Attempt to delete null packageName.");
15481            return false;
15482        }
15483        PackageParser.Package p;
15484        synchronized (mPackages) {
15485            p = mPackages.get(packageName);
15486        }
15487        if (p == null) {
15488            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15489            return false;
15490        }
15491        final ApplicationInfo applicationInfo = p.applicationInfo;
15492        if (applicationInfo == null) {
15493            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15494            return false;
15495        }
15496        // TODO: triage flags as part of 26466827
15497        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15498        try {
15499            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
15500                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
15501        } catch (InstallerException e) {
15502            Slog.w(TAG, "Couldn't remove cache files for package "
15503                    + packageName + " u" + userId, e);
15504            return false;
15505        }
15506        return true;
15507    }
15508
15509    @Override
15510    public void getPackageSizeInfo(final String packageName, int userHandle,
15511            final IPackageStatsObserver observer) {
15512        mContext.enforceCallingOrSelfPermission(
15513                android.Manifest.permission.GET_PACKAGE_SIZE, null);
15514        if (packageName == null) {
15515            throw new IllegalArgumentException("Attempt to get size of null packageName");
15516        }
15517
15518        PackageStats stats = new PackageStats(packageName, userHandle);
15519
15520        /*
15521         * Queue up an async operation since the package measurement may take a
15522         * little while.
15523         */
15524        Message msg = mHandler.obtainMessage(INIT_COPY);
15525        msg.obj = new MeasureParams(stats, observer);
15526        mHandler.sendMessage(msg);
15527    }
15528
15529    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
15530            PackageStats pStats) {
15531        if (packageName == null) {
15532            Slog.w(TAG, "Attempt to get size of null packageName.");
15533            return false;
15534        }
15535        PackageParser.Package p;
15536        boolean dataOnly = false;
15537        String libDirRoot = null;
15538        String asecPath = null;
15539        PackageSetting ps = null;
15540        synchronized (mPackages) {
15541            p = mPackages.get(packageName);
15542            ps = mSettings.mPackages.get(packageName);
15543            if(p == null) {
15544                dataOnly = true;
15545                if((ps == null) || (ps.pkg == null)) {
15546                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15547                    return false;
15548                }
15549                p = ps.pkg;
15550            }
15551            if (ps != null) {
15552                libDirRoot = ps.legacyNativeLibraryPathString;
15553            }
15554            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
15555                final long token = Binder.clearCallingIdentity();
15556                try {
15557                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
15558                    if (secureContainerId != null) {
15559                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
15560                    }
15561                } finally {
15562                    Binder.restoreCallingIdentity(token);
15563                }
15564            }
15565        }
15566        String publicSrcDir = null;
15567        if(!dataOnly) {
15568            final ApplicationInfo applicationInfo = p.applicationInfo;
15569            if (applicationInfo == null) {
15570                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15571                return false;
15572            }
15573            if (p.isForwardLocked()) {
15574                publicSrcDir = applicationInfo.getBaseResourcePath();
15575            }
15576        }
15577        // TODO: extend to measure size of split APKs
15578        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
15579        // not just the first level.
15580        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
15581        // just the primary.
15582        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
15583
15584        String apkPath;
15585        File packageDir = new File(p.codePath);
15586
15587        if (packageDir.isDirectory() && p.canHaveOatDir()) {
15588            apkPath = packageDir.getAbsolutePath();
15589            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
15590            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
15591                libDirRoot = null;
15592            }
15593        } else {
15594            apkPath = p.baseCodePath;
15595        }
15596
15597        // TODO: triage flags as part of 26466827
15598        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15599        try {
15600            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
15601                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
15602        } catch (InstallerException e) {
15603            return false;
15604        }
15605
15606        // Fix-up for forward-locked applications in ASEC containers.
15607        if (!isExternal(p)) {
15608            pStats.codeSize += pStats.externalCodeSize;
15609            pStats.externalCodeSize = 0L;
15610        }
15611
15612        return true;
15613    }
15614
15615    private int getUidTargetSdkVersionLockedLPr(int uid) {
15616        Object obj = mSettings.getUserIdLPr(uid);
15617        if (obj instanceof SharedUserSetting) {
15618            final SharedUserSetting sus = (SharedUserSetting) obj;
15619            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
15620            final Iterator<PackageSetting> it = sus.packages.iterator();
15621            while (it.hasNext()) {
15622                final PackageSetting ps = it.next();
15623                if (ps.pkg != null) {
15624                    int v = ps.pkg.applicationInfo.targetSdkVersion;
15625                    if (v < vers) vers = v;
15626                }
15627            }
15628            return vers;
15629        } else if (obj instanceof PackageSetting) {
15630            final PackageSetting ps = (PackageSetting) obj;
15631            if (ps.pkg != null) {
15632                return ps.pkg.applicationInfo.targetSdkVersion;
15633            }
15634        }
15635        return Build.VERSION_CODES.CUR_DEVELOPMENT;
15636    }
15637
15638    @Override
15639    public void addPreferredActivity(IntentFilter filter, int match,
15640            ComponentName[] set, ComponentName activity, int userId) {
15641        addPreferredActivityInternal(filter, match, set, activity, true, userId,
15642                "Adding preferred");
15643    }
15644
15645    private void addPreferredActivityInternal(IntentFilter filter, int match,
15646            ComponentName[] set, ComponentName activity, boolean always, int userId,
15647            String opname) {
15648        // writer
15649        int callingUid = Binder.getCallingUid();
15650        enforceCrossUserPermission(callingUid, userId,
15651                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
15652        if (filter.countActions() == 0) {
15653            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15654            return;
15655        }
15656        synchronized (mPackages) {
15657            if (mContext.checkCallingOrSelfPermission(
15658                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15659                    != PackageManager.PERMISSION_GRANTED) {
15660                if (getUidTargetSdkVersionLockedLPr(callingUid)
15661                        < Build.VERSION_CODES.FROYO) {
15662                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
15663                            + callingUid);
15664                    return;
15665                }
15666                mContext.enforceCallingOrSelfPermission(
15667                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15668            }
15669
15670            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
15671            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
15672                    + userId + ":");
15673            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15674            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
15675            scheduleWritePackageRestrictionsLocked(userId);
15676        }
15677    }
15678
15679    @Override
15680    public void replacePreferredActivity(IntentFilter filter, int match,
15681            ComponentName[] set, ComponentName activity, int userId) {
15682        if (filter.countActions() != 1) {
15683            throw new IllegalArgumentException(
15684                    "replacePreferredActivity expects filter to have only 1 action.");
15685        }
15686        if (filter.countDataAuthorities() != 0
15687                || filter.countDataPaths() != 0
15688                || filter.countDataSchemes() > 1
15689                || filter.countDataTypes() != 0) {
15690            throw new IllegalArgumentException(
15691                    "replacePreferredActivity expects filter to have no data authorities, " +
15692                    "paths, or types; and at most one scheme.");
15693        }
15694
15695        final int callingUid = Binder.getCallingUid();
15696        enforceCrossUserPermission(callingUid, userId,
15697                true /* requireFullPermission */, false /* checkShell */,
15698                "replace preferred activity");
15699        synchronized (mPackages) {
15700            if (mContext.checkCallingOrSelfPermission(
15701                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15702                    != PackageManager.PERMISSION_GRANTED) {
15703                if (getUidTargetSdkVersionLockedLPr(callingUid)
15704                        < Build.VERSION_CODES.FROYO) {
15705                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
15706                            + Binder.getCallingUid());
15707                    return;
15708                }
15709                mContext.enforceCallingOrSelfPermission(
15710                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15711            }
15712
15713            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15714            if (pir != null) {
15715                // Get all of the existing entries that exactly match this filter.
15716                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
15717                if (existing != null && existing.size() == 1) {
15718                    PreferredActivity cur = existing.get(0);
15719                    if (DEBUG_PREFERRED) {
15720                        Slog.i(TAG, "Checking replace of preferred:");
15721                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15722                        if (!cur.mPref.mAlways) {
15723                            Slog.i(TAG, "  -- CUR; not mAlways!");
15724                        } else {
15725                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
15726                            Slog.i(TAG, "  -- CUR: mSet="
15727                                    + Arrays.toString(cur.mPref.mSetComponents));
15728                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
15729                            Slog.i(TAG, "  -- NEW: mMatch="
15730                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
15731                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
15732                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
15733                        }
15734                    }
15735                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
15736                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
15737                            && cur.mPref.sameSet(set)) {
15738                        // Setting the preferred activity to what it happens to be already
15739                        if (DEBUG_PREFERRED) {
15740                            Slog.i(TAG, "Replacing with same preferred activity "
15741                                    + cur.mPref.mShortComponent + " for user "
15742                                    + userId + ":");
15743                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15744                        }
15745                        return;
15746                    }
15747                }
15748
15749                if (existing != null) {
15750                    if (DEBUG_PREFERRED) {
15751                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
15752                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15753                    }
15754                    for (int i = 0; i < existing.size(); i++) {
15755                        PreferredActivity pa = existing.get(i);
15756                        if (DEBUG_PREFERRED) {
15757                            Slog.i(TAG, "Removing existing preferred activity "
15758                                    + pa.mPref.mComponent + ":");
15759                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
15760                        }
15761                        pir.removeFilter(pa);
15762                    }
15763                }
15764            }
15765            addPreferredActivityInternal(filter, match, set, activity, true, userId,
15766                    "Replacing preferred");
15767        }
15768    }
15769
15770    @Override
15771    public void clearPackagePreferredActivities(String packageName) {
15772        final int uid = Binder.getCallingUid();
15773        // writer
15774        synchronized (mPackages) {
15775            PackageParser.Package pkg = mPackages.get(packageName);
15776            if (pkg == null || pkg.applicationInfo.uid != uid) {
15777                if (mContext.checkCallingOrSelfPermission(
15778                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
15779                        != PackageManager.PERMISSION_GRANTED) {
15780                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
15781                            < Build.VERSION_CODES.FROYO) {
15782                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
15783                                + Binder.getCallingUid());
15784                        return;
15785                    }
15786                    mContext.enforceCallingOrSelfPermission(
15787                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15788                }
15789            }
15790
15791            int user = UserHandle.getCallingUserId();
15792            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
15793                scheduleWritePackageRestrictionsLocked(user);
15794            }
15795        }
15796    }
15797
15798    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15799    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
15800        ArrayList<PreferredActivity> removed = null;
15801        boolean changed = false;
15802        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
15803            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
15804            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
15805            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
15806                continue;
15807            }
15808            Iterator<PreferredActivity> it = pir.filterIterator();
15809            while (it.hasNext()) {
15810                PreferredActivity pa = it.next();
15811                // Mark entry for removal only if it matches the package name
15812                // and the entry is of type "always".
15813                if (packageName == null ||
15814                        (pa.mPref.mComponent.getPackageName().equals(packageName)
15815                                && pa.mPref.mAlways)) {
15816                    if (removed == null) {
15817                        removed = new ArrayList<PreferredActivity>();
15818                    }
15819                    removed.add(pa);
15820                }
15821            }
15822            if (removed != null) {
15823                for (int j=0; j<removed.size(); j++) {
15824                    PreferredActivity pa = removed.get(j);
15825                    pir.removeFilter(pa);
15826                }
15827                changed = true;
15828            }
15829        }
15830        return changed;
15831    }
15832
15833    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15834    private void clearIntentFilterVerificationsLPw(int userId) {
15835        final int packageCount = mPackages.size();
15836        for (int i = 0; i < packageCount; i++) {
15837            PackageParser.Package pkg = mPackages.valueAt(i);
15838            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
15839        }
15840    }
15841
15842    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
15843    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
15844        if (userId == UserHandle.USER_ALL) {
15845            if (mSettings.removeIntentFilterVerificationLPw(packageName,
15846                    sUserManager.getUserIds())) {
15847                for (int oneUserId : sUserManager.getUserIds()) {
15848                    scheduleWritePackageRestrictionsLocked(oneUserId);
15849                }
15850            }
15851        } else {
15852            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
15853                scheduleWritePackageRestrictionsLocked(userId);
15854            }
15855        }
15856    }
15857
15858    void clearDefaultBrowserIfNeeded(String packageName) {
15859        for (int oneUserId : sUserManager.getUserIds()) {
15860            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
15861            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
15862            if (packageName.equals(defaultBrowserPackageName)) {
15863                setDefaultBrowserPackageName(null, oneUserId);
15864            }
15865        }
15866    }
15867
15868    @Override
15869    public void resetApplicationPreferences(int userId) {
15870        mContext.enforceCallingOrSelfPermission(
15871                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15872        // writer
15873        synchronized (mPackages) {
15874            final long identity = Binder.clearCallingIdentity();
15875            try {
15876                clearPackagePreferredActivitiesLPw(null, userId);
15877                mSettings.applyDefaultPreferredAppsLPw(this, userId);
15878                // TODO: We have to reset the default SMS and Phone. This requires
15879                // significant refactoring to keep all default apps in the package
15880                // manager (cleaner but more work) or have the services provide
15881                // callbacks to the package manager to request a default app reset.
15882                applyFactoryDefaultBrowserLPw(userId);
15883                clearIntentFilterVerificationsLPw(userId);
15884                primeDomainVerificationsLPw(userId);
15885                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
15886                scheduleWritePackageRestrictionsLocked(userId);
15887            } finally {
15888                Binder.restoreCallingIdentity(identity);
15889            }
15890        }
15891    }
15892
15893    @Override
15894    public int getPreferredActivities(List<IntentFilter> outFilters,
15895            List<ComponentName> outActivities, String packageName) {
15896
15897        int num = 0;
15898        final int userId = UserHandle.getCallingUserId();
15899        // reader
15900        synchronized (mPackages) {
15901            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
15902            if (pir != null) {
15903                final Iterator<PreferredActivity> it = pir.filterIterator();
15904                while (it.hasNext()) {
15905                    final PreferredActivity pa = it.next();
15906                    if (packageName == null
15907                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
15908                                    && pa.mPref.mAlways)) {
15909                        if (outFilters != null) {
15910                            outFilters.add(new IntentFilter(pa));
15911                        }
15912                        if (outActivities != null) {
15913                            outActivities.add(pa.mPref.mComponent);
15914                        }
15915                    }
15916                }
15917            }
15918        }
15919
15920        return num;
15921    }
15922
15923    @Override
15924    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
15925            int userId) {
15926        int callingUid = Binder.getCallingUid();
15927        if (callingUid != Process.SYSTEM_UID) {
15928            throw new SecurityException(
15929                    "addPersistentPreferredActivity can only be run by the system");
15930        }
15931        if (filter.countActions() == 0) {
15932            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
15933            return;
15934        }
15935        synchronized (mPackages) {
15936            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
15937                    ":");
15938            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
15939            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
15940                    new PersistentPreferredActivity(filter, activity));
15941            scheduleWritePackageRestrictionsLocked(userId);
15942        }
15943    }
15944
15945    @Override
15946    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
15947        int callingUid = Binder.getCallingUid();
15948        if (callingUid != Process.SYSTEM_UID) {
15949            throw new SecurityException(
15950                    "clearPackagePersistentPreferredActivities can only be run by the system");
15951        }
15952        ArrayList<PersistentPreferredActivity> removed = null;
15953        boolean changed = false;
15954        synchronized (mPackages) {
15955            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
15956                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
15957                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
15958                        .valueAt(i);
15959                if (userId != thisUserId) {
15960                    continue;
15961                }
15962                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
15963                while (it.hasNext()) {
15964                    PersistentPreferredActivity ppa = it.next();
15965                    // Mark entry for removal only if it matches the package name.
15966                    if (ppa.mComponent.getPackageName().equals(packageName)) {
15967                        if (removed == null) {
15968                            removed = new ArrayList<PersistentPreferredActivity>();
15969                        }
15970                        removed.add(ppa);
15971                    }
15972                }
15973                if (removed != null) {
15974                    for (int j=0; j<removed.size(); j++) {
15975                        PersistentPreferredActivity ppa = removed.get(j);
15976                        ppir.removeFilter(ppa);
15977                    }
15978                    changed = true;
15979                }
15980            }
15981
15982            if (changed) {
15983                scheduleWritePackageRestrictionsLocked(userId);
15984            }
15985        }
15986    }
15987
15988    /**
15989     * Common machinery for picking apart a restored XML blob and passing
15990     * it to a caller-supplied functor to be applied to the running system.
15991     */
15992    private void restoreFromXml(XmlPullParser parser, int userId,
15993            String expectedStartTag, BlobXmlRestorer functor)
15994            throws IOException, XmlPullParserException {
15995        int type;
15996        while ((type = parser.next()) != XmlPullParser.START_TAG
15997                && type != XmlPullParser.END_DOCUMENT) {
15998        }
15999        if (type != XmlPullParser.START_TAG) {
16000            // oops didn't find a start tag?!
16001            if (DEBUG_BACKUP) {
16002                Slog.e(TAG, "Didn't find start tag during restore");
16003            }
16004            return;
16005        }
16006Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16007        // this is supposed to be TAG_PREFERRED_BACKUP
16008        if (!expectedStartTag.equals(parser.getName())) {
16009            if (DEBUG_BACKUP) {
16010                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16011            }
16012            return;
16013        }
16014
16015        // skip interfering stuff, then we're aligned with the backing implementation
16016        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16017Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16018        functor.apply(parser, userId);
16019    }
16020
16021    private interface BlobXmlRestorer {
16022        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16023    }
16024
16025    /**
16026     * Non-Binder method, support for the backup/restore mechanism: write the
16027     * full set of preferred activities in its canonical XML format.  Returns the
16028     * XML output as a byte array, or null if there is none.
16029     */
16030    @Override
16031    public byte[] getPreferredActivityBackup(int userId) {
16032        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16033            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16034        }
16035
16036        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16037        try {
16038            final XmlSerializer serializer = new FastXmlSerializer();
16039            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16040            serializer.startDocument(null, true);
16041            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16042
16043            synchronized (mPackages) {
16044                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16045            }
16046
16047            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16048            serializer.endDocument();
16049            serializer.flush();
16050        } catch (Exception e) {
16051            if (DEBUG_BACKUP) {
16052                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16053            }
16054            return null;
16055        }
16056
16057        return dataStream.toByteArray();
16058    }
16059
16060    @Override
16061    public void restorePreferredActivities(byte[] backup, int userId) {
16062        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16063            throw new SecurityException("Only the system may call restorePreferredActivities()");
16064        }
16065
16066        try {
16067            final XmlPullParser parser = Xml.newPullParser();
16068            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16069            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16070                    new BlobXmlRestorer() {
16071                        @Override
16072                        public void apply(XmlPullParser parser, int userId)
16073                                throws XmlPullParserException, IOException {
16074                            synchronized (mPackages) {
16075                                mSettings.readPreferredActivitiesLPw(parser, userId);
16076                            }
16077                        }
16078                    } );
16079        } catch (Exception e) {
16080            if (DEBUG_BACKUP) {
16081                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16082            }
16083        }
16084    }
16085
16086    /**
16087     * Non-Binder method, support for the backup/restore mechanism: write the
16088     * default browser (etc) settings in its canonical XML format.  Returns the default
16089     * browser XML representation as a byte array, or null if there is none.
16090     */
16091    @Override
16092    public byte[] getDefaultAppsBackup(int userId) {
16093        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16094            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16095        }
16096
16097        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16098        try {
16099            final XmlSerializer serializer = new FastXmlSerializer();
16100            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16101            serializer.startDocument(null, true);
16102            serializer.startTag(null, TAG_DEFAULT_APPS);
16103
16104            synchronized (mPackages) {
16105                mSettings.writeDefaultAppsLPr(serializer, userId);
16106            }
16107
16108            serializer.endTag(null, TAG_DEFAULT_APPS);
16109            serializer.endDocument();
16110            serializer.flush();
16111        } catch (Exception e) {
16112            if (DEBUG_BACKUP) {
16113                Slog.e(TAG, "Unable to write default apps for backup", e);
16114            }
16115            return null;
16116        }
16117
16118        return dataStream.toByteArray();
16119    }
16120
16121    @Override
16122    public void restoreDefaultApps(byte[] backup, int userId) {
16123        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16124            throw new SecurityException("Only the system may call restoreDefaultApps()");
16125        }
16126
16127        try {
16128            final XmlPullParser parser = Xml.newPullParser();
16129            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16130            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16131                    new BlobXmlRestorer() {
16132                        @Override
16133                        public void apply(XmlPullParser parser, int userId)
16134                                throws XmlPullParserException, IOException {
16135                            synchronized (mPackages) {
16136                                mSettings.readDefaultAppsLPw(parser, userId);
16137                            }
16138                        }
16139                    } );
16140        } catch (Exception e) {
16141            if (DEBUG_BACKUP) {
16142                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16143            }
16144        }
16145    }
16146
16147    @Override
16148    public byte[] getIntentFilterVerificationBackup(int userId) {
16149        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16150            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16151        }
16152
16153        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16154        try {
16155            final XmlSerializer serializer = new FastXmlSerializer();
16156            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16157            serializer.startDocument(null, true);
16158            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16159
16160            synchronized (mPackages) {
16161                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16162            }
16163
16164            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16165            serializer.endDocument();
16166            serializer.flush();
16167        } catch (Exception e) {
16168            if (DEBUG_BACKUP) {
16169                Slog.e(TAG, "Unable to write default apps for backup", e);
16170            }
16171            return null;
16172        }
16173
16174        return dataStream.toByteArray();
16175    }
16176
16177    @Override
16178    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16179        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16180            throw new SecurityException("Only the system may call restorePreferredActivities()");
16181        }
16182
16183        try {
16184            final XmlPullParser parser = Xml.newPullParser();
16185            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16186            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16187                    new BlobXmlRestorer() {
16188                        @Override
16189                        public void apply(XmlPullParser parser, int userId)
16190                                throws XmlPullParserException, IOException {
16191                            synchronized (mPackages) {
16192                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16193                                mSettings.writeLPr();
16194                            }
16195                        }
16196                    } );
16197        } catch (Exception e) {
16198            if (DEBUG_BACKUP) {
16199                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16200            }
16201        }
16202    }
16203
16204    @Override
16205    public byte[] getPermissionGrantBackup(int userId) {
16206        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16207            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16208        }
16209
16210        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16211        try {
16212            final XmlSerializer serializer = new FastXmlSerializer();
16213            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16214            serializer.startDocument(null, true);
16215            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16216
16217            synchronized (mPackages) {
16218                serializeRuntimePermissionGrantsLPr(serializer, userId);
16219            }
16220
16221            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16222            serializer.endDocument();
16223            serializer.flush();
16224        } catch (Exception e) {
16225            if (DEBUG_BACKUP) {
16226                Slog.e(TAG, "Unable to write default apps for backup", e);
16227            }
16228            return null;
16229        }
16230
16231        return dataStream.toByteArray();
16232    }
16233
16234    @Override
16235    public void restorePermissionGrants(byte[] backup, int userId) {
16236        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16237            throw new SecurityException("Only the system may call restorePermissionGrants()");
16238        }
16239
16240        try {
16241            final XmlPullParser parser = Xml.newPullParser();
16242            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16243            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16244                    new BlobXmlRestorer() {
16245                        @Override
16246                        public void apply(XmlPullParser parser, int userId)
16247                                throws XmlPullParserException, IOException {
16248                            synchronized (mPackages) {
16249                                processRestoredPermissionGrantsLPr(parser, userId);
16250                            }
16251                        }
16252                    } );
16253        } catch (Exception e) {
16254            if (DEBUG_BACKUP) {
16255                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16256            }
16257        }
16258    }
16259
16260    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16261            throws IOException {
16262        serializer.startTag(null, TAG_ALL_GRANTS);
16263
16264        final int N = mSettings.mPackages.size();
16265        for (int i = 0; i < N; i++) {
16266            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16267            boolean pkgGrantsKnown = false;
16268
16269            PermissionsState packagePerms = ps.getPermissionsState();
16270
16271            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16272                final int grantFlags = state.getFlags();
16273                // only look at grants that are not system/policy fixed
16274                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16275                    final boolean isGranted = state.isGranted();
16276                    // And only back up the user-twiddled state bits
16277                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16278                        final String packageName = mSettings.mPackages.keyAt(i);
16279                        if (!pkgGrantsKnown) {
16280                            serializer.startTag(null, TAG_GRANT);
16281                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16282                            pkgGrantsKnown = true;
16283                        }
16284
16285                        final boolean userSet =
16286                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16287                        final boolean userFixed =
16288                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16289                        final boolean revoke =
16290                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16291
16292                        serializer.startTag(null, TAG_PERMISSION);
16293                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16294                        if (isGranted) {
16295                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16296                        }
16297                        if (userSet) {
16298                            serializer.attribute(null, ATTR_USER_SET, "true");
16299                        }
16300                        if (userFixed) {
16301                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16302                        }
16303                        if (revoke) {
16304                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16305                        }
16306                        serializer.endTag(null, TAG_PERMISSION);
16307                    }
16308                }
16309            }
16310
16311            if (pkgGrantsKnown) {
16312                serializer.endTag(null, TAG_GRANT);
16313            }
16314        }
16315
16316        serializer.endTag(null, TAG_ALL_GRANTS);
16317    }
16318
16319    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16320            throws XmlPullParserException, IOException {
16321        String pkgName = null;
16322        int outerDepth = parser.getDepth();
16323        int type;
16324        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16325                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16326            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16327                continue;
16328            }
16329
16330            final String tagName = parser.getName();
16331            if (tagName.equals(TAG_GRANT)) {
16332                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16333                if (DEBUG_BACKUP) {
16334                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16335                }
16336            } else if (tagName.equals(TAG_PERMISSION)) {
16337
16338                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16339                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16340
16341                int newFlagSet = 0;
16342                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16343                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16344                }
16345                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16346                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16347                }
16348                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16349                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16350                }
16351                if (DEBUG_BACKUP) {
16352                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16353                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16354                }
16355                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16356                if (ps != null) {
16357                    // Already installed so we apply the grant immediately
16358                    if (DEBUG_BACKUP) {
16359                        Slog.v(TAG, "        + already installed; applying");
16360                    }
16361                    PermissionsState perms = ps.getPermissionsState();
16362                    BasePermission bp = mSettings.mPermissions.get(permName);
16363                    if (bp != null) {
16364                        if (isGranted) {
16365                            perms.grantRuntimePermission(bp, userId);
16366                        }
16367                        if (newFlagSet != 0) {
16368                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16369                        }
16370                    }
16371                } else {
16372                    // Need to wait for post-restore install to apply the grant
16373                    if (DEBUG_BACKUP) {
16374                        Slog.v(TAG, "        - not yet installed; saving for later");
16375                    }
16376                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16377                            isGranted, newFlagSet, userId);
16378                }
16379            } else {
16380                PackageManagerService.reportSettingsProblem(Log.WARN,
16381                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16382                XmlUtils.skipCurrentTag(parser);
16383            }
16384        }
16385
16386        scheduleWriteSettingsLocked();
16387        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16388    }
16389
16390    @Override
16391    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16392            int sourceUserId, int targetUserId, int flags) {
16393        mContext.enforceCallingOrSelfPermission(
16394                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16395        int callingUid = Binder.getCallingUid();
16396        enforceOwnerRights(ownerPackage, callingUid);
16397        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16398        if (intentFilter.countActions() == 0) {
16399            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16400            return;
16401        }
16402        synchronized (mPackages) {
16403            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16404                    ownerPackage, targetUserId, flags);
16405            CrossProfileIntentResolver resolver =
16406                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16407            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16408            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16409            if (existing != null) {
16410                int size = existing.size();
16411                for (int i = 0; i < size; i++) {
16412                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16413                        return;
16414                    }
16415                }
16416            }
16417            resolver.addFilter(newFilter);
16418            scheduleWritePackageRestrictionsLocked(sourceUserId);
16419        }
16420    }
16421
16422    @Override
16423    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16424        mContext.enforceCallingOrSelfPermission(
16425                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16426        int callingUid = Binder.getCallingUid();
16427        enforceOwnerRights(ownerPackage, callingUid);
16428        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16429        synchronized (mPackages) {
16430            CrossProfileIntentResolver resolver =
16431                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16432            ArraySet<CrossProfileIntentFilter> set =
16433                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16434            for (CrossProfileIntentFilter filter : set) {
16435                if (filter.getOwnerPackage().equals(ownerPackage)) {
16436                    resolver.removeFilter(filter);
16437                }
16438            }
16439            scheduleWritePackageRestrictionsLocked(sourceUserId);
16440        }
16441    }
16442
16443    // Enforcing that callingUid is owning pkg on userId
16444    private void enforceOwnerRights(String pkg, int callingUid) {
16445        // The system owns everything.
16446        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16447            return;
16448        }
16449        int callingUserId = UserHandle.getUserId(callingUid);
16450        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16451        if (pi == null) {
16452            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16453                    + callingUserId);
16454        }
16455        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16456            throw new SecurityException("Calling uid " + callingUid
16457                    + " does not own package " + pkg);
16458        }
16459    }
16460
16461    @Override
16462    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16463        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
16464    }
16465
16466    private Intent getHomeIntent() {
16467        Intent intent = new Intent(Intent.ACTION_MAIN);
16468        intent.addCategory(Intent.CATEGORY_HOME);
16469        return intent;
16470    }
16471
16472    private IntentFilter getHomeFilter() {
16473        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
16474        filter.addCategory(Intent.CATEGORY_HOME);
16475        filter.addCategory(Intent.CATEGORY_DEFAULT);
16476        return filter;
16477    }
16478
16479    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
16480            int userId) {
16481        Intent intent  = getHomeIntent();
16482        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
16483                PackageManager.GET_META_DATA, userId);
16484        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16485                true, false, false, userId);
16486
16487        allHomeCandidates.clear();
16488        if (list != null) {
16489            for (ResolveInfo ri : list) {
16490                allHomeCandidates.add(ri);
16491            }
16492        }
16493        return (preferred == null || preferred.activityInfo == null)
16494                ? null
16495                : new ComponentName(preferred.activityInfo.packageName,
16496                        preferred.activityInfo.name);
16497    }
16498
16499    @Override
16500    public void setHomeActivity(ComponentName comp, int userId) {
16501        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
16502        getHomeActivitiesAsUser(homeActivities, userId);
16503
16504        boolean found = false;
16505
16506        final int size = homeActivities.size();
16507        final ComponentName[] set = new ComponentName[size];
16508        for (int i = 0; i < size; i++) {
16509            final ResolveInfo candidate = homeActivities.get(i);
16510            final ActivityInfo info = candidate.activityInfo;
16511            final ComponentName activityName = new ComponentName(info.packageName, info.name);
16512            set[i] = activityName;
16513            if (!found && activityName.equals(comp)) {
16514                found = true;
16515            }
16516        }
16517        if (!found) {
16518            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
16519                    + userId);
16520        }
16521        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
16522                set, comp, userId);
16523    }
16524
16525    @Override
16526    public void setApplicationEnabledSetting(String appPackageName,
16527            int newState, int flags, int userId, String callingPackage) {
16528        if (!sUserManager.exists(userId)) return;
16529        if (callingPackage == null) {
16530            callingPackage = Integer.toString(Binder.getCallingUid());
16531        }
16532        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
16533    }
16534
16535    @Override
16536    public void setComponentEnabledSetting(ComponentName componentName,
16537            int newState, int flags, int userId) {
16538        if (!sUserManager.exists(userId)) return;
16539        setEnabledSetting(componentName.getPackageName(),
16540                componentName.getClassName(), newState, flags, userId, null);
16541    }
16542
16543    private void setEnabledSetting(final String packageName, String className, int newState,
16544            final int flags, int userId, String callingPackage) {
16545        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
16546              || newState == COMPONENT_ENABLED_STATE_ENABLED
16547              || newState == COMPONENT_ENABLED_STATE_DISABLED
16548              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
16549              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
16550            throw new IllegalArgumentException("Invalid new component state: "
16551                    + newState);
16552        }
16553        PackageSetting pkgSetting;
16554        final int uid = Binder.getCallingUid();
16555        final int permission = mContext.checkCallingOrSelfPermission(
16556                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16557        enforceCrossUserPermission(uid, userId,
16558                false /* requireFullPermission */, true /* checkShell */, "set enabled");
16559        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16560        boolean sendNow = false;
16561        boolean isApp = (className == null);
16562        String componentName = isApp ? packageName : className;
16563        int packageUid = -1;
16564        ArrayList<String> components;
16565
16566        // writer
16567        synchronized (mPackages) {
16568            pkgSetting = mSettings.mPackages.get(packageName);
16569            if (pkgSetting == null) {
16570                if (className == null) {
16571                    throw new IllegalArgumentException("Unknown package: " + packageName);
16572                }
16573                throw new IllegalArgumentException(
16574                        "Unknown component: " + packageName + "/" + className);
16575            }
16576            // Allow root and verify that userId is not being specified by a different user
16577            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
16578                throw new SecurityException(
16579                        "Permission Denial: attempt to change component state from pid="
16580                        + Binder.getCallingPid()
16581                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
16582            }
16583            if (className == null) {
16584                // We're dealing with an application/package level state change
16585                if (pkgSetting.getEnabled(userId) == newState) {
16586                    // Nothing to do
16587                    return;
16588                }
16589                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
16590                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
16591                    // Don't care about who enables an app.
16592                    callingPackage = null;
16593                }
16594                pkgSetting.setEnabled(newState, userId, callingPackage);
16595                // pkgSetting.pkg.mSetEnabled = newState;
16596            } else {
16597                // We're dealing with a component level state change
16598                // First, verify that this is a valid class name.
16599                PackageParser.Package pkg = pkgSetting.pkg;
16600                if (pkg == null || !pkg.hasComponentClassName(className)) {
16601                    if (pkg != null &&
16602                            pkg.applicationInfo.targetSdkVersion >=
16603                                    Build.VERSION_CODES.JELLY_BEAN) {
16604                        throw new IllegalArgumentException("Component class " + className
16605                                + " does not exist in " + packageName);
16606                    } else {
16607                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
16608                                + className + " does not exist in " + packageName);
16609                    }
16610                }
16611                switch (newState) {
16612                case COMPONENT_ENABLED_STATE_ENABLED:
16613                    if (!pkgSetting.enableComponentLPw(className, userId)) {
16614                        return;
16615                    }
16616                    break;
16617                case COMPONENT_ENABLED_STATE_DISABLED:
16618                    if (!pkgSetting.disableComponentLPw(className, userId)) {
16619                        return;
16620                    }
16621                    break;
16622                case COMPONENT_ENABLED_STATE_DEFAULT:
16623                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
16624                        return;
16625                    }
16626                    break;
16627                default:
16628                    Slog.e(TAG, "Invalid new component state: " + newState);
16629                    return;
16630                }
16631            }
16632            scheduleWritePackageRestrictionsLocked(userId);
16633            components = mPendingBroadcasts.get(userId, packageName);
16634            final boolean newPackage = components == null;
16635            if (newPackage) {
16636                components = new ArrayList<String>();
16637            }
16638            if (!components.contains(componentName)) {
16639                components.add(componentName);
16640            }
16641            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
16642                sendNow = true;
16643                // Purge entry from pending broadcast list if another one exists already
16644                // since we are sending one right away.
16645                mPendingBroadcasts.remove(userId, packageName);
16646            } else {
16647                if (newPackage) {
16648                    mPendingBroadcasts.put(userId, packageName, components);
16649                }
16650                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
16651                    // Schedule a message
16652                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
16653                }
16654            }
16655        }
16656
16657        long callingId = Binder.clearCallingIdentity();
16658        try {
16659            if (sendNow) {
16660                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
16661                sendPackageChangedBroadcast(packageName,
16662                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
16663            }
16664        } finally {
16665            Binder.restoreCallingIdentity(callingId);
16666        }
16667    }
16668
16669    @Override
16670    public void flushPackageRestrictionsAsUser(int userId) {
16671        if (!sUserManager.exists(userId)) {
16672            return;
16673        }
16674        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
16675                false /* checkShell */, "flushPackageRestrictions");
16676        synchronized (mPackages) {
16677            mSettings.writePackageRestrictionsLPr(userId);
16678            mDirtyUsers.remove(userId);
16679            if (mDirtyUsers.isEmpty()) {
16680                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
16681            }
16682        }
16683    }
16684
16685    private void sendPackageChangedBroadcast(String packageName,
16686            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
16687        if (DEBUG_INSTALL)
16688            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
16689                    + componentNames);
16690        Bundle extras = new Bundle(4);
16691        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
16692        String nameList[] = new String[componentNames.size()];
16693        componentNames.toArray(nameList);
16694        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
16695        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
16696        extras.putInt(Intent.EXTRA_UID, packageUid);
16697        // If this is not reporting a change of the overall package, then only send it
16698        // to registered receivers.  We don't want to launch a swath of apps for every
16699        // little component state change.
16700        final int flags = !componentNames.contains(packageName)
16701                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
16702        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
16703                new int[] {UserHandle.getUserId(packageUid)});
16704    }
16705
16706    @Override
16707    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
16708        if (!sUserManager.exists(userId)) return;
16709        final int uid = Binder.getCallingUid();
16710        final int permission = mContext.checkCallingOrSelfPermission(
16711                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
16712        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
16713        enforceCrossUserPermission(uid, userId,
16714                true /* requireFullPermission */, true /* checkShell */, "stop package");
16715        // writer
16716        synchronized (mPackages) {
16717            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
16718                    allowedByPermission, uid, userId)) {
16719                scheduleWritePackageRestrictionsLocked(userId);
16720            }
16721        }
16722    }
16723
16724    @Override
16725    public String getInstallerPackageName(String packageName) {
16726        // reader
16727        synchronized (mPackages) {
16728            return mSettings.getInstallerPackageNameLPr(packageName);
16729        }
16730    }
16731
16732    @Override
16733    public int getApplicationEnabledSetting(String packageName, int userId) {
16734        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16735        int uid = Binder.getCallingUid();
16736        enforceCrossUserPermission(uid, userId,
16737                false /* requireFullPermission */, false /* checkShell */, "get enabled");
16738        // reader
16739        synchronized (mPackages) {
16740            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
16741        }
16742    }
16743
16744    @Override
16745    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
16746        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
16747        int uid = Binder.getCallingUid();
16748        enforceCrossUserPermission(uid, userId,
16749                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
16750        // reader
16751        synchronized (mPackages) {
16752            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
16753        }
16754    }
16755
16756    @Override
16757    public void enterSafeMode() {
16758        enforceSystemOrRoot("Only the system can request entering safe mode");
16759
16760        if (!mSystemReady) {
16761            mSafeMode = true;
16762        }
16763    }
16764
16765    @Override
16766    public void systemReady() {
16767        mSystemReady = true;
16768
16769        // Read the compatibilty setting when the system is ready.
16770        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
16771                mContext.getContentResolver(),
16772                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
16773        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
16774        if (DEBUG_SETTINGS) {
16775            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
16776        }
16777
16778        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
16779
16780        synchronized (mPackages) {
16781            // Verify that all of the preferred activity components actually
16782            // exist.  It is possible for applications to be updated and at
16783            // that point remove a previously declared activity component that
16784            // had been set as a preferred activity.  We try to clean this up
16785            // the next time we encounter that preferred activity, but it is
16786            // possible for the user flow to never be able to return to that
16787            // situation so here we do a sanity check to make sure we haven't
16788            // left any junk around.
16789            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
16790            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16791                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16792                removed.clear();
16793                for (PreferredActivity pa : pir.filterSet()) {
16794                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
16795                        removed.add(pa);
16796                    }
16797                }
16798                if (removed.size() > 0) {
16799                    for (int r=0; r<removed.size(); r++) {
16800                        PreferredActivity pa = removed.get(r);
16801                        Slog.w(TAG, "Removing dangling preferred activity: "
16802                                + pa.mPref.mComponent);
16803                        pir.removeFilter(pa);
16804                    }
16805                    mSettings.writePackageRestrictionsLPr(
16806                            mSettings.mPreferredActivities.keyAt(i));
16807                }
16808            }
16809
16810            for (int userId : UserManagerService.getInstance().getUserIds()) {
16811                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
16812                    grantPermissionsUserIds = ArrayUtils.appendInt(
16813                            grantPermissionsUserIds, userId);
16814                }
16815            }
16816        }
16817        sUserManager.systemReady();
16818
16819        // If we upgraded grant all default permissions before kicking off.
16820        for (int userId : grantPermissionsUserIds) {
16821            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
16822        }
16823
16824        // Kick off any messages waiting for system ready
16825        if (mPostSystemReadyMessages != null) {
16826            for (Message msg : mPostSystemReadyMessages) {
16827                msg.sendToTarget();
16828            }
16829            mPostSystemReadyMessages = null;
16830        }
16831
16832        // Watch for external volumes that come and go over time
16833        final StorageManager storage = mContext.getSystemService(StorageManager.class);
16834        storage.registerListener(mStorageListener);
16835
16836        mInstallerService.systemReady();
16837        mPackageDexOptimizer.systemReady();
16838
16839        MountServiceInternal mountServiceInternal = LocalServices.getService(
16840                MountServiceInternal.class);
16841        mountServiceInternal.addExternalStoragePolicy(
16842                new MountServiceInternal.ExternalStorageMountPolicy() {
16843            @Override
16844            public int getMountMode(int uid, String packageName) {
16845                if (Process.isIsolated(uid)) {
16846                    return Zygote.MOUNT_EXTERNAL_NONE;
16847                }
16848                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
16849                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16850                }
16851                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16852                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
16853                }
16854                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
16855                    return Zygote.MOUNT_EXTERNAL_READ;
16856                }
16857                return Zygote.MOUNT_EXTERNAL_WRITE;
16858            }
16859
16860            @Override
16861            public boolean hasExternalStorage(int uid, String packageName) {
16862                return true;
16863            }
16864        });
16865    }
16866
16867    @Override
16868    public boolean isSafeMode() {
16869        return mSafeMode;
16870    }
16871
16872    @Override
16873    public boolean hasSystemUidErrors() {
16874        return mHasSystemUidErrors;
16875    }
16876
16877    static String arrayToString(int[] array) {
16878        StringBuffer buf = new StringBuffer(128);
16879        buf.append('[');
16880        if (array != null) {
16881            for (int i=0; i<array.length; i++) {
16882                if (i > 0) buf.append(", ");
16883                buf.append(array[i]);
16884            }
16885        }
16886        buf.append(']');
16887        return buf.toString();
16888    }
16889
16890    static class DumpState {
16891        public static final int DUMP_LIBS = 1 << 0;
16892        public static final int DUMP_FEATURES = 1 << 1;
16893        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
16894        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
16895        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
16896        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
16897        public static final int DUMP_PERMISSIONS = 1 << 6;
16898        public static final int DUMP_PACKAGES = 1 << 7;
16899        public static final int DUMP_SHARED_USERS = 1 << 8;
16900        public static final int DUMP_MESSAGES = 1 << 9;
16901        public static final int DUMP_PROVIDERS = 1 << 10;
16902        public static final int DUMP_VERIFIERS = 1 << 11;
16903        public static final int DUMP_PREFERRED = 1 << 12;
16904        public static final int DUMP_PREFERRED_XML = 1 << 13;
16905        public static final int DUMP_KEYSETS = 1 << 14;
16906        public static final int DUMP_VERSION = 1 << 15;
16907        public static final int DUMP_INSTALLS = 1 << 16;
16908        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
16909        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
16910
16911        public static final int OPTION_SHOW_FILTERS = 1 << 0;
16912
16913        private int mTypes;
16914
16915        private int mOptions;
16916
16917        private boolean mTitlePrinted;
16918
16919        private SharedUserSetting mSharedUser;
16920
16921        public boolean isDumping(int type) {
16922            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
16923                return true;
16924            }
16925
16926            return (mTypes & type) != 0;
16927        }
16928
16929        public void setDump(int type) {
16930            mTypes |= type;
16931        }
16932
16933        public boolean isOptionEnabled(int option) {
16934            return (mOptions & option) != 0;
16935        }
16936
16937        public void setOptionEnabled(int option) {
16938            mOptions |= option;
16939        }
16940
16941        public boolean onTitlePrinted() {
16942            final boolean printed = mTitlePrinted;
16943            mTitlePrinted = true;
16944            return printed;
16945        }
16946
16947        public boolean getTitlePrinted() {
16948            return mTitlePrinted;
16949        }
16950
16951        public void setTitlePrinted(boolean enabled) {
16952            mTitlePrinted = enabled;
16953        }
16954
16955        public SharedUserSetting getSharedUser() {
16956            return mSharedUser;
16957        }
16958
16959        public void setSharedUser(SharedUserSetting user) {
16960            mSharedUser = user;
16961        }
16962    }
16963
16964    @Override
16965    public void onShellCommand(FileDescriptor in, FileDescriptor out,
16966            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
16967        (new PackageManagerShellCommand(this)).exec(
16968                this, in, out, err, args, resultReceiver);
16969    }
16970
16971    @Override
16972    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
16973        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
16974                != PackageManager.PERMISSION_GRANTED) {
16975            pw.println("Permission Denial: can't dump ActivityManager from from pid="
16976                    + Binder.getCallingPid()
16977                    + ", uid=" + Binder.getCallingUid()
16978                    + " without permission "
16979                    + android.Manifest.permission.DUMP);
16980            return;
16981        }
16982
16983        DumpState dumpState = new DumpState();
16984        boolean fullPreferred = false;
16985        boolean checkin = false;
16986
16987        String packageName = null;
16988        ArraySet<String> permissionNames = null;
16989
16990        int opti = 0;
16991        while (opti < args.length) {
16992            String opt = args[opti];
16993            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
16994                break;
16995            }
16996            opti++;
16997
16998            if ("-a".equals(opt)) {
16999                // Right now we only know how to print all.
17000            } else if ("-h".equals(opt)) {
17001                pw.println("Package manager dump options:");
17002                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17003                pw.println("    --checkin: dump for a checkin");
17004                pw.println("    -f: print details of intent filters");
17005                pw.println("    -h: print this help");
17006                pw.println("  cmd may be one of:");
17007                pw.println("    l[ibraries]: list known shared libraries");
17008                pw.println("    f[eatures]: list device features");
17009                pw.println("    k[eysets]: print known keysets");
17010                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17011                pw.println("    perm[issions]: dump permissions");
17012                pw.println("    permission [name ...]: dump declaration and use of given permission");
17013                pw.println("    pref[erred]: print preferred package settings");
17014                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17015                pw.println("    prov[iders]: dump content providers");
17016                pw.println("    p[ackages]: dump installed packages");
17017                pw.println("    s[hared-users]: dump shared user IDs");
17018                pw.println("    m[essages]: print collected runtime messages");
17019                pw.println("    v[erifiers]: print package verifier info");
17020                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17021                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17022                pw.println("    version: print database version info");
17023                pw.println("    write: write current settings now");
17024                pw.println("    installs: details about install sessions");
17025                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17026                pw.println("    <package.name>: info about given package");
17027                return;
17028            } else if ("--checkin".equals(opt)) {
17029                checkin = true;
17030            } else if ("-f".equals(opt)) {
17031                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17032            } else {
17033                pw.println("Unknown argument: " + opt + "; use -h for help");
17034            }
17035        }
17036
17037        // Is the caller requesting to dump a particular piece of data?
17038        if (opti < args.length) {
17039            String cmd = args[opti];
17040            opti++;
17041            // Is this a package name?
17042            if ("android".equals(cmd) || cmd.contains(".")) {
17043                packageName = cmd;
17044                // When dumping a single package, we always dump all of its
17045                // filter information since the amount of data will be reasonable.
17046                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17047            } else if ("check-permission".equals(cmd)) {
17048                if (opti >= args.length) {
17049                    pw.println("Error: check-permission missing permission argument");
17050                    return;
17051                }
17052                String perm = args[opti];
17053                opti++;
17054                if (opti >= args.length) {
17055                    pw.println("Error: check-permission missing package argument");
17056                    return;
17057                }
17058                String pkg = args[opti];
17059                opti++;
17060                int user = UserHandle.getUserId(Binder.getCallingUid());
17061                if (opti < args.length) {
17062                    try {
17063                        user = Integer.parseInt(args[opti]);
17064                    } catch (NumberFormatException e) {
17065                        pw.println("Error: check-permission user argument is not a number: "
17066                                + args[opti]);
17067                        return;
17068                    }
17069                }
17070                pw.println(checkPermission(perm, pkg, user));
17071                return;
17072            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17073                dumpState.setDump(DumpState.DUMP_LIBS);
17074            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17075                dumpState.setDump(DumpState.DUMP_FEATURES);
17076            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17077                if (opti >= args.length) {
17078                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17079                            | DumpState.DUMP_SERVICE_RESOLVERS
17080                            | DumpState.DUMP_RECEIVER_RESOLVERS
17081                            | DumpState.DUMP_CONTENT_RESOLVERS);
17082                } else {
17083                    while (opti < args.length) {
17084                        String name = args[opti];
17085                        if ("a".equals(name) || "activity".equals(name)) {
17086                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17087                        } else if ("s".equals(name) || "service".equals(name)) {
17088                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17089                        } else if ("r".equals(name) || "receiver".equals(name)) {
17090                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17091                        } else if ("c".equals(name) || "content".equals(name)) {
17092                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17093                        } else {
17094                            pw.println("Error: unknown resolver table type: " + name);
17095                            return;
17096                        }
17097                        opti++;
17098                    }
17099                }
17100            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17101                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17102            } else if ("permission".equals(cmd)) {
17103                if (opti >= args.length) {
17104                    pw.println("Error: permission requires permission name");
17105                    return;
17106                }
17107                permissionNames = new ArraySet<>();
17108                while (opti < args.length) {
17109                    permissionNames.add(args[opti]);
17110                    opti++;
17111                }
17112                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17113                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17114            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17115                dumpState.setDump(DumpState.DUMP_PREFERRED);
17116            } else if ("preferred-xml".equals(cmd)) {
17117                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17118                if (opti < args.length && "--full".equals(args[opti])) {
17119                    fullPreferred = true;
17120                    opti++;
17121                }
17122            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17123                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17124            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17125                dumpState.setDump(DumpState.DUMP_PACKAGES);
17126            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17127                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17128            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17129                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17130            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17131                dumpState.setDump(DumpState.DUMP_MESSAGES);
17132            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17133                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17134            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17135                    || "intent-filter-verifiers".equals(cmd)) {
17136                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17137            } else if ("version".equals(cmd)) {
17138                dumpState.setDump(DumpState.DUMP_VERSION);
17139            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17140                dumpState.setDump(DumpState.DUMP_KEYSETS);
17141            } else if ("installs".equals(cmd)) {
17142                dumpState.setDump(DumpState.DUMP_INSTALLS);
17143            } else if ("write".equals(cmd)) {
17144                synchronized (mPackages) {
17145                    mSettings.writeLPr();
17146                    pw.println("Settings written.");
17147                    return;
17148                }
17149            }
17150        }
17151
17152        if (checkin) {
17153            pw.println("vers,1");
17154        }
17155
17156        // reader
17157        synchronized (mPackages) {
17158            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17159                if (!checkin) {
17160                    if (dumpState.onTitlePrinted())
17161                        pw.println();
17162                    pw.println("Database versions:");
17163                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17164                }
17165            }
17166
17167            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17168                if (!checkin) {
17169                    if (dumpState.onTitlePrinted())
17170                        pw.println();
17171                    pw.println("Verifiers:");
17172                    pw.print("  Required: ");
17173                    pw.print(mRequiredVerifierPackage);
17174                    pw.print(" (uid=");
17175                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17176                            UserHandle.USER_SYSTEM));
17177                    pw.println(")");
17178                } else if (mRequiredVerifierPackage != null) {
17179                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17180                    pw.print(",");
17181                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17182                            UserHandle.USER_SYSTEM));
17183                }
17184            }
17185
17186            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17187                    packageName == null) {
17188                if (mIntentFilterVerifierComponent != null) {
17189                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17190                    if (!checkin) {
17191                        if (dumpState.onTitlePrinted())
17192                            pw.println();
17193                        pw.println("Intent Filter Verifier:");
17194                        pw.print("  Using: ");
17195                        pw.print(verifierPackageName);
17196                        pw.print(" (uid=");
17197                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17198                                UserHandle.USER_SYSTEM));
17199                        pw.println(")");
17200                    } else if (verifierPackageName != null) {
17201                        pw.print("ifv,"); pw.print(verifierPackageName);
17202                        pw.print(",");
17203                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17204                                UserHandle.USER_SYSTEM));
17205                    }
17206                } else {
17207                    pw.println();
17208                    pw.println("No Intent Filter Verifier available!");
17209                }
17210            }
17211
17212            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17213                boolean printedHeader = false;
17214                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17215                while (it.hasNext()) {
17216                    String name = it.next();
17217                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17218                    if (!checkin) {
17219                        if (!printedHeader) {
17220                            if (dumpState.onTitlePrinted())
17221                                pw.println();
17222                            pw.println("Libraries:");
17223                            printedHeader = true;
17224                        }
17225                        pw.print("  ");
17226                    } else {
17227                        pw.print("lib,");
17228                    }
17229                    pw.print(name);
17230                    if (!checkin) {
17231                        pw.print(" -> ");
17232                    }
17233                    if (ent.path != null) {
17234                        if (!checkin) {
17235                            pw.print("(jar) ");
17236                            pw.print(ent.path);
17237                        } else {
17238                            pw.print(",jar,");
17239                            pw.print(ent.path);
17240                        }
17241                    } else {
17242                        if (!checkin) {
17243                            pw.print("(apk) ");
17244                            pw.print(ent.apk);
17245                        } else {
17246                            pw.print(",apk,");
17247                            pw.print(ent.apk);
17248                        }
17249                    }
17250                    pw.println();
17251                }
17252            }
17253
17254            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17255                if (dumpState.onTitlePrinted())
17256                    pw.println();
17257                if (!checkin) {
17258                    pw.println("Features:");
17259                }
17260
17261                for (FeatureInfo feat : mAvailableFeatures.values()) {
17262                    if (checkin) {
17263                        pw.print("feat,");
17264                        pw.print(feat.name);
17265                        pw.print(",");
17266                        pw.println(feat.version);
17267                    } else {
17268                        pw.print("  ");
17269                        pw.print(feat.name);
17270                        if (feat.version > 0) {
17271                            pw.print(" version=");
17272                            pw.print(feat.version);
17273                        }
17274                        pw.println();
17275                    }
17276                }
17277            }
17278
17279            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17280                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17281                        : "Activity Resolver Table:", "  ", packageName,
17282                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17283                    dumpState.setTitlePrinted(true);
17284                }
17285            }
17286            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17287                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17288                        : "Receiver Resolver Table:", "  ", packageName,
17289                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17290                    dumpState.setTitlePrinted(true);
17291                }
17292            }
17293            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17294                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17295                        : "Service Resolver Table:", "  ", packageName,
17296                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17297                    dumpState.setTitlePrinted(true);
17298                }
17299            }
17300            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17301                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17302                        : "Provider Resolver Table:", "  ", packageName,
17303                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17304                    dumpState.setTitlePrinted(true);
17305                }
17306            }
17307
17308            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17309                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17310                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17311                    int user = mSettings.mPreferredActivities.keyAt(i);
17312                    if (pir.dump(pw,
17313                            dumpState.getTitlePrinted()
17314                                ? "\nPreferred Activities User " + user + ":"
17315                                : "Preferred Activities User " + user + ":", "  ",
17316                            packageName, true, false)) {
17317                        dumpState.setTitlePrinted(true);
17318                    }
17319                }
17320            }
17321
17322            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17323                pw.flush();
17324                FileOutputStream fout = new FileOutputStream(fd);
17325                BufferedOutputStream str = new BufferedOutputStream(fout);
17326                XmlSerializer serializer = new FastXmlSerializer();
17327                try {
17328                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17329                    serializer.startDocument(null, true);
17330                    serializer.setFeature(
17331                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17332                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17333                    serializer.endDocument();
17334                    serializer.flush();
17335                } catch (IllegalArgumentException e) {
17336                    pw.println("Failed writing: " + e);
17337                } catch (IllegalStateException e) {
17338                    pw.println("Failed writing: " + e);
17339                } catch (IOException e) {
17340                    pw.println("Failed writing: " + e);
17341                }
17342            }
17343
17344            if (!checkin
17345                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17346                    && packageName == null) {
17347                pw.println();
17348                int count = mSettings.mPackages.size();
17349                if (count == 0) {
17350                    pw.println("No applications!");
17351                    pw.println();
17352                } else {
17353                    final String prefix = "  ";
17354                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17355                    if (allPackageSettings.size() == 0) {
17356                        pw.println("No domain preferred apps!");
17357                        pw.println();
17358                    } else {
17359                        pw.println("App verification status:");
17360                        pw.println();
17361                        count = 0;
17362                        for (PackageSetting ps : allPackageSettings) {
17363                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17364                            if (ivi == null || ivi.getPackageName() == null) continue;
17365                            pw.println(prefix + "Package: " + ivi.getPackageName());
17366                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17367                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17368                            pw.println();
17369                            count++;
17370                        }
17371                        if (count == 0) {
17372                            pw.println(prefix + "No app verification established.");
17373                            pw.println();
17374                        }
17375                        for (int userId : sUserManager.getUserIds()) {
17376                            pw.println("App linkages for user " + userId + ":");
17377                            pw.println();
17378                            count = 0;
17379                            for (PackageSetting ps : allPackageSettings) {
17380                                final long status = ps.getDomainVerificationStatusForUser(userId);
17381                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17382                                    continue;
17383                                }
17384                                pw.println(prefix + "Package: " + ps.name);
17385                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17386                                String statusStr = IntentFilterVerificationInfo.
17387                                        getStatusStringFromValue(status);
17388                                pw.println(prefix + "Status:  " + statusStr);
17389                                pw.println();
17390                                count++;
17391                            }
17392                            if (count == 0) {
17393                                pw.println(prefix + "No configured app linkages.");
17394                                pw.println();
17395                            }
17396                        }
17397                    }
17398                }
17399            }
17400
17401            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17402                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17403                if (packageName == null && permissionNames == null) {
17404                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17405                        if (iperm == 0) {
17406                            if (dumpState.onTitlePrinted())
17407                                pw.println();
17408                            pw.println("AppOp Permissions:");
17409                        }
17410                        pw.print("  AppOp Permission ");
17411                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17412                        pw.println(":");
17413                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17414                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17415                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17416                        }
17417                    }
17418                }
17419            }
17420
17421            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17422                boolean printedSomething = false;
17423                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17424                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17425                        continue;
17426                    }
17427                    if (!printedSomething) {
17428                        if (dumpState.onTitlePrinted())
17429                            pw.println();
17430                        pw.println("Registered ContentProviders:");
17431                        printedSomething = true;
17432                    }
17433                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17434                    pw.print("    "); pw.println(p.toString());
17435                }
17436                printedSomething = false;
17437                for (Map.Entry<String, PackageParser.Provider> entry :
17438                        mProvidersByAuthority.entrySet()) {
17439                    PackageParser.Provider p = entry.getValue();
17440                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17441                        continue;
17442                    }
17443                    if (!printedSomething) {
17444                        if (dumpState.onTitlePrinted())
17445                            pw.println();
17446                        pw.println("ContentProvider Authorities:");
17447                        printedSomething = true;
17448                    }
17449                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17450                    pw.print("    "); pw.println(p.toString());
17451                    if (p.info != null && p.info.applicationInfo != null) {
17452                        final String appInfo = p.info.applicationInfo.toString();
17453                        pw.print("      applicationInfo="); pw.println(appInfo);
17454                    }
17455                }
17456            }
17457
17458            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17459                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17460            }
17461
17462            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17463                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17464            }
17465
17466            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17467                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17468            }
17469
17470            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17471                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17472            }
17473
17474            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17475                // XXX should handle packageName != null by dumping only install data that
17476                // the given package is involved with.
17477                if (dumpState.onTitlePrinted()) pw.println();
17478                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17479            }
17480
17481            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17482                if (dumpState.onTitlePrinted()) pw.println();
17483                mSettings.dumpReadMessagesLPr(pw, dumpState);
17484
17485                pw.println();
17486                pw.println("Package warning messages:");
17487                BufferedReader in = null;
17488                String line = null;
17489                try {
17490                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17491                    while ((line = in.readLine()) != null) {
17492                        if (line.contains("ignored: updated version")) continue;
17493                        pw.println(line);
17494                    }
17495                } catch (IOException ignored) {
17496                } finally {
17497                    IoUtils.closeQuietly(in);
17498                }
17499            }
17500
17501            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
17502                BufferedReader in = null;
17503                String line = null;
17504                try {
17505                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17506                    while ((line = in.readLine()) != null) {
17507                        if (line.contains("ignored: updated version")) continue;
17508                        pw.print("msg,");
17509                        pw.println(line);
17510                    }
17511                } catch (IOException ignored) {
17512                } finally {
17513                    IoUtils.closeQuietly(in);
17514                }
17515            }
17516        }
17517    }
17518
17519    private String dumpDomainString(String packageName) {
17520        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
17521                .getList();
17522        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
17523
17524        ArraySet<String> result = new ArraySet<>();
17525        if (iviList.size() > 0) {
17526            for (IntentFilterVerificationInfo ivi : iviList) {
17527                for (String host : ivi.getDomains()) {
17528                    result.add(host);
17529                }
17530            }
17531        }
17532        if (filters != null && filters.size() > 0) {
17533            for (IntentFilter filter : filters) {
17534                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
17535                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
17536                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
17537                    result.addAll(filter.getHostsList());
17538                }
17539            }
17540        }
17541
17542        StringBuilder sb = new StringBuilder(result.size() * 16);
17543        for (String domain : result) {
17544            if (sb.length() > 0) sb.append(" ");
17545            sb.append(domain);
17546        }
17547        return sb.toString();
17548    }
17549
17550    // ------- apps on sdcard specific code -------
17551    static final boolean DEBUG_SD_INSTALL = false;
17552
17553    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
17554
17555    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
17556
17557    private boolean mMediaMounted = false;
17558
17559    static String getEncryptKey() {
17560        try {
17561            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
17562                    SD_ENCRYPTION_KEYSTORE_NAME);
17563            if (sdEncKey == null) {
17564                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
17565                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
17566                if (sdEncKey == null) {
17567                    Slog.e(TAG, "Failed to create encryption keys");
17568                    return null;
17569                }
17570            }
17571            return sdEncKey;
17572        } catch (NoSuchAlgorithmException nsae) {
17573            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
17574            return null;
17575        } catch (IOException ioe) {
17576            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
17577            return null;
17578        }
17579    }
17580
17581    /*
17582     * Update media status on PackageManager.
17583     */
17584    @Override
17585    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
17586        int callingUid = Binder.getCallingUid();
17587        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
17588            throw new SecurityException("Media status can only be updated by the system");
17589        }
17590        // reader; this apparently protects mMediaMounted, but should probably
17591        // be a different lock in that case.
17592        synchronized (mPackages) {
17593            Log.i(TAG, "Updating external media status from "
17594                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
17595                    + (mediaStatus ? "mounted" : "unmounted"));
17596            if (DEBUG_SD_INSTALL)
17597                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
17598                        + ", mMediaMounted=" + mMediaMounted);
17599            if (mediaStatus == mMediaMounted) {
17600                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
17601                        : 0, -1);
17602                mHandler.sendMessage(msg);
17603                return;
17604            }
17605            mMediaMounted = mediaStatus;
17606        }
17607        // Queue up an async operation since the package installation may take a
17608        // little while.
17609        mHandler.post(new Runnable() {
17610            public void run() {
17611                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
17612            }
17613        });
17614    }
17615
17616    /**
17617     * Called by MountService when the initial ASECs to scan are available.
17618     * Should block until all the ASEC containers are finished being scanned.
17619     */
17620    public void scanAvailableAsecs() {
17621        updateExternalMediaStatusInner(true, false, false);
17622    }
17623
17624    /*
17625     * Collect information of applications on external media, map them against
17626     * existing containers and update information based on current mount status.
17627     * Please note that we always have to report status if reportStatus has been
17628     * set to true especially when unloading packages.
17629     */
17630    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
17631            boolean externalStorage) {
17632        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
17633        int[] uidArr = EmptyArray.INT;
17634
17635        final String[] list = PackageHelper.getSecureContainerList();
17636        if (ArrayUtils.isEmpty(list)) {
17637            Log.i(TAG, "No secure containers found");
17638        } else {
17639            // Process list of secure containers and categorize them
17640            // as active or stale based on their package internal state.
17641
17642            // reader
17643            synchronized (mPackages) {
17644                for (String cid : list) {
17645                    // Leave stages untouched for now; installer service owns them
17646                    if (PackageInstallerService.isStageName(cid)) continue;
17647
17648                    if (DEBUG_SD_INSTALL)
17649                        Log.i(TAG, "Processing container " + cid);
17650                    String pkgName = getAsecPackageName(cid);
17651                    if (pkgName == null) {
17652                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
17653                        continue;
17654                    }
17655                    if (DEBUG_SD_INSTALL)
17656                        Log.i(TAG, "Looking for pkg : " + pkgName);
17657
17658                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
17659                    if (ps == null) {
17660                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
17661                        continue;
17662                    }
17663
17664                    /*
17665                     * Skip packages that are not external if we're unmounting
17666                     * external storage.
17667                     */
17668                    if (externalStorage && !isMounted && !isExternal(ps)) {
17669                        continue;
17670                    }
17671
17672                    final AsecInstallArgs args = new AsecInstallArgs(cid,
17673                            getAppDexInstructionSets(ps), ps.isForwardLocked());
17674                    // The package status is changed only if the code path
17675                    // matches between settings and the container id.
17676                    if (ps.codePathString != null
17677                            && ps.codePathString.startsWith(args.getCodePath())) {
17678                        if (DEBUG_SD_INSTALL) {
17679                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
17680                                    + " at code path: " + ps.codePathString);
17681                        }
17682
17683                        // We do have a valid package installed on sdcard
17684                        processCids.put(args, ps.codePathString);
17685                        final int uid = ps.appId;
17686                        if (uid != -1) {
17687                            uidArr = ArrayUtils.appendInt(uidArr, uid);
17688                        }
17689                    } else {
17690                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
17691                                + ps.codePathString);
17692                    }
17693                }
17694            }
17695
17696            Arrays.sort(uidArr);
17697        }
17698
17699        // Process packages with valid entries.
17700        if (isMounted) {
17701            if (DEBUG_SD_INSTALL)
17702                Log.i(TAG, "Loading packages");
17703            loadMediaPackages(processCids, uidArr, externalStorage);
17704            startCleaningPackages();
17705            mInstallerService.onSecureContainersAvailable();
17706        } else {
17707            if (DEBUG_SD_INSTALL)
17708                Log.i(TAG, "Unloading packages");
17709            unloadMediaPackages(processCids, uidArr, reportStatus);
17710        }
17711    }
17712
17713    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17714            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
17715        final int size = infos.size();
17716        final String[] packageNames = new String[size];
17717        final int[] packageUids = new int[size];
17718        for (int i = 0; i < size; i++) {
17719            final ApplicationInfo info = infos.get(i);
17720            packageNames[i] = info.packageName;
17721            packageUids[i] = info.uid;
17722        }
17723        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
17724                finishedReceiver);
17725    }
17726
17727    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17728            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17729        sendResourcesChangedBroadcast(mediaStatus, replacing,
17730                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
17731    }
17732
17733    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
17734            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
17735        int size = pkgList.length;
17736        if (size > 0) {
17737            // Send broadcasts here
17738            Bundle extras = new Bundle();
17739            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
17740            if (uidArr != null) {
17741                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
17742            }
17743            if (replacing) {
17744                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
17745            }
17746            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
17747                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
17748            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
17749        }
17750    }
17751
17752   /*
17753     * Look at potentially valid container ids from processCids If package
17754     * information doesn't match the one on record or package scanning fails,
17755     * the cid is added to list of removeCids. We currently don't delete stale
17756     * containers.
17757     */
17758    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
17759            boolean externalStorage) {
17760        ArrayList<String> pkgList = new ArrayList<String>();
17761        Set<AsecInstallArgs> keys = processCids.keySet();
17762
17763        for (AsecInstallArgs args : keys) {
17764            String codePath = processCids.get(args);
17765            if (DEBUG_SD_INSTALL)
17766                Log.i(TAG, "Loading container : " + args.cid);
17767            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
17768            try {
17769                // Make sure there are no container errors first.
17770                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
17771                    Slog.e(TAG, "Failed to mount cid : " + args.cid
17772                            + " when installing from sdcard");
17773                    continue;
17774                }
17775                // Check code path here.
17776                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
17777                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
17778                            + " does not match one in settings " + codePath);
17779                    continue;
17780                }
17781                // Parse package
17782                int parseFlags = mDefParseFlags;
17783                if (args.isExternalAsec()) {
17784                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
17785                }
17786                if (args.isFwdLocked()) {
17787                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
17788                }
17789
17790                synchronized (mInstallLock) {
17791                    PackageParser.Package pkg = null;
17792                    try {
17793                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
17794                    } catch (PackageManagerException e) {
17795                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
17796                    }
17797                    // Scan the package
17798                    if (pkg != null) {
17799                        /*
17800                         * TODO why is the lock being held? doPostInstall is
17801                         * called in other places without the lock. This needs
17802                         * to be straightened out.
17803                         */
17804                        // writer
17805                        synchronized (mPackages) {
17806                            retCode = PackageManager.INSTALL_SUCCEEDED;
17807                            pkgList.add(pkg.packageName);
17808                            // Post process args
17809                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
17810                                    pkg.applicationInfo.uid);
17811                        }
17812                    } else {
17813                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
17814                    }
17815                }
17816
17817            } finally {
17818                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
17819                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
17820                }
17821            }
17822        }
17823        // writer
17824        synchronized (mPackages) {
17825            // If the platform SDK has changed since the last time we booted,
17826            // we need to re-grant app permission to catch any new ones that
17827            // appear. This is really a hack, and means that apps can in some
17828            // cases get permissions that the user didn't initially explicitly
17829            // allow... it would be nice to have some better way to handle
17830            // this situation.
17831            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
17832                    : mSettings.getInternalVersion();
17833            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
17834                    : StorageManager.UUID_PRIVATE_INTERNAL;
17835
17836            int updateFlags = UPDATE_PERMISSIONS_ALL;
17837            if (ver.sdkVersion != mSdkVersion) {
17838                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17839                        + mSdkVersion + "; regranting permissions for external");
17840                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
17841            }
17842            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
17843
17844            // Yay, everything is now upgraded
17845            ver.forceCurrent();
17846
17847            // can downgrade to reader
17848            // Persist settings
17849            mSettings.writeLPr();
17850        }
17851        // Send a broadcast to let everyone know we are done processing
17852        if (pkgList.size() > 0) {
17853            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
17854        }
17855    }
17856
17857   /*
17858     * Utility method to unload a list of specified containers
17859     */
17860    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
17861        // Just unmount all valid containers.
17862        for (AsecInstallArgs arg : cidArgs) {
17863            synchronized (mInstallLock) {
17864                arg.doPostDeleteLI(false);
17865           }
17866       }
17867   }
17868
17869    /*
17870     * Unload packages mounted on external media. This involves deleting package
17871     * data from internal structures, sending broadcasts about disabled packages,
17872     * gc'ing to free up references, unmounting all secure containers
17873     * corresponding to packages on external media, and posting a
17874     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
17875     * that we always have to post this message if status has been requested no
17876     * matter what.
17877     */
17878    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
17879            final boolean reportStatus) {
17880        if (DEBUG_SD_INSTALL)
17881            Log.i(TAG, "unloading media packages");
17882        ArrayList<String> pkgList = new ArrayList<String>();
17883        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
17884        final Set<AsecInstallArgs> keys = processCids.keySet();
17885        for (AsecInstallArgs args : keys) {
17886            String pkgName = args.getPackageName();
17887            if (DEBUG_SD_INSTALL)
17888                Log.i(TAG, "Trying to unload pkg : " + pkgName);
17889            // Delete package internally
17890            PackageRemovedInfo outInfo = new PackageRemovedInfo();
17891            synchronized (mInstallLock) {
17892                boolean res = deletePackageLI(pkgName, null, false, null,
17893                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
17894                if (res) {
17895                    pkgList.add(pkgName);
17896                } else {
17897                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
17898                    failedList.add(args);
17899                }
17900            }
17901        }
17902
17903        // reader
17904        synchronized (mPackages) {
17905            // We didn't update the settings after removing each package;
17906            // write them now for all packages.
17907            mSettings.writeLPr();
17908        }
17909
17910        // We have to absolutely send UPDATED_MEDIA_STATUS only
17911        // after confirming that all the receivers processed the ordered
17912        // broadcast when packages get disabled, force a gc to clean things up.
17913        // and unload all the containers.
17914        if (pkgList.size() > 0) {
17915            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
17916                    new IIntentReceiver.Stub() {
17917                public void performReceive(Intent intent, int resultCode, String data,
17918                        Bundle extras, boolean ordered, boolean sticky,
17919                        int sendingUser) throws RemoteException {
17920                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
17921                            reportStatus ? 1 : 0, 1, keys);
17922                    mHandler.sendMessage(msg);
17923                }
17924            });
17925        } else {
17926            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
17927                    keys);
17928            mHandler.sendMessage(msg);
17929        }
17930    }
17931
17932    private void loadPrivatePackages(final VolumeInfo vol) {
17933        mHandler.post(new Runnable() {
17934            @Override
17935            public void run() {
17936                loadPrivatePackagesInner(vol);
17937            }
17938        });
17939    }
17940
17941    private void loadPrivatePackagesInner(VolumeInfo vol) {
17942        final String volumeUuid = vol.fsUuid;
17943        if (TextUtils.isEmpty(volumeUuid)) {
17944            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
17945            return;
17946        }
17947
17948        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
17949        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
17950
17951        final VersionInfo ver;
17952        final List<PackageSetting> packages;
17953        synchronized (mPackages) {
17954            ver = mSettings.findOrCreateVersion(volumeUuid);
17955            packages = mSettings.getVolumePackagesLPr(volumeUuid);
17956        }
17957
17958        // TODO: introduce a new concept similar to "frozen" to prevent these
17959        // apps from being launched until after data has been fully reconciled
17960        for (PackageSetting ps : packages) {
17961            synchronized (mInstallLock) {
17962                final PackageParser.Package pkg;
17963                try {
17964                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
17965                    loaded.add(pkg.applicationInfo);
17966
17967                } catch (PackageManagerException e) {
17968                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
17969                }
17970
17971                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
17972                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
17973                }
17974            }
17975        }
17976
17977        // Reconcile app data for all started/unlocked users
17978        final StorageManager sm = mContext.getSystemService(StorageManager.class);
17979        final UserManager um = mContext.getSystemService(UserManager.class);
17980        for (UserInfo user : um.getUsers()) {
17981            final int flags;
17982            if (um.isUserUnlocked(user.id)) {
17983                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
17984            } else if (um.isUserRunning(user.id)) {
17985                flags = StorageManager.FLAG_STORAGE_DE;
17986            } else {
17987                continue;
17988            }
17989
17990            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
17991            reconcileAppsData(volumeUuid, user.id, flags);
17992        }
17993
17994        synchronized (mPackages) {
17995            int updateFlags = UPDATE_PERMISSIONS_ALL;
17996            if (ver.sdkVersion != mSdkVersion) {
17997                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
17998                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
17999                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18000            }
18001            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18002
18003            // Yay, everything is now upgraded
18004            ver.forceCurrent();
18005
18006            mSettings.writeLPr();
18007        }
18008
18009        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18010        sendResourcesChangedBroadcast(true, false, loaded, null);
18011    }
18012
18013    private void unloadPrivatePackages(final VolumeInfo vol) {
18014        mHandler.post(new Runnable() {
18015            @Override
18016            public void run() {
18017                unloadPrivatePackagesInner(vol);
18018            }
18019        });
18020    }
18021
18022    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18023        final String volumeUuid = vol.fsUuid;
18024        if (TextUtils.isEmpty(volumeUuid)) {
18025            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18026            return;
18027        }
18028
18029        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18030        synchronized (mInstallLock) {
18031        synchronized (mPackages) {
18032            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18033            for (PackageSetting ps : packages) {
18034                if (ps.pkg == null) continue;
18035
18036                final ApplicationInfo info = ps.pkg.applicationInfo;
18037                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18038                if (deletePackageLI(ps.name, null, false, null,
18039                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
18040                    unloaded.add(info);
18041                } else {
18042                    Slog.w(TAG, "Failed to unload " + ps.codePath);
18043                }
18044            }
18045
18046            mSettings.writeLPr();
18047        }
18048        }
18049
18050        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18051        sendResourcesChangedBroadcast(false, false, unloaded, null);
18052    }
18053
18054    /**
18055     * Examine all users present on given mounted volume, and destroy data
18056     * belonging to users that are no longer valid, or whose user ID has been
18057     * recycled.
18058     */
18059    private void reconcileUsers(String volumeUuid) {
18060        // TODO: also reconcile DE directories
18061        final File[] files = FileUtils
18062                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
18063        for (File file : files) {
18064            if (!file.isDirectory()) continue;
18065
18066            final int userId;
18067            final UserInfo info;
18068            try {
18069                userId = Integer.parseInt(file.getName());
18070                info = sUserManager.getUserInfo(userId);
18071            } catch (NumberFormatException e) {
18072                Slog.w(TAG, "Invalid user directory " + file);
18073                continue;
18074            }
18075
18076            boolean destroyUser = false;
18077            if (info == null) {
18078                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18079                        + " because no matching user was found");
18080                destroyUser = true;
18081            } else {
18082                try {
18083                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18084                } catch (IOException e) {
18085                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18086                            + " because we failed to enforce serial number: " + e);
18087                    destroyUser = true;
18088                }
18089            }
18090
18091            if (destroyUser) {
18092                synchronized (mInstallLock) {
18093                    try {
18094                        mInstaller.removeUserDataDirs(volumeUuid, userId);
18095                    } catch (InstallerException e) {
18096                        Slog.w(TAG, "Failed to clean up user dirs", e);
18097                    }
18098                }
18099            }
18100        }
18101    }
18102
18103    private void assertPackageKnown(String volumeUuid, String packageName)
18104            throws PackageManagerException {
18105        synchronized (mPackages) {
18106            final PackageSetting ps = mSettings.mPackages.get(packageName);
18107            if (ps == null) {
18108                throw new PackageManagerException("Package " + packageName + " is unknown");
18109            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18110                throw new PackageManagerException(
18111                        "Package " + packageName + " found on unknown volume " + volumeUuid
18112                                + "; expected volume " + ps.volumeUuid);
18113            }
18114        }
18115    }
18116
18117    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18118            throws PackageManagerException {
18119        synchronized (mPackages) {
18120            final PackageSetting ps = mSettings.mPackages.get(packageName);
18121            if (ps == null) {
18122                throw new PackageManagerException("Package " + packageName + " is unknown");
18123            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18124                throw new PackageManagerException(
18125                        "Package " + packageName + " found on unknown volume " + volumeUuid
18126                                + "; expected volume " + ps.volumeUuid);
18127            } else if (!ps.getInstalled(userId)) {
18128                throw new PackageManagerException(
18129                        "Package " + packageName + " not installed for user " + userId);
18130            }
18131        }
18132    }
18133
18134    /**
18135     * Examine all apps present on given mounted volume, and destroy apps that
18136     * aren't expected, either due to uninstallation or reinstallation on
18137     * another volume.
18138     */
18139    private void reconcileApps(String volumeUuid) {
18140        final File[] files = FileUtils
18141                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18142        for (File file : files) {
18143            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18144                    && !PackageInstallerService.isStageName(file.getName());
18145            if (!isPackage) {
18146                // Ignore entries which are not packages
18147                continue;
18148            }
18149
18150            try {
18151                final PackageLite pkg = PackageParser.parsePackageLite(file,
18152                        PackageParser.PARSE_MUST_BE_APK);
18153                assertPackageKnown(volumeUuid, pkg.packageName);
18154
18155            } catch (PackageParserException | PackageManagerException e) {
18156                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18157                synchronized (mInstallLock) {
18158                    removeCodePathLI(file);
18159                }
18160            }
18161        }
18162    }
18163
18164    /**
18165     * Reconcile all app data for the given user.
18166     * <p>
18167     * Verifies that directories exist and that ownership and labeling is
18168     * correct for all installed apps on all mounted volumes.
18169     */
18170    void reconcileAppsData(int userId, int flags) {
18171        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18172        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18173            final String volumeUuid = vol.getFsUuid();
18174            reconcileAppsData(volumeUuid, userId, flags);
18175        }
18176    }
18177
18178    /**
18179     * Reconcile all app data on given mounted volume.
18180     * <p>
18181     * Destroys app data that isn't expected, either due to uninstallation or
18182     * reinstallation on another volume.
18183     * <p>
18184     * Verifies that directories exist and that ownership and labeling is
18185     * correct for all installed apps.
18186     */
18187    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
18188        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
18189                + Integer.toHexString(flags));
18190
18191        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
18192        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
18193
18194        boolean restoreconNeeded = false;
18195
18196        // First look for stale data that doesn't belong, and check if things
18197        // have changed since we did our last restorecon
18198        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18199            if (!isUserKeyUnlocked(userId)) {
18200                throw new RuntimeException(
18201                        "Yikes, someone asked us to reconcile CE storage while " + userId
18202                                + " was still locked; this would have caused massive data loss!");
18203            }
18204
18205            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
18206
18207            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
18208            for (File file : files) {
18209                final String packageName = file.getName();
18210                try {
18211                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18212                } catch (PackageManagerException e) {
18213                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18214                    synchronized (mInstallLock) {
18215                        destroyAppDataLI(volumeUuid, packageName, userId,
18216                                StorageManager.FLAG_STORAGE_CE);
18217                    }
18218                }
18219            }
18220        }
18221        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18222            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
18223
18224            final File[] files = FileUtils.listFilesOrEmpty(deDir);
18225            for (File file : files) {
18226                final String packageName = file.getName();
18227                try {
18228                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18229                } catch (PackageManagerException e) {
18230                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18231                    synchronized (mInstallLock) {
18232                        destroyAppDataLI(volumeUuid, packageName, userId,
18233                                StorageManager.FLAG_STORAGE_DE);
18234                    }
18235                }
18236            }
18237        }
18238
18239        // Ensure that data directories are ready to roll for all packages
18240        // installed for this volume and user
18241        final List<PackageSetting> packages;
18242        synchronized (mPackages) {
18243            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18244        }
18245        int preparedCount = 0;
18246        for (PackageSetting ps : packages) {
18247            final String packageName = ps.name;
18248            if (ps.pkg == null) {
18249                Slog.w(TAG, "Odd, missing scanned package " + packageName);
18250                // TODO: might be due to legacy ASEC apps; we should circle back
18251                // and reconcile again once they're scanned
18252                continue;
18253            }
18254
18255            if (ps.getInstalled(userId)) {
18256                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18257
18258                if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) {
18259                    // We may have just shuffled around app data directories, so
18260                    // prepare them one more time
18261                    prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18262                }
18263
18264                preparedCount++;
18265            }
18266        }
18267
18268        if (restoreconNeeded) {
18269            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18270                SELinuxMMAC.setRestoreconDone(ceDir);
18271            }
18272            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18273                SELinuxMMAC.setRestoreconDone(deDir);
18274            }
18275        }
18276
18277        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
18278                + " packages; restoreconNeeded was " + restoreconNeeded);
18279    }
18280
18281    /**
18282     * Prepare app data for the given app just after it was installed or
18283     * upgraded. This method carefully only touches users that it's installed
18284     * for, and it forces a restorecon to handle any seinfo changes.
18285     * <p>
18286     * Verifies that directories exist and that ownership and labeling is
18287     * correct for all installed apps. If there is an ownership mismatch, it
18288     * will try recovering system apps by wiping data; third-party app data is
18289     * left intact.
18290     * <p>
18291     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
18292     */
18293    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
18294        prepareAppDataAfterInstallInternal(pkg);
18295        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18296        for (int i = 0; i < childCount; i++) {
18297            PackageParser.Package childPackage = pkg.childPackages.get(i);
18298            prepareAppDataAfterInstallInternal(childPackage);
18299        }
18300    }
18301
18302    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
18303        final PackageSetting ps;
18304        synchronized (mPackages) {
18305            ps = mSettings.mPackages.get(pkg.packageName);
18306            mSettings.writeKernelMappingLPr(ps);
18307        }
18308
18309        final UserManager um = mContext.getSystemService(UserManager.class);
18310        for (UserInfo user : um.getUsers()) {
18311            final int flags;
18312            if (um.isUserUnlocked(user.id)) {
18313                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18314            } else if (um.isUserRunning(user.id)) {
18315                flags = StorageManager.FLAG_STORAGE_DE;
18316            } else {
18317                continue;
18318            }
18319
18320            if (ps.getInstalled(user.id)) {
18321                // Whenever an app changes, force a restorecon of its data
18322                // TODO: when user data is locked, mark that we're still dirty
18323                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
18324            }
18325        }
18326    }
18327
18328    /**
18329     * Prepare app data for the given app.
18330     * <p>
18331     * Verifies that directories exist and that ownership and labeling is
18332     * correct for all installed apps. If there is an ownership mismatch, this
18333     * will try recovering system apps by wiping data; third-party app data is
18334     * left intact.
18335     */
18336    private void prepareAppData(String volumeUuid, int userId, int flags,
18337            PackageParser.Package pkg, boolean restoreconNeeded) {
18338        if (DEBUG_APP_DATA) {
18339            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18340                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18341        }
18342
18343        final String packageName = pkg.packageName;
18344        final ApplicationInfo app = pkg.applicationInfo;
18345        final int appId = UserHandle.getAppId(app.uid);
18346
18347        Preconditions.checkNotNull(app.seinfo);
18348
18349        synchronized (mInstallLock) {
18350            try {
18351                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18352                        appId, app.seinfo, app.targetSdkVersion);
18353            } catch (InstallerException e) {
18354                if (app.isSystemApp()) {
18355                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18356                            + ", but trying to recover: " + e);
18357                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
18358                    try {
18359                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18360                                appId, app.seinfo, app.targetSdkVersion);
18361                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18362                    } catch (InstallerException e2) {
18363                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
18364                    }
18365                } else {
18366                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18367                }
18368            }
18369
18370            if (restoreconNeeded) {
18371                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
18372            }
18373
18374            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18375                // Create a native library symlink only if we have native libraries
18376                // and if the native libraries are 32 bit libraries. We do not provide
18377                // this symlink for 64 bit libraries.
18378                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18379                    final String nativeLibPath = app.nativeLibraryDir;
18380                    try {
18381                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18382                                nativeLibPath, userId);
18383                    } catch (InstallerException e) {
18384                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18385                    }
18386                }
18387            }
18388        }
18389    }
18390
18391    /**
18392     * For system apps on non-FBE devices, this method migrates any existing
18393     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
18394     * requested by the app.
18395     */
18396    private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) {
18397        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
18398                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
18399            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
18400                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
18401            synchronized (mInstallLock) {
18402                try {
18403                    mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget);
18404                } catch (InstallerException e) {
18405                    logCriticalInfo(Log.WARN,
18406                            "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
18407                }
18408            }
18409            return true;
18410        } else {
18411            return false;
18412        }
18413    }
18414
18415    private void unfreezePackage(String packageName) {
18416        synchronized (mPackages) {
18417            final PackageSetting ps = mSettings.mPackages.get(packageName);
18418            if (ps != null) {
18419                ps.frozen = false;
18420            }
18421        }
18422    }
18423
18424    @Override
18425    public int movePackage(final String packageName, final String volumeUuid) {
18426        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18427
18428        final int moveId = mNextMoveId.getAndIncrement();
18429        mHandler.post(new Runnable() {
18430            @Override
18431            public void run() {
18432                try {
18433                    movePackageInternal(packageName, volumeUuid, moveId);
18434                } catch (PackageManagerException e) {
18435                    Slog.w(TAG, "Failed to move " + packageName, e);
18436                    mMoveCallbacks.notifyStatusChanged(moveId,
18437                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18438                }
18439            }
18440        });
18441        return moveId;
18442    }
18443
18444    private void movePackageInternal(final String packageName, final String volumeUuid,
18445            final int moveId) throws PackageManagerException {
18446        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
18447        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18448        final PackageManager pm = mContext.getPackageManager();
18449
18450        final boolean currentAsec;
18451        final String currentVolumeUuid;
18452        final File codeFile;
18453        final String installerPackageName;
18454        final String packageAbiOverride;
18455        final int appId;
18456        final String seinfo;
18457        final String label;
18458        final int targetSdkVersion;
18459
18460        // reader
18461        synchronized (mPackages) {
18462            final PackageParser.Package pkg = mPackages.get(packageName);
18463            final PackageSetting ps = mSettings.mPackages.get(packageName);
18464            if (pkg == null || ps == null) {
18465                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
18466            }
18467
18468            if (pkg.applicationInfo.isSystemApp()) {
18469                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
18470                        "Cannot move system application");
18471            }
18472
18473            if (pkg.applicationInfo.isExternalAsec()) {
18474                currentAsec = true;
18475                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
18476            } else if (pkg.applicationInfo.isForwardLocked()) {
18477                currentAsec = true;
18478                currentVolumeUuid = "forward_locked";
18479            } else {
18480                currentAsec = false;
18481                currentVolumeUuid = ps.volumeUuid;
18482
18483                final File probe = new File(pkg.codePath);
18484                final File probeOat = new File(probe, "oat");
18485                if (!probe.isDirectory() || !probeOat.isDirectory()) {
18486                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18487                            "Move only supported for modern cluster style installs");
18488                }
18489            }
18490
18491            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
18492                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18493                        "Package already moved to " + volumeUuid);
18494            }
18495            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
18496                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
18497                        "Device admin cannot be moved");
18498            }
18499
18500            if (ps.frozen) {
18501                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
18502                        "Failed to move already frozen package");
18503            }
18504            ps.frozen = true;
18505
18506            codeFile = new File(pkg.codePath);
18507            installerPackageName = ps.installerPackageName;
18508            packageAbiOverride = ps.cpuAbiOverrideString;
18509            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18510            seinfo = pkg.applicationInfo.seinfo;
18511            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
18512            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
18513        }
18514
18515        // Now that we're guarded by frozen state, kill app during move
18516        final long token = Binder.clearCallingIdentity();
18517        try {
18518            killApplication(packageName, appId, "move pkg");
18519        } finally {
18520            Binder.restoreCallingIdentity(token);
18521        }
18522
18523        final Bundle extras = new Bundle();
18524        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
18525        extras.putString(Intent.EXTRA_TITLE, label);
18526        mMoveCallbacks.notifyCreated(moveId, extras);
18527
18528        int installFlags;
18529        final boolean moveCompleteApp;
18530        final File measurePath;
18531
18532        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
18533            installFlags = INSTALL_INTERNAL;
18534            moveCompleteApp = !currentAsec;
18535            measurePath = Environment.getDataAppDirectory(volumeUuid);
18536        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
18537            installFlags = INSTALL_EXTERNAL;
18538            moveCompleteApp = false;
18539            measurePath = storage.getPrimaryPhysicalVolume().getPath();
18540        } else {
18541            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
18542            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
18543                    || !volume.isMountedWritable()) {
18544                unfreezePackage(packageName);
18545                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18546                        "Move location not mounted private volume");
18547            }
18548
18549            Preconditions.checkState(!currentAsec);
18550
18551            installFlags = INSTALL_INTERNAL;
18552            moveCompleteApp = true;
18553            measurePath = Environment.getDataAppDirectory(volumeUuid);
18554        }
18555
18556        final PackageStats stats = new PackageStats(null, -1);
18557        synchronized (mInstaller) {
18558            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
18559                unfreezePackage(packageName);
18560                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18561                        "Failed to measure package size");
18562            }
18563        }
18564
18565        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
18566                + stats.dataSize);
18567
18568        final long startFreeBytes = measurePath.getFreeSpace();
18569        final long sizeBytes;
18570        if (moveCompleteApp) {
18571            sizeBytes = stats.codeSize + stats.dataSize;
18572        } else {
18573            sizeBytes = stats.codeSize;
18574        }
18575
18576        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
18577            unfreezePackage(packageName);
18578            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18579                    "Not enough free space to move");
18580        }
18581
18582        mMoveCallbacks.notifyStatusChanged(moveId, 10);
18583
18584        final CountDownLatch installedLatch = new CountDownLatch(1);
18585        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
18586            @Override
18587            public void onUserActionRequired(Intent intent) throws RemoteException {
18588                throw new IllegalStateException();
18589            }
18590
18591            @Override
18592            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
18593                    Bundle extras) throws RemoteException {
18594                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
18595                        + PackageManager.installStatusToString(returnCode, msg));
18596
18597                installedLatch.countDown();
18598
18599                // Regardless of success or failure of the move operation,
18600                // always unfreeze the package
18601                unfreezePackage(packageName);
18602
18603                final int status = PackageManager.installStatusToPublicStatus(returnCode);
18604                switch (status) {
18605                    case PackageInstaller.STATUS_SUCCESS:
18606                        mMoveCallbacks.notifyStatusChanged(moveId,
18607                                PackageManager.MOVE_SUCCEEDED);
18608                        break;
18609                    case PackageInstaller.STATUS_FAILURE_STORAGE:
18610                        mMoveCallbacks.notifyStatusChanged(moveId,
18611                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
18612                        break;
18613                    default:
18614                        mMoveCallbacks.notifyStatusChanged(moveId,
18615                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18616                        break;
18617                }
18618            }
18619        };
18620
18621        final MoveInfo move;
18622        if (moveCompleteApp) {
18623            // Kick off a thread to report progress estimates
18624            new Thread() {
18625                @Override
18626                public void run() {
18627                    while (true) {
18628                        try {
18629                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
18630                                break;
18631                            }
18632                        } catch (InterruptedException ignored) {
18633                        }
18634
18635                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
18636                        final int progress = 10 + (int) MathUtils.constrain(
18637                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
18638                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
18639                    }
18640                }
18641            }.start();
18642
18643            final String dataAppName = codeFile.getName();
18644            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
18645                    dataAppName, appId, seinfo, targetSdkVersion);
18646        } else {
18647            move = null;
18648        }
18649
18650        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
18651
18652        final Message msg = mHandler.obtainMessage(INIT_COPY);
18653        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
18654        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
18655                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
18656                packageAbiOverride, null);
18657        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
18658        msg.obj = params;
18659
18660        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
18661                System.identityHashCode(msg.obj));
18662        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
18663                System.identityHashCode(msg.obj));
18664
18665        mHandler.sendMessage(msg);
18666    }
18667
18668    @Override
18669    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
18670        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18671
18672        final int realMoveId = mNextMoveId.getAndIncrement();
18673        final Bundle extras = new Bundle();
18674        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
18675        mMoveCallbacks.notifyCreated(realMoveId, extras);
18676
18677        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
18678            @Override
18679            public void onCreated(int moveId, Bundle extras) {
18680                // Ignored
18681            }
18682
18683            @Override
18684            public void onStatusChanged(int moveId, int status, long estMillis) {
18685                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
18686            }
18687        };
18688
18689        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18690        storage.setPrimaryStorageUuid(volumeUuid, callback);
18691        return realMoveId;
18692    }
18693
18694    @Override
18695    public int getMoveStatus(int moveId) {
18696        mContext.enforceCallingOrSelfPermission(
18697                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18698        return mMoveCallbacks.mLastStatus.get(moveId);
18699    }
18700
18701    @Override
18702    public void registerMoveCallback(IPackageMoveObserver callback) {
18703        mContext.enforceCallingOrSelfPermission(
18704                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18705        mMoveCallbacks.register(callback);
18706    }
18707
18708    @Override
18709    public void unregisterMoveCallback(IPackageMoveObserver callback) {
18710        mContext.enforceCallingOrSelfPermission(
18711                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
18712        mMoveCallbacks.unregister(callback);
18713    }
18714
18715    @Override
18716    public boolean setInstallLocation(int loc) {
18717        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
18718                null);
18719        if (getInstallLocation() == loc) {
18720            return true;
18721        }
18722        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
18723                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
18724            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
18725                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
18726            return true;
18727        }
18728        return false;
18729   }
18730
18731    @Override
18732    public int getInstallLocation() {
18733        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
18734                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
18735                PackageHelper.APP_INSTALL_AUTO);
18736    }
18737
18738    /** Called by UserManagerService */
18739    void cleanUpUser(UserManagerService userManager, int userHandle) {
18740        synchronized (mPackages) {
18741            mDirtyUsers.remove(userHandle);
18742            mUserNeedsBadging.delete(userHandle);
18743            mSettings.removeUserLPw(userHandle);
18744            mPendingBroadcasts.remove(userHandle);
18745            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
18746        }
18747        synchronized (mInstallLock) {
18748            final StorageManager storage = mContext.getSystemService(StorageManager.class);
18749            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18750                final String volumeUuid = vol.getFsUuid();
18751                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
18752                try {
18753                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
18754                } catch (InstallerException e) {
18755                    Slog.w(TAG, "Failed to remove user data", e);
18756                }
18757            }
18758            synchronized (mPackages) {
18759                removeUnusedPackagesLILPw(userManager, userHandle);
18760            }
18761        }
18762    }
18763
18764    /**
18765     * We're removing userHandle and would like to remove any downloaded packages
18766     * that are no longer in use by any other user.
18767     * @param userHandle the user being removed
18768     */
18769    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
18770        final boolean DEBUG_CLEAN_APKS = false;
18771        int [] users = userManager.getUserIds();
18772        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
18773        while (psit.hasNext()) {
18774            PackageSetting ps = psit.next();
18775            if (ps.pkg == null) {
18776                continue;
18777            }
18778            final String packageName = ps.pkg.packageName;
18779            // Skip over if system app
18780            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
18781                continue;
18782            }
18783            if (DEBUG_CLEAN_APKS) {
18784                Slog.i(TAG, "Checking package " + packageName);
18785            }
18786            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
18787            if (keep) {
18788                if (DEBUG_CLEAN_APKS) {
18789                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
18790                }
18791            } else {
18792                for (int i = 0; i < users.length; i++) {
18793                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
18794                        keep = true;
18795                        if (DEBUG_CLEAN_APKS) {
18796                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
18797                                    + users[i]);
18798                        }
18799                        break;
18800                    }
18801                }
18802            }
18803            if (!keep) {
18804                if (DEBUG_CLEAN_APKS) {
18805                    Slog.i(TAG, "  Removing package " + packageName);
18806                }
18807                mHandler.post(new Runnable() {
18808                    public void run() {
18809                        deletePackageX(packageName, userHandle, 0);
18810                    } //end run
18811                });
18812            }
18813        }
18814    }
18815
18816    /** Called by UserManagerService */
18817    void createNewUser(int userHandle) {
18818        synchronized (mInstallLock) {
18819            try {
18820                mInstaller.createUserConfig(userHandle);
18821            } catch (InstallerException e) {
18822                Slog.w(TAG, "Failed to create user config", e);
18823            }
18824            mSettings.createNewUserLI(this, mInstaller, userHandle);
18825        }
18826        synchronized (mPackages) {
18827            applyFactoryDefaultBrowserLPw(userHandle);
18828            primeDomainVerificationsLPw(userHandle);
18829        }
18830    }
18831
18832    void newUserCreated(final int userHandle) {
18833        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
18834        // If permission review for legacy apps is required, we represent
18835        // dagerous permissions for such apps as always granted runtime
18836        // permissions to keep per user flag state whether review is needed.
18837        // Hence, if a new user is added we have to propagate dangerous
18838        // permission grants for these legacy apps.
18839        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
18840            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
18841                    | UPDATE_PERMISSIONS_REPLACE_ALL);
18842        }
18843    }
18844
18845    @Override
18846    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
18847        mContext.enforceCallingOrSelfPermission(
18848                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
18849                "Only package verification agents can read the verifier device identity");
18850
18851        synchronized (mPackages) {
18852            return mSettings.getVerifierDeviceIdentityLPw();
18853        }
18854    }
18855
18856    @Override
18857    public void setPermissionEnforced(String permission, boolean enforced) {
18858        // TODO: Now that we no longer change GID for storage, this should to away.
18859        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
18860                "setPermissionEnforced");
18861        if (READ_EXTERNAL_STORAGE.equals(permission)) {
18862            synchronized (mPackages) {
18863                if (mSettings.mReadExternalStorageEnforced == null
18864                        || mSettings.mReadExternalStorageEnforced != enforced) {
18865                    mSettings.mReadExternalStorageEnforced = enforced;
18866                    mSettings.writeLPr();
18867                }
18868            }
18869            // kill any non-foreground processes so we restart them and
18870            // grant/revoke the GID.
18871            final IActivityManager am = ActivityManagerNative.getDefault();
18872            if (am != null) {
18873                final long token = Binder.clearCallingIdentity();
18874                try {
18875                    am.killProcessesBelowForeground("setPermissionEnforcement");
18876                } catch (RemoteException e) {
18877                } finally {
18878                    Binder.restoreCallingIdentity(token);
18879                }
18880            }
18881        } else {
18882            throw new IllegalArgumentException("No selective enforcement for " + permission);
18883        }
18884    }
18885
18886    @Override
18887    @Deprecated
18888    public boolean isPermissionEnforced(String permission) {
18889        return true;
18890    }
18891
18892    @Override
18893    public boolean isStorageLow() {
18894        final long token = Binder.clearCallingIdentity();
18895        try {
18896            final DeviceStorageMonitorInternal
18897                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
18898            if (dsm != null) {
18899                return dsm.isMemoryLow();
18900            } else {
18901                return false;
18902            }
18903        } finally {
18904            Binder.restoreCallingIdentity(token);
18905        }
18906    }
18907
18908    @Override
18909    public IPackageInstaller getPackageInstaller() {
18910        return mInstallerService;
18911    }
18912
18913    private boolean userNeedsBadging(int userId) {
18914        int index = mUserNeedsBadging.indexOfKey(userId);
18915        if (index < 0) {
18916            final UserInfo userInfo;
18917            final long token = Binder.clearCallingIdentity();
18918            try {
18919                userInfo = sUserManager.getUserInfo(userId);
18920            } finally {
18921                Binder.restoreCallingIdentity(token);
18922            }
18923            final boolean b;
18924            if (userInfo != null && userInfo.isManagedProfile()) {
18925                b = true;
18926            } else {
18927                b = false;
18928            }
18929            mUserNeedsBadging.put(userId, b);
18930            return b;
18931        }
18932        return mUserNeedsBadging.valueAt(index);
18933    }
18934
18935    @Override
18936    public KeySet getKeySetByAlias(String packageName, String alias) {
18937        if (packageName == null || alias == null) {
18938            return null;
18939        }
18940        synchronized(mPackages) {
18941            final PackageParser.Package pkg = mPackages.get(packageName);
18942            if (pkg == null) {
18943                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18944                throw new IllegalArgumentException("Unknown package: " + packageName);
18945            }
18946            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18947            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
18948        }
18949    }
18950
18951    @Override
18952    public KeySet getSigningKeySet(String packageName) {
18953        if (packageName == null) {
18954            return null;
18955        }
18956        synchronized(mPackages) {
18957            final PackageParser.Package pkg = mPackages.get(packageName);
18958            if (pkg == null) {
18959                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18960                throw new IllegalArgumentException("Unknown package: " + packageName);
18961            }
18962            if (pkg.applicationInfo.uid != Binder.getCallingUid()
18963                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
18964                throw new SecurityException("May not access signing KeySet of other apps.");
18965            }
18966            KeySetManagerService ksms = mSettings.mKeySetManagerService;
18967            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
18968        }
18969    }
18970
18971    @Override
18972    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
18973        if (packageName == null || ks == null) {
18974            return false;
18975        }
18976        synchronized(mPackages) {
18977            final PackageParser.Package pkg = mPackages.get(packageName);
18978            if (pkg == null) {
18979                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
18980                throw new IllegalArgumentException("Unknown package: " + packageName);
18981            }
18982            IBinder ksh = ks.getToken();
18983            if (ksh instanceof KeySetHandle) {
18984                KeySetManagerService ksms = mSettings.mKeySetManagerService;
18985                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
18986            }
18987            return false;
18988        }
18989    }
18990
18991    @Override
18992    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
18993        if (packageName == null || ks == null) {
18994            return false;
18995        }
18996        synchronized(mPackages) {
18997            final PackageParser.Package pkg = mPackages.get(packageName);
18998            if (pkg == null) {
18999                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19000                throw new IllegalArgumentException("Unknown package: " + packageName);
19001            }
19002            IBinder ksh = ks.getToken();
19003            if (ksh instanceof KeySetHandle) {
19004                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19005                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19006            }
19007            return false;
19008        }
19009    }
19010
19011    private void deletePackageIfUnusedLPr(final String packageName) {
19012        PackageSetting ps = mSettings.mPackages.get(packageName);
19013        if (ps == null) {
19014            return;
19015        }
19016        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19017            // TODO Implement atomic delete if package is unused
19018            // It is currently possible that the package will be deleted even if it is installed
19019            // after this method returns.
19020            mHandler.post(new Runnable() {
19021                public void run() {
19022                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
19023                }
19024            });
19025        }
19026    }
19027
19028    /**
19029     * Check and throw if the given before/after packages would be considered a
19030     * downgrade.
19031     */
19032    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
19033            throws PackageManagerException {
19034        if (after.versionCode < before.mVersionCode) {
19035            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19036                    "Update version code " + after.versionCode + " is older than current "
19037                    + before.mVersionCode);
19038        } else if (after.versionCode == before.mVersionCode) {
19039            if (after.baseRevisionCode < before.baseRevisionCode) {
19040                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19041                        "Update base revision code " + after.baseRevisionCode
19042                        + " is older than current " + before.baseRevisionCode);
19043            }
19044
19045            if (!ArrayUtils.isEmpty(after.splitNames)) {
19046                for (int i = 0; i < after.splitNames.length; i++) {
19047                    final String splitName = after.splitNames[i];
19048                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
19049                    if (j != -1) {
19050                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
19051                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19052                                    "Update split " + splitName + " revision code "
19053                                    + after.splitRevisionCodes[i] + " is older than current "
19054                                    + before.splitRevisionCodes[j]);
19055                        }
19056                    }
19057                }
19058            }
19059        }
19060    }
19061
19062    private static class MoveCallbacks extends Handler {
19063        private static final int MSG_CREATED = 1;
19064        private static final int MSG_STATUS_CHANGED = 2;
19065
19066        private final RemoteCallbackList<IPackageMoveObserver>
19067                mCallbacks = new RemoteCallbackList<>();
19068
19069        private final SparseIntArray mLastStatus = new SparseIntArray();
19070
19071        public MoveCallbacks(Looper looper) {
19072            super(looper);
19073        }
19074
19075        public void register(IPackageMoveObserver callback) {
19076            mCallbacks.register(callback);
19077        }
19078
19079        public void unregister(IPackageMoveObserver callback) {
19080            mCallbacks.unregister(callback);
19081        }
19082
19083        @Override
19084        public void handleMessage(Message msg) {
19085            final SomeArgs args = (SomeArgs) msg.obj;
19086            final int n = mCallbacks.beginBroadcast();
19087            for (int i = 0; i < n; i++) {
19088                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
19089                try {
19090                    invokeCallback(callback, msg.what, args);
19091                } catch (RemoteException ignored) {
19092                }
19093            }
19094            mCallbacks.finishBroadcast();
19095            args.recycle();
19096        }
19097
19098        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
19099                throws RemoteException {
19100            switch (what) {
19101                case MSG_CREATED: {
19102                    callback.onCreated(args.argi1, (Bundle) args.arg2);
19103                    break;
19104                }
19105                case MSG_STATUS_CHANGED: {
19106                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
19107                    break;
19108                }
19109            }
19110        }
19111
19112        private void notifyCreated(int moveId, Bundle extras) {
19113            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
19114
19115            final SomeArgs args = SomeArgs.obtain();
19116            args.argi1 = moveId;
19117            args.arg2 = extras;
19118            obtainMessage(MSG_CREATED, args).sendToTarget();
19119        }
19120
19121        private void notifyStatusChanged(int moveId, int status) {
19122            notifyStatusChanged(moveId, status, -1);
19123        }
19124
19125        private void notifyStatusChanged(int moveId, int status, long estMillis) {
19126            Slog.v(TAG, "Move " + moveId + " status " + status);
19127
19128            final SomeArgs args = SomeArgs.obtain();
19129            args.argi1 = moveId;
19130            args.argi2 = status;
19131            args.arg3 = estMillis;
19132            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
19133
19134            synchronized (mLastStatus) {
19135                mLastStatus.put(moveId, status);
19136            }
19137        }
19138    }
19139
19140    private final static class OnPermissionChangeListeners extends Handler {
19141        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
19142
19143        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
19144                new RemoteCallbackList<>();
19145
19146        public OnPermissionChangeListeners(Looper looper) {
19147            super(looper);
19148        }
19149
19150        @Override
19151        public void handleMessage(Message msg) {
19152            switch (msg.what) {
19153                case MSG_ON_PERMISSIONS_CHANGED: {
19154                    final int uid = msg.arg1;
19155                    handleOnPermissionsChanged(uid);
19156                } break;
19157            }
19158        }
19159
19160        public void addListenerLocked(IOnPermissionsChangeListener listener) {
19161            mPermissionListeners.register(listener);
19162
19163        }
19164
19165        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
19166            mPermissionListeners.unregister(listener);
19167        }
19168
19169        public void onPermissionsChanged(int uid) {
19170            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
19171                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
19172            }
19173        }
19174
19175        private void handleOnPermissionsChanged(int uid) {
19176            final int count = mPermissionListeners.beginBroadcast();
19177            try {
19178                for (int i = 0; i < count; i++) {
19179                    IOnPermissionsChangeListener callback = mPermissionListeners
19180                            .getBroadcastItem(i);
19181                    try {
19182                        callback.onPermissionsChanged(uid);
19183                    } catch (RemoteException e) {
19184                        Log.e(TAG, "Permission listener is dead", e);
19185                    }
19186                }
19187            } finally {
19188                mPermissionListeners.finishBroadcast();
19189            }
19190        }
19191    }
19192
19193    private class PackageManagerInternalImpl extends PackageManagerInternal {
19194        @Override
19195        public void setLocationPackagesProvider(PackagesProvider provider) {
19196            synchronized (mPackages) {
19197                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
19198            }
19199        }
19200
19201        @Override
19202        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
19203            synchronized (mPackages) {
19204                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
19205            }
19206        }
19207
19208        @Override
19209        public void setSmsAppPackagesProvider(PackagesProvider provider) {
19210            synchronized (mPackages) {
19211                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
19212            }
19213        }
19214
19215        @Override
19216        public void setDialerAppPackagesProvider(PackagesProvider provider) {
19217            synchronized (mPackages) {
19218                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
19219            }
19220        }
19221
19222        @Override
19223        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
19224            synchronized (mPackages) {
19225                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
19226            }
19227        }
19228
19229        @Override
19230        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
19231            synchronized (mPackages) {
19232                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
19233            }
19234        }
19235
19236        @Override
19237        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
19238            synchronized (mPackages) {
19239                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
19240                        packageName, userId);
19241            }
19242        }
19243
19244        @Override
19245        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
19246            synchronized (mPackages) {
19247                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
19248                        packageName, userId);
19249            }
19250        }
19251
19252        @Override
19253        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
19254            synchronized (mPackages) {
19255                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
19256                        packageName, userId);
19257            }
19258        }
19259
19260        @Override
19261        public void setKeepUninstalledPackages(final List<String> packageList) {
19262            Preconditions.checkNotNull(packageList);
19263            List<String> removedFromList = null;
19264            synchronized (mPackages) {
19265                if (mKeepUninstalledPackages != null) {
19266                    final int packagesCount = mKeepUninstalledPackages.size();
19267                    for (int i = 0; i < packagesCount; i++) {
19268                        String oldPackage = mKeepUninstalledPackages.get(i);
19269                        if (packageList != null && packageList.contains(oldPackage)) {
19270                            continue;
19271                        }
19272                        if (removedFromList == null) {
19273                            removedFromList = new ArrayList<>();
19274                        }
19275                        removedFromList.add(oldPackage);
19276                    }
19277                }
19278                mKeepUninstalledPackages = new ArrayList<>(packageList);
19279                if (removedFromList != null) {
19280                    final int removedCount = removedFromList.size();
19281                    for (int i = 0; i < removedCount; i++) {
19282                        deletePackageIfUnusedLPr(removedFromList.get(i));
19283                    }
19284                }
19285            }
19286        }
19287
19288        @Override
19289        public boolean isPermissionsReviewRequired(String packageName, int userId) {
19290            synchronized (mPackages) {
19291                // If we do not support permission review, done.
19292                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
19293                    return false;
19294                }
19295
19296                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
19297                if (packageSetting == null) {
19298                    return false;
19299                }
19300
19301                // Permission review applies only to apps not supporting the new permission model.
19302                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
19303                    return false;
19304                }
19305
19306                // Legacy apps have the permission and get user consent on launch.
19307                PermissionsState permissionsState = packageSetting.getPermissionsState();
19308                return permissionsState.isPermissionReviewRequired(userId);
19309            }
19310        }
19311
19312        @Override
19313        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
19314            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
19315        }
19316
19317        @Override
19318        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19319                int userId) {
19320            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
19321        }
19322    }
19323
19324    @Override
19325    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
19326        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
19327        synchronized (mPackages) {
19328            final long identity = Binder.clearCallingIdentity();
19329            try {
19330                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
19331                        packageNames, userId);
19332            } finally {
19333                Binder.restoreCallingIdentity(identity);
19334            }
19335        }
19336    }
19337
19338    private static void enforceSystemOrPhoneCaller(String tag) {
19339        int callingUid = Binder.getCallingUid();
19340        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
19341            throw new SecurityException(
19342                    "Cannot call " + tag + " from UID " + callingUid);
19343        }
19344    }
19345
19346    boolean isHistoricalPackageUsageAvailable() {
19347        return mPackageUsage.isHistoricalPackageUsageAvailable();
19348    }
19349
19350    /**
19351     * Return a <b>copy</b> of the collection of packages known to the package manager.
19352     * @return A copy of the values of mPackages.
19353     */
19354    Collection<PackageParser.Package> getPackages() {
19355        synchronized (mPackages) {
19356            return new ArrayList<>(mPackages.values());
19357        }
19358    }
19359}
19360