PackageManagerService.java revision 40ccfdd831ce76e2f1df84a9d4b865f5cf8b65aa
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_FACTORY_ONLY;
68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
75import static android.content.pm.PackageManager.PERMISSION_DENIED;
76import static android.content.pm.PackageManager.PERMISSION_GRANTED;
77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
78import static android.content.pm.PackageParser.isApkFile;
79import static android.os.Process.FIRST_APPLICATION_UID;
80import static android.os.Process.PACKAGE_INFO_GID;
81import static android.os.Process.SYSTEM_UID;
82import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
83import static android.system.OsConstants.O_CREAT;
84import static android.system.OsConstants.O_RDWR;
85
86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
87import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
88import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
89import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
90import static com.android.internal.util.ArrayUtils.appendInt;
91import static com.android.server.pm.Installer.DEXOPT_PUBLIC;
92import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
95import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
96import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason;
98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter;
99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE;
100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS;
101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
102
103import android.Manifest;
104import android.annotation.NonNull;
105import android.annotation.Nullable;
106import android.app.ActivityManager;
107import android.app.ActivityManagerNative;
108import android.app.IActivityManager;
109import android.app.admin.DevicePolicyManagerInternal;
110import android.app.admin.IDevicePolicyManager;
111import android.app.admin.SecurityLog;
112import android.app.backup.IBackupManager;
113import android.content.BroadcastReceiver;
114import android.content.ComponentName;
115import android.content.Context;
116import android.content.IIntentReceiver;
117import android.content.Intent;
118import android.content.IntentFilter;
119import android.content.IntentFilter.AuthorityEntry;
120import android.content.IntentSender;
121import android.content.IntentSender.SendIntentException;
122import android.content.ServiceConnection;
123import android.content.pm.ActivityInfo;
124import android.content.pm.ApplicationInfo;
125import android.content.pm.AppsQueryHelper;
126import android.content.pm.ComponentInfo;
127import android.content.pm.EphemeralApplicationInfo;
128import android.content.pm.EphemeralResolveInfo;
129import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo;
130import android.content.pm.FeatureInfo;
131import android.content.pm.IOnPermissionsChangeListener;
132import android.content.pm.IPackageDataObserver;
133import android.content.pm.IPackageDeleteObserver;
134import android.content.pm.IPackageDeleteObserver2;
135import android.content.pm.IPackageInstallObserver2;
136import android.content.pm.IPackageInstaller;
137import android.content.pm.IPackageManager;
138import android.content.pm.IPackageMoveObserver;
139import android.content.pm.IPackageStatsObserver;
140import android.content.pm.InstrumentationInfo;
141import android.content.pm.IntentFilterVerificationInfo;
142import android.content.pm.KeySet;
143import android.content.pm.PackageCleanItem;
144import android.content.pm.PackageInfo;
145import android.content.pm.PackageInfoLite;
146import android.content.pm.PackageInstaller;
147import android.content.pm.PackageManager;
148import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
149import android.content.pm.PackageManagerInternal;
150import android.content.pm.PackageParser;
151import android.content.pm.PackageParser.ActivityIntentInfo;
152import android.content.pm.PackageParser.IntentInfo;
153import android.content.pm.PackageParser.PackageLite;
154import android.content.pm.PackageParser.PackageParserException;
155import android.content.pm.PackageStats;
156import android.content.pm.PackageUserState;
157import android.content.pm.ParceledListSlice;
158import android.content.pm.PermissionGroupInfo;
159import android.content.pm.PermissionInfo;
160import android.content.pm.ProviderInfo;
161import android.content.pm.ResolveInfo;
162import android.content.pm.ServiceInfo;
163import android.content.pm.Signature;
164import android.content.pm.UserInfo;
165import android.content.pm.VerifierDeviceIdentity;
166import android.content.pm.VerifierInfo;
167import android.content.res.Resources;
168import android.graphics.Bitmap;
169import android.hardware.display.DisplayManager;
170import android.net.Uri;
171import android.os.Binder;
172import android.os.Build;
173import android.os.Bundle;
174import android.os.Debug;
175import android.os.Environment;
176import android.os.Environment.UserEnvironment;
177import android.os.FileUtils;
178import android.os.Handler;
179import android.os.IBinder;
180import android.os.Looper;
181import android.os.Message;
182import android.os.Parcel;
183import android.os.ParcelFileDescriptor;
184import android.os.Process;
185import android.os.RemoteCallbackList;
186import android.os.RemoteException;
187import android.os.ResultReceiver;
188import android.os.SELinux;
189import android.os.ServiceManager;
190import android.os.SystemClock;
191import android.os.SystemProperties;
192import android.os.Trace;
193import android.os.UserHandle;
194import android.os.UserManager;
195import android.os.storage.IMountService;
196import android.os.storage.MountServiceInternal;
197import android.os.storage.StorageEventListener;
198import android.os.storage.StorageManager;
199import android.os.storage.VolumeInfo;
200import android.os.storage.VolumeRecord;
201import android.security.KeyStore;
202import android.security.SystemKeyStore;
203import android.system.ErrnoException;
204import android.system.Os;
205import android.text.TextUtils;
206import android.text.format.DateUtils;
207import android.util.ArrayMap;
208import android.util.ArraySet;
209import android.util.AtomicFile;
210import android.util.DisplayMetrics;
211import android.util.EventLog;
212import android.util.ExceptionUtils;
213import android.util.Log;
214import android.util.LogPrinter;
215import android.util.MathUtils;
216import android.util.PrintStreamPrinter;
217import android.util.Slog;
218import android.util.SparseArray;
219import android.util.SparseBooleanArray;
220import android.util.SparseIntArray;
221import android.util.Xml;
222import android.view.Display;
223
224import com.android.internal.R;
225import com.android.internal.annotations.GuardedBy;
226import com.android.internal.app.IMediaContainerService;
227import com.android.internal.app.ResolverActivity;
228import com.android.internal.content.NativeLibraryHelper;
229import com.android.internal.content.PackageHelper;
230import com.android.internal.os.IParcelFileDescriptorFactory;
231import com.android.internal.os.InstallerConnection.InstallerException;
232import com.android.internal.os.SomeArgs;
233import com.android.internal.os.Zygote;
234import com.android.internal.util.ArrayUtils;
235import com.android.internal.util.FastPrintWriter;
236import com.android.internal.util.FastXmlSerializer;
237import com.android.internal.util.IndentingPrintWriter;
238import com.android.internal.util.Preconditions;
239import com.android.internal.util.XmlUtils;
240import com.android.server.EventLogTags;
241import com.android.server.FgThread;
242import com.android.server.IntentResolver;
243import com.android.server.LocalServices;
244import com.android.server.ServiceThread;
245import com.android.server.SystemConfig;
246import com.android.server.Watchdog;
247import com.android.server.pm.PermissionsState.PermissionState;
248import com.android.server.pm.Settings.DatabaseVersion;
249import com.android.server.pm.Settings.VersionInfo;
250import com.android.server.storage.DeviceStorageMonitorInternal;
251
252import dalvik.system.DexFile;
253import dalvik.system.VMRuntime;
254
255import libcore.io.IoUtils;
256import libcore.util.EmptyArray;
257
258import org.xmlpull.v1.XmlPullParser;
259import org.xmlpull.v1.XmlPullParserException;
260import org.xmlpull.v1.XmlSerializer;
261
262import java.io.BufferedInputStream;
263import java.io.BufferedOutputStream;
264import java.io.BufferedReader;
265import java.io.ByteArrayInputStream;
266import java.io.ByteArrayOutputStream;
267import java.io.File;
268import java.io.FileDescriptor;
269import java.io.FileNotFoundException;
270import java.io.FileOutputStream;
271import java.io.FileReader;
272import java.io.FilenameFilter;
273import java.io.IOException;
274import java.io.InputStream;
275import java.io.PrintWriter;
276import java.nio.charset.StandardCharsets;
277import java.security.MessageDigest;
278import java.security.NoSuchAlgorithmException;
279import java.security.PublicKey;
280import java.security.cert.CertificateEncodingException;
281import java.security.cert.CertificateException;
282import java.text.SimpleDateFormat;
283import java.util.ArrayList;
284import java.util.Arrays;
285import java.util.Collection;
286import java.util.Collections;
287import java.util.Comparator;
288import java.util.Date;
289import java.util.HashSet;
290import java.util.Iterator;
291import java.util.List;
292import java.util.Map;
293import java.util.Objects;
294import java.util.Set;
295import java.util.concurrent.CountDownLatch;
296import java.util.concurrent.TimeUnit;
297import java.util.concurrent.atomic.AtomicBoolean;
298import java.util.concurrent.atomic.AtomicInteger;
299import java.util.concurrent.atomic.AtomicLong;
300
301/**
302 * Keep track of all those .apks everywhere.
303 *
304 * This is very central to the platform's security; please run the unit
305 * tests whenever making modifications here:
306 *
307runtest -c android.content.pm.PackageManagerTests frameworks-core
308 *
309 * {@hide}
310 */
311public class PackageManagerService extends IPackageManager.Stub {
312    static final String TAG = "PackageManager";
313    static final boolean DEBUG_SETTINGS = false;
314    static final boolean DEBUG_PREFERRED = false;
315    static final boolean DEBUG_UPGRADE = false;
316    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
317    private static final boolean DEBUG_BACKUP = false;
318    private static final boolean DEBUG_INSTALL = false;
319    private static final boolean DEBUG_REMOVE = false;
320    private static final boolean DEBUG_BROADCASTS = false;
321    private static final boolean DEBUG_SHOW_INFO = false;
322    private static final boolean DEBUG_PACKAGE_INFO = false;
323    private static final boolean DEBUG_INTENT_MATCHING = false;
324    private static final boolean DEBUG_PACKAGE_SCANNING = false;
325    private static final boolean DEBUG_VERIFY = false;
326    private static final boolean DEBUG_FILTERS = false;
327
328    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
329    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
330    // user, but by default initialize to this.
331    static final boolean DEBUG_DEXOPT = false;
332
333    private static final boolean DEBUG_ABI_SELECTION = false;
334    private static final boolean DEBUG_EPHEMERAL = false;
335    private static final boolean DEBUG_TRIAGED_MISSING = false;
336    private static final boolean DEBUG_APP_DATA = false;
337
338    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
339
340    private static final boolean DISABLE_EPHEMERAL_APPS = true;
341
342    private static final int RADIO_UID = Process.PHONE_UID;
343    private static final int LOG_UID = Process.LOG_UID;
344    private static final int NFC_UID = Process.NFC_UID;
345    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
346    private static final int SHELL_UID = Process.SHELL_UID;
347
348    // Cap the size of permission trees that 3rd party apps can define
349    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
350
351    // Suffix used during package installation when copying/moving
352    // package apks to install directory.
353    private static final String INSTALL_PACKAGE_SUFFIX = "-";
354
355    static final int SCAN_NO_DEX = 1<<1;
356    static final int SCAN_FORCE_DEX = 1<<2;
357    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
358    static final int SCAN_NEW_INSTALL = 1<<4;
359    static final int SCAN_NO_PATHS = 1<<5;
360    static final int SCAN_UPDATE_TIME = 1<<6;
361    static final int SCAN_DEFER_DEX = 1<<7;
362    static final int SCAN_BOOTING = 1<<8;
363    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
364    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
365    static final int SCAN_REPLACING = 1<<11;
366    static final int SCAN_REQUIRE_KNOWN = 1<<12;
367    static final int SCAN_MOVE = 1<<13;
368    static final int SCAN_INITIAL = 1<<14;
369    static final int SCAN_CHECK_ONLY = 1<<15;
370    static final int SCAN_DONT_KILL_APP = 1<<17;
371
372    static final int REMOVE_CHATTY = 1<<16;
373
374    private static final int[] EMPTY_INT_ARRAY = new int[0];
375
376    /**
377     * Timeout (in milliseconds) after which the watchdog should declare that
378     * our handler thread is wedged.  The usual default for such things is one
379     * minute but we sometimes do very lengthy I/O operations on this thread,
380     * such as installing multi-gigabyte applications, so ours needs to be longer.
381     */
382    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
383
384    /**
385     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
386     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
387     * settings entry if available, otherwise we use the hardcoded default.  If it's been
388     * more than this long since the last fstrim, we force one during the boot sequence.
389     *
390     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
391     * one gets run at the next available charging+idle time.  This final mandatory
392     * no-fstrim check kicks in only of the other scheduling criteria is never met.
393     */
394    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
395
396    /**
397     * Whether verification is enabled by default.
398     */
399    private static final boolean DEFAULT_VERIFY_ENABLE = true;
400
401    /**
402     * The default maximum time to wait for the verification agent to return in
403     * milliseconds.
404     */
405    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
406
407    /**
408     * The default response for package verification timeout.
409     *
410     * This can be either PackageManager.VERIFICATION_ALLOW or
411     * PackageManager.VERIFICATION_REJECT.
412     */
413    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
414
415    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
416
417    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
418            DEFAULT_CONTAINER_PACKAGE,
419            "com.android.defcontainer.DefaultContainerService");
420
421    private static final String KILL_APP_REASON_GIDS_CHANGED =
422            "permission grant or revoke changed gids";
423
424    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
425            "permissions revoked";
426
427    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
428
429    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
430
431    /** Permission grant: not grant the permission. */
432    private static final int GRANT_DENIED = 1;
433
434    /** Permission grant: grant the permission as an install permission. */
435    private static final int GRANT_INSTALL = 2;
436
437    /** Permission grant: grant the permission as a runtime one. */
438    private static final int GRANT_RUNTIME = 3;
439
440    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
441    private static final int GRANT_UPGRADE = 4;
442
443    /** Canonical intent used to identify what counts as a "web browser" app */
444    private static final Intent sBrowserIntent;
445    static {
446        sBrowserIntent = new Intent();
447        sBrowserIntent.setAction(Intent.ACTION_VIEW);
448        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
449        sBrowserIntent.setData(Uri.parse("http:"));
450    }
451
452    /**
453     * The set of all protected actions [i.e. those actions for which a high priority
454     * intent filter is disallowed].
455     */
456    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
457    static {
458        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
459        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
460        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
461        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
462    }
463
464    // Compilation reasons.
465    public static final int REASON_FIRST_BOOT = 0;
466    public static final int REASON_BOOT = 1;
467    public static final int REASON_INSTALL = 2;
468    public static final int REASON_BACKGROUND_DEXOPT = 3;
469    public static final int REASON_AB_OTA = 4;
470    public static final int REASON_NON_SYSTEM_LIBRARY = 5;
471    public static final int REASON_SHARED_APK = 6;
472    public static final int REASON_FORCED_DEXOPT = 7;
473
474    public static final int REASON_LAST = REASON_FORCED_DEXOPT;
475
476    final ServiceThread mHandlerThread;
477
478    final PackageHandler mHandler;
479
480    private final ProcessLoggingHandler mProcessLoggingHandler;
481
482    /**
483     * Messages for {@link #mHandler} that need to wait for system ready before
484     * being dispatched.
485     */
486    private ArrayList<Message> mPostSystemReadyMessages;
487
488    final int mSdkVersion = Build.VERSION.SDK_INT;
489
490    final Context mContext;
491    final boolean mFactoryTest;
492    final boolean mOnlyCore;
493    final DisplayMetrics mMetrics;
494    final int mDefParseFlags;
495    final String[] mSeparateProcesses;
496    final boolean mIsUpgrade;
497    final boolean mIsPreNUpgrade;
498
499    /** The location for ASEC container files on internal storage. */
500    final String mAsecInternalPath;
501
502    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
503    // LOCK HELD.  Can be called with mInstallLock held.
504    @GuardedBy("mInstallLock")
505    final Installer mInstaller;
506
507    /** Directory where installed third-party apps stored */
508    final File mAppInstallDir;
509    final File mEphemeralInstallDir;
510
511    /**
512     * Directory to which applications installed internally have their
513     * 32 bit native libraries copied.
514     */
515    private File mAppLib32InstallDir;
516
517    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
518    // apps.
519    final File mDrmAppPrivateInstallDir;
520
521    // ----------------------------------------------------------------
522
523    // Lock for state used when installing and doing other long running
524    // operations.  Methods that must be called with this lock held have
525    // the suffix "LI".
526    final Object mInstallLock = new Object();
527
528    // ----------------------------------------------------------------
529
530    // Keys are String (package name), values are Package.  This also serves
531    // as the lock for the global state.  Methods that must be called with
532    // this lock held have the prefix "LP".
533    @GuardedBy("mPackages")
534    final ArrayMap<String, PackageParser.Package> mPackages =
535            new ArrayMap<String, PackageParser.Package>();
536
537    final ArrayMap<String, Set<String>> mKnownCodebase =
538            new ArrayMap<String, Set<String>>();
539
540    // Tracks available target package names -> overlay package paths.
541    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
542        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
543
544    /**
545     * Tracks new system packages [received in an OTA] that we expect to
546     * find updated user-installed versions. Keys are package name, values
547     * are package location.
548     */
549    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
550    /**
551     * Tracks high priority intent filters for protected actions. During boot, certain
552     * filter actions are protected and should never be allowed to have a high priority
553     * intent filter for them. However, there is one, and only one exception -- the
554     * setup wizard. It must be able to define a high priority intent filter for these
555     * actions to ensure there are no escapes from the wizard. We need to delay processing
556     * of these during boot as we need to look at all of the system packages in order
557     * to know which component is the setup wizard.
558     */
559    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
560    /**
561     * Whether or not processing protected filters should be deferred.
562     */
563    private boolean mDeferProtectedFilters = true;
564
565    /**
566     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
567     */
568    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
569    /**
570     * Whether or not system app permissions should be promoted from install to runtime.
571     */
572    boolean mPromoteSystemApps;
573
574    final Settings mSettings;
575    boolean mRestoredSettings;
576
577    // System configuration read by SystemConfig.
578    final int[] mGlobalGids;
579    final SparseArray<ArraySet<String>> mSystemPermissions;
580    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
581
582    // If mac_permissions.xml was found for seinfo labeling.
583    boolean mFoundPolicyFile;
584
585    private final EphemeralApplicationRegistry mEphemeralApplicationRegistry;
586
587    public static final class SharedLibraryEntry {
588        public final String path;
589        public final String apk;
590
591        SharedLibraryEntry(String _path, String _apk) {
592            path = _path;
593            apk = _apk;
594        }
595    }
596
597    // Currently known shared libraries.
598    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
599            new ArrayMap<String, SharedLibraryEntry>();
600
601    // All available activities, for your resolving pleasure.
602    final ActivityIntentResolver mActivities =
603            new ActivityIntentResolver();
604
605    // All available receivers, for your resolving pleasure.
606    final ActivityIntentResolver mReceivers =
607            new ActivityIntentResolver();
608
609    // All available services, for your resolving pleasure.
610    final ServiceIntentResolver mServices = new ServiceIntentResolver();
611
612    // All available providers, for your resolving pleasure.
613    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
614
615    // Mapping from provider base names (first directory in content URI codePath)
616    // to the provider information.
617    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
618            new ArrayMap<String, PackageParser.Provider>();
619
620    // Mapping from instrumentation class names to info about them.
621    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
622            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
623
624    // Mapping from permission names to info about them.
625    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
626            new ArrayMap<String, PackageParser.PermissionGroup>();
627
628    // Packages whose data we have transfered into another package, thus
629    // should no longer exist.
630    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
631
632    // Broadcast actions that are only available to the system.
633    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
634
635    /** List of packages waiting for verification. */
636    final SparseArray<PackageVerificationState> mPendingVerification
637            = new SparseArray<PackageVerificationState>();
638
639    /** Set of packages associated with each app op permission. */
640    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
641
642    final PackageInstallerService mInstallerService;
643
644    private final PackageDexOptimizer mPackageDexOptimizer;
645
646    private AtomicInteger mNextMoveId = new AtomicInteger();
647    private final MoveCallbacks mMoveCallbacks;
648
649    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
650
651    // Cache of users who need badging.
652    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
653
654    /** Token for keys in mPendingVerification. */
655    private int mPendingVerificationToken = 0;
656
657    volatile boolean mSystemReady;
658    volatile boolean mSafeMode;
659    volatile boolean mHasSystemUidErrors;
660
661    ApplicationInfo mAndroidApplication;
662    final ActivityInfo mResolveActivity = new ActivityInfo();
663    final ResolveInfo mResolveInfo = new ResolveInfo();
664    ComponentName mResolveComponentName;
665    PackageParser.Package mPlatformPackage;
666    ComponentName mCustomResolverComponentName;
667
668    boolean mResolverReplaced = false;
669
670    private final @Nullable ComponentName mIntentFilterVerifierComponent;
671    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
672
673    private int mIntentFilterVerificationToken = 0;
674
675    /** Component that knows whether or not an ephemeral application exists */
676    final ComponentName mEphemeralResolverComponent;
677    /** The service connection to the ephemeral resolver */
678    final EphemeralResolverConnection mEphemeralResolverConnection;
679
680    /** Component used to install ephemeral applications */
681    final ComponentName mEphemeralInstallerComponent;
682    final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo();
683    final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo();
684
685    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
686            = new SparseArray<IntentFilterVerificationState>();
687
688    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy =
689            new DefaultPermissionGrantPolicy(this);
690
691    // List of packages names to keep cached, even if they are uninstalled for all users
692    private List<String> mKeepUninstalledPackages;
693
694    private static class IFVerificationParams {
695        PackageParser.Package pkg;
696        boolean replacing;
697        int userId;
698        int verifierUid;
699
700        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
701                int _userId, int _verifierUid) {
702            pkg = _pkg;
703            replacing = _replacing;
704            userId = _userId;
705            replacing = _replacing;
706            verifierUid = _verifierUid;
707        }
708    }
709
710    private interface IntentFilterVerifier<T extends IntentFilter> {
711        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
712                                               T filter, String packageName);
713        void startVerifications(int userId);
714        void receiveVerificationResponse(int verificationId);
715    }
716
717    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
718        private Context mContext;
719        private ComponentName mIntentFilterVerifierComponent;
720        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
721
722        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
723            mContext = context;
724            mIntentFilterVerifierComponent = verifierComponent;
725        }
726
727        private String getDefaultScheme() {
728            return IntentFilter.SCHEME_HTTPS;
729        }
730
731        @Override
732        public void startVerifications(int userId) {
733            // Launch verifications requests
734            int count = mCurrentIntentFilterVerifications.size();
735            for (int n=0; n<count; n++) {
736                int verificationId = mCurrentIntentFilterVerifications.get(n);
737                final IntentFilterVerificationState ivs =
738                        mIntentFilterVerificationStates.get(verificationId);
739
740                String packageName = ivs.getPackageName();
741
742                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
743                final int filterCount = filters.size();
744                ArraySet<String> domainsSet = new ArraySet<>();
745                for (int m=0; m<filterCount; m++) {
746                    PackageParser.ActivityIntentInfo filter = filters.get(m);
747                    domainsSet.addAll(filter.getHostsList());
748                }
749                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
750                synchronized (mPackages) {
751                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
752                            packageName, domainsList) != null) {
753                        scheduleWriteSettingsLocked();
754                    }
755                }
756                sendVerificationRequest(userId, verificationId, ivs);
757            }
758            mCurrentIntentFilterVerifications.clear();
759        }
760
761        private void sendVerificationRequest(int userId, int verificationId,
762                IntentFilterVerificationState ivs) {
763
764            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
765            verificationIntent.putExtra(
766                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
767                    verificationId);
768            verificationIntent.putExtra(
769                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
770                    getDefaultScheme());
771            verificationIntent.putExtra(
772                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
773                    ivs.getHostsString());
774            verificationIntent.putExtra(
775                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
776                    ivs.getPackageName());
777            verificationIntent.setComponent(mIntentFilterVerifierComponent);
778            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
779
780            UserHandle user = new UserHandle(userId);
781            mContext.sendBroadcastAsUser(verificationIntent, user);
782            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
783                    "Sending IntentFilter verification broadcast");
784        }
785
786        public void receiveVerificationResponse(int verificationId) {
787            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
788
789            final boolean verified = ivs.isVerified();
790
791            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
792            final int count = filters.size();
793            if (DEBUG_DOMAIN_VERIFICATION) {
794                Slog.i(TAG, "Received verification response " + verificationId
795                        + " for " + count + " filters, verified=" + verified);
796            }
797            for (int n=0; n<count; n++) {
798                PackageParser.ActivityIntentInfo filter = filters.get(n);
799                filter.setVerified(verified);
800
801                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
802                        + " verified with result:" + verified + " and hosts:"
803                        + ivs.getHostsString());
804            }
805
806            mIntentFilterVerificationStates.remove(verificationId);
807
808            final String packageName = ivs.getPackageName();
809            IntentFilterVerificationInfo ivi = null;
810
811            synchronized (mPackages) {
812                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
813            }
814            if (ivi == null) {
815                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
816                        + verificationId + " packageName:" + packageName);
817                return;
818            }
819            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
820                    "Updating IntentFilterVerificationInfo for package " + packageName
821                            +" verificationId:" + verificationId);
822
823            synchronized (mPackages) {
824                if (verified) {
825                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
826                } else {
827                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
828                }
829                scheduleWriteSettingsLocked();
830
831                final int userId = ivs.getUserId();
832                if (userId != UserHandle.USER_ALL) {
833                    final int userStatus =
834                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
835
836                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
837                    boolean needUpdate = false;
838
839                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
840                    // already been set by the User thru the Disambiguation dialog
841                    switch (userStatus) {
842                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
843                            if (verified) {
844                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
845                            } else {
846                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
847                            }
848                            needUpdate = true;
849                            break;
850
851                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
852                            if (verified) {
853                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
854                                needUpdate = true;
855                            }
856                            break;
857
858                        default:
859                            // Nothing to do
860                    }
861
862                    if (needUpdate) {
863                        mSettings.updateIntentFilterVerificationStatusLPw(
864                                packageName, updatedStatus, userId);
865                        scheduleWritePackageRestrictionsLocked(userId);
866                    }
867                }
868            }
869        }
870
871        @Override
872        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
873                    ActivityIntentInfo filter, String packageName) {
874            if (!hasValidDomains(filter)) {
875                return false;
876            }
877            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
878            if (ivs == null) {
879                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
880                        packageName);
881            }
882            if (DEBUG_DOMAIN_VERIFICATION) {
883                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
884            }
885            ivs.addFilter(filter);
886            return true;
887        }
888
889        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
890                int userId, int verificationId, String packageName) {
891            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
892                    verifierUid, userId, packageName);
893            ivs.setPendingState();
894            synchronized (mPackages) {
895                mIntentFilterVerificationStates.append(verificationId, ivs);
896                mCurrentIntentFilterVerifications.add(verificationId);
897            }
898            return ivs;
899        }
900    }
901
902    private static boolean hasValidDomains(ActivityIntentInfo filter) {
903        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
904                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
905                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
906    }
907
908    // Set of pending broadcasts for aggregating enable/disable of components.
909    static class PendingPackageBroadcasts {
910        // for each user id, a map of <package name -> components within that package>
911        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
912
913        public PendingPackageBroadcasts() {
914            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
915        }
916
917        public ArrayList<String> get(int userId, String packageName) {
918            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
919            return packages.get(packageName);
920        }
921
922        public void put(int userId, String packageName, ArrayList<String> components) {
923            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
924            packages.put(packageName, components);
925        }
926
927        public void remove(int userId, String packageName) {
928            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
929            if (packages != null) {
930                packages.remove(packageName);
931            }
932        }
933
934        public void remove(int userId) {
935            mUidMap.remove(userId);
936        }
937
938        public int userIdCount() {
939            return mUidMap.size();
940        }
941
942        public int userIdAt(int n) {
943            return mUidMap.keyAt(n);
944        }
945
946        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
947            return mUidMap.get(userId);
948        }
949
950        public int size() {
951            // total number of pending broadcast entries across all userIds
952            int num = 0;
953            for (int i = 0; i< mUidMap.size(); i++) {
954                num += mUidMap.valueAt(i).size();
955            }
956            return num;
957        }
958
959        public void clear() {
960            mUidMap.clear();
961        }
962
963        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
964            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
965            if (map == null) {
966                map = new ArrayMap<String, ArrayList<String>>();
967                mUidMap.put(userId, map);
968            }
969            return map;
970        }
971    }
972    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
973
974    // Service Connection to remote media container service to copy
975    // package uri's from external media onto secure containers
976    // or internal storage.
977    private IMediaContainerService mContainerService = null;
978
979    static final int SEND_PENDING_BROADCAST = 1;
980    static final int MCS_BOUND = 3;
981    static final int END_COPY = 4;
982    static final int INIT_COPY = 5;
983    static final int MCS_UNBIND = 6;
984    static final int START_CLEANING_PACKAGE = 7;
985    static final int FIND_INSTALL_LOC = 8;
986    static final int POST_INSTALL = 9;
987    static final int MCS_RECONNECT = 10;
988    static final int MCS_GIVE_UP = 11;
989    static final int UPDATED_MEDIA_STATUS = 12;
990    static final int WRITE_SETTINGS = 13;
991    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
992    static final int PACKAGE_VERIFIED = 15;
993    static final int CHECK_PENDING_VERIFICATION = 16;
994    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
995    static final int INTENT_FILTER_VERIFIED = 18;
996
997    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
998
999    // Delay time in millisecs
1000    static final int BROADCAST_DELAY = 10 * 1000;
1001
1002    static UserManagerService sUserManager;
1003
1004    // Stores a list of users whose package restrictions file needs to be updated
1005    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1006
1007    final private DefaultContainerConnection mDefContainerConn =
1008            new DefaultContainerConnection();
1009    class DefaultContainerConnection implements ServiceConnection {
1010        public void onServiceConnected(ComponentName name, IBinder service) {
1011            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1012            IMediaContainerService imcs =
1013                IMediaContainerService.Stub.asInterface(service);
1014            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1015        }
1016
1017        public void onServiceDisconnected(ComponentName name) {
1018            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1019        }
1020    }
1021
1022    // Recordkeeping of restore-after-install operations that are currently in flight
1023    // between the Package Manager and the Backup Manager
1024    static class PostInstallData {
1025        public InstallArgs args;
1026        public PackageInstalledInfo res;
1027
1028        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1029            args = _a;
1030            res = _r;
1031        }
1032    }
1033
1034    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1035    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1036
1037    // XML tags for backup/restore of various bits of state
1038    private static final String TAG_PREFERRED_BACKUP = "pa";
1039    private static final String TAG_DEFAULT_APPS = "da";
1040    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1041
1042    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1043    private static final String TAG_ALL_GRANTS = "rt-grants";
1044    private static final String TAG_GRANT = "grant";
1045    private static final String ATTR_PACKAGE_NAME = "pkg";
1046
1047    private static final String TAG_PERMISSION = "perm";
1048    private static final String ATTR_PERMISSION_NAME = "name";
1049    private static final String ATTR_IS_GRANTED = "g";
1050    private static final String ATTR_USER_SET = "set";
1051    private static final String ATTR_USER_FIXED = "fixed";
1052    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1053
1054    // System/policy permission grants are not backed up
1055    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1056            FLAG_PERMISSION_POLICY_FIXED
1057            | FLAG_PERMISSION_SYSTEM_FIXED
1058            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1059
1060    // And we back up these user-adjusted states
1061    private static final int USER_RUNTIME_GRANT_MASK =
1062            FLAG_PERMISSION_USER_SET
1063            | FLAG_PERMISSION_USER_FIXED
1064            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1065
1066    final @Nullable String mRequiredVerifierPackage;
1067    final @Nullable String mRequiredInstallerPackage;
1068    final @Nullable String mSetupWizardPackage;
1069
1070    private final PackageUsage mPackageUsage = new PackageUsage();
1071
1072    private class PackageUsage {
1073        private static final int WRITE_INTERVAL
1074            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
1075
1076        private final Object mFileLock = new Object();
1077        private final AtomicLong mLastWritten = new AtomicLong(0);
1078        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
1079
1080        private boolean mIsHistoricalPackageUsageAvailable = true;
1081
1082        boolean isHistoricalPackageUsageAvailable() {
1083            return mIsHistoricalPackageUsageAvailable;
1084        }
1085
1086        void write(boolean force) {
1087            if (force) {
1088                writeInternal();
1089                return;
1090            }
1091            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
1092                && !DEBUG_DEXOPT) {
1093                return;
1094            }
1095            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
1096                new Thread("PackageUsage_DiskWriter") {
1097                    @Override
1098                    public void run() {
1099                        try {
1100                            writeInternal();
1101                        } finally {
1102                            mBackgroundWriteRunning.set(false);
1103                        }
1104                    }
1105                }.start();
1106            }
1107        }
1108
1109        private void writeInternal() {
1110            synchronized (mPackages) {
1111                synchronized (mFileLock) {
1112                    AtomicFile file = getFile();
1113                    FileOutputStream f = null;
1114                    try {
1115                        f = file.startWrite();
1116                        BufferedOutputStream out = new BufferedOutputStream(f);
1117                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
1118                        StringBuilder sb = new StringBuilder();
1119                        for (PackageParser.Package pkg : mPackages.values()) {
1120                            if (pkg.mLastPackageUsageTimeInMills == 0) {
1121                                continue;
1122                            }
1123                            sb.setLength(0);
1124                            sb.append(pkg.packageName);
1125                            sb.append(' ');
1126                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
1127                            sb.append('\n');
1128                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
1129                        }
1130                        out.flush();
1131                        file.finishWrite(f);
1132                    } catch (IOException e) {
1133                        if (f != null) {
1134                            file.failWrite(f);
1135                        }
1136                        Log.e(TAG, "Failed to write package usage times", e);
1137                    }
1138                }
1139            }
1140            mLastWritten.set(SystemClock.elapsedRealtime());
1141        }
1142
1143        void readLP() {
1144            synchronized (mFileLock) {
1145                AtomicFile file = getFile();
1146                BufferedInputStream in = null;
1147                try {
1148                    in = new BufferedInputStream(file.openRead());
1149                    StringBuffer sb = new StringBuffer();
1150                    while (true) {
1151                        String packageName = readToken(in, sb, ' ');
1152                        if (packageName == null) {
1153                            break;
1154                        }
1155                        String timeInMillisString = readToken(in, sb, '\n');
1156                        if (timeInMillisString == null) {
1157                            throw new IOException("Failed to find last usage time for package "
1158                                                  + packageName);
1159                        }
1160                        PackageParser.Package pkg = mPackages.get(packageName);
1161                        if (pkg == null) {
1162                            continue;
1163                        }
1164                        long timeInMillis;
1165                        try {
1166                            timeInMillis = Long.parseLong(timeInMillisString);
1167                        } catch (NumberFormatException e) {
1168                            throw new IOException("Failed to parse " + timeInMillisString
1169                                                  + " as a long.", e);
1170                        }
1171                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
1172                    }
1173                } catch (FileNotFoundException expected) {
1174                    mIsHistoricalPackageUsageAvailable = false;
1175                } catch (IOException e) {
1176                    Log.w(TAG, "Failed to read package usage times", e);
1177                } finally {
1178                    IoUtils.closeQuietly(in);
1179                }
1180            }
1181            mLastWritten.set(SystemClock.elapsedRealtime());
1182        }
1183
1184        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
1185                throws IOException {
1186            sb.setLength(0);
1187            while (true) {
1188                int ch = in.read();
1189                if (ch == -1) {
1190                    if (sb.length() == 0) {
1191                        return null;
1192                    }
1193                    throw new IOException("Unexpected EOF");
1194                }
1195                if (ch == endOfToken) {
1196                    return sb.toString();
1197                }
1198                sb.append((char)ch);
1199            }
1200        }
1201
1202        private AtomicFile getFile() {
1203            File dataDir = Environment.getDataDirectory();
1204            File systemDir = new File(dataDir, "system");
1205            File fname = new File(systemDir, "package-usage.list");
1206            return new AtomicFile(fname);
1207        }
1208    }
1209
1210    class PackageHandler extends Handler {
1211        private boolean mBound = false;
1212        final ArrayList<HandlerParams> mPendingInstalls =
1213            new ArrayList<HandlerParams>();
1214
1215        private boolean connectToService() {
1216            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1217                    " DefaultContainerService");
1218            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1219            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1220            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1221                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1222                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1223                mBound = true;
1224                return true;
1225            }
1226            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1227            return false;
1228        }
1229
1230        private void disconnectService() {
1231            mContainerService = null;
1232            mBound = false;
1233            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1234            mContext.unbindService(mDefContainerConn);
1235            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1236        }
1237
1238        PackageHandler(Looper looper) {
1239            super(looper);
1240        }
1241
1242        public void handleMessage(Message msg) {
1243            try {
1244                doHandleMessage(msg);
1245            } finally {
1246                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1247            }
1248        }
1249
1250        void doHandleMessage(Message msg) {
1251            switch (msg.what) {
1252                case INIT_COPY: {
1253                    HandlerParams params = (HandlerParams) msg.obj;
1254                    int idx = mPendingInstalls.size();
1255                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1256                    // If a bind was already initiated we dont really
1257                    // need to do anything. The pending install
1258                    // will be processed later on.
1259                    if (!mBound) {
1260                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1261                                System.identityHashCode(mHandler));
1262                        // If this is the only one pending we might
1263                        // have to bind to the service again.
1264                        if (!connectToService()) {
1265                            Slog.e(TAG, "Failed to bind to media container service");
1266                            params.serviceError();
1267                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1268                                    System.identityHashCode(mHandler));
1269                            if (params.traceMethod != null) {
1270                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1271                                        params.traceCookie);
1272                            }
1273                            return;
1274                        } else {
1275                            // Once we bind to the service, the first
1276                            // pending request will be processed.
1277                            mPendingInstalls.add(idx, params);
1278                        }
1279                    } else {
1280                        mPendingInstalls.add(idx, params);
1281                        // Already bound to the service. Just make
1282                        // sure we trigger off processing the first request.
1283                        if (idx == 0) {
1284                            mHandler.sendEmptyMessage(MCS_BOUND);
1285                        }
1286                    }
1287                    break;
1288                }
1289                case MCS_BOUND: {
1290                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1291                    if (msg.obj != null) {
1292                        mContainerService = (IMediaContainerService) msg.obj;
1293                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1294                                System.identityHashCode(mHandler));
1295                    }
1296                    if (mContainerService == null) {
1297                        if (!mBound) {
1298                            // Something seriously wrong since we are not bound and we are not
1299                            // waiting for connection. Bail out.
1300                            Slog.e(TAG, "Cannot bind to media container service");
1301                            for (HandlerParams params : mPendingInstalls) {
1302                                // Indicate service bind error
1303                                params.serviceError();
1304                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1305                                        System.identityHashCode(params));
1306                                if (params.traceMethod != null) {
1307                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1308                                            params.traceMethod, params.traceCookie);
1309                                }
1310                                return;
1311                            }
1312                            mPendingInstalls.clear();
1313                        } else {
1314                            Slog.w(TAG, "Waiting to connect to media container service");
1315                        }
1316                    } else if (mPendingInstalls.size() > 0) {
1317                        HandlerParams params = mPendingInstalls.get(0);
1318                        if (params != null) {
1319                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1320                                    System.identityHashCode(params));
1321                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1322                            if (params.startCopy()) {
1323                                // We are done...  look for more work or to
1324                                // go idle.
1325                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1326                                        "Checking for more work or unbind...");
1327                                // Delete pending install
1328                                if (mPendingInstalls.size() > 0) {
1329                                    mPendingInstalls.remove(0);
1330                                }
1331                                if (mPendingInstalls.size() == 0) {
1332                                    if (mBound) {
1333                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1334                                                "Posting delayed MCS_UNBIND");
1335                                        removeMessages(MCS_UNBIND);
1336                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1337                                        // Unbind after a little delay, to avoid
1338                                        // continual thrashing.
1339                                        sendMessageDelayed(ubmsg, 10000);
1340                                    }
1341                                } else {
1342                                    // There are more pending requests in queue.
1343                                    // Just post MCS_BOUND message to trigger processing
1344                                    // of next pending install.
1345                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1346                                            "Posting MCS_BOUND for next work");
1347                                    mHandler.sendEmptyMessage(MCS_BOUND);
1348                                }
1349                            }
1350                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1351                        }
1352                    } else {
1353                        // Should never happen ideally.
1354                        Slog.w(TAG, "Empty queue");
1355                    }
1356                    break;
1357                }
1358                case MCS_RECONNECT: {
1359                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1360                    if (mPendingInstalls.size() > 0) {
1361                        if (mBound) {
1362                            disconnectService();
1363                        }
1364                        if (!connectToService()) {
1365                            Slog.e(TAG, "Failed to bind to media container service");
1366                            for (HandlerParams params : mPendingInstalls) {
1367                                // Indicate service bind error
1368                                params.serviceError();
1369                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1370                                        System.identityHashCode(params));
1371                            }
1372                            mPendingInstalls.clear();
1373                        }
1374                    }
1375                    break;
1376                }
1377                case MCS_UNBIND: {
1378                    // If there is no actual work left, then time to unbind.
1379                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1380
1381                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1382                        if (mBound) {
1383                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1384
1385                            disconnectService();
1386                        }
1387                    } else if (mPendingInstalls.size() > 0) {
1388                        // There are more pending requests in queue.
1389                        // Just post MCS_BOUND message to trigger processing
1390                        // of next pending install.
1391                        mHandler.sendEmptyMessage(MCS_BOUND);
1392                    }
1393
1394                    break;
1395                }
1396                case MCS_GIVE_UP: {
1397                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1398                    HandlerParams params = mPendingInstalls.remove(0);
1399                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1400                            System.identityHashCode(params));
1401                    break;
1402                }
1403                case SEND_PENDING_BROADCAST: {
1404                    String packages[];
1405                    ArrayList<String> components[];
1406                    int size = 0;
1407                    int uids[];
1408                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1409                    synchronized (mPackages) {
1410                        if (mPendingBroadcasts == null) {
1411                            return;
1412                        }
1413                        size = mPendingBroadcasts.size();
1414                        if (size <= 0) {
1415                            // Nothing to be done. Just return
1416                            return;
1417                        }
1418                        packages = new String[size];
1419                        components = new ArrayList[size];
1420                        uids = new int[size];
1421                        int i = 0;  // filling out the above arrays
1422
1423                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1424                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1425                            Iterator<Map.Entry<String, ArrayList<String>>> it
1426                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1427                                            .entrySet().iterator();
1428                            while (it.hasNext() && i < size) {
1429                                Map.Entry<String, ArrayList<String>> ent = it.next();
1430                                packages[i] = ent.getKey();
1431                                components[i] = ent.getValue();
1432                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1433                                uids[i] = (ps != null)
1434                                        ? UserHandle.getUid(packageUserId, ps.appId)
1435                                        : -1;
1436                                i++;
1437                            }
1438                        }
1439                        size = i;
1440                        mPendingBroadcasts.clear();
1441                    }
1442                    // Send broadcasts
1443                    for (int i = 0; i < size; i++) {
1444                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1445                    }
1446                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1447                    break;
1448                }
1449                case START_CLEANING_PACKAGE: {
1450                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1451                    final String packageName = (String)msg.obj;
1452                    final int userId = msg.arg1;
1453                    final boolean andCode = msg.arg2 != 0;
1454                    synchronized (mPackages) {
1455                        if (userId == UserHandle.USER_ALL) {
1456                            int[] users = sUserManager.getUserIds();
1457                            for (int user : users) {
1458                                mSettings.addPackageToCleanLPw(
1459                                        new PackageCleanItem(user, packageName, andCode));
1460                            }
1461                        } else {
1462                            mSettings.addPackageToCleanLPw(
1463                                    new PackageCleanItem(userId, packageName, andCode));
1464                        }
1465                    }
1466                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1467                    startCleaningPackages();
1468                } break;
1469                case POST_INSTALL: {
1470                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1471
1472                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1473                    mRunningInstalls.delete(msg.arg1);
1474
1475                    if (data != null) {
1476                        InstallArgs args = data.args;
1477                        PackageInstalledInfo parentRes = data.res;
1478
1479                        final boolean grantPermissions = (args.installFlags
1480                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1481                        final boolean killApp = (args.installFlags
1482                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1483                        final String[] grantedPermissions = args.installGrantPermissions;
1484
1485                        // Handle the parent package
1486                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1487                                grantedPermissions, args.observer);
1488
1489                        // Handle the child packages
1490                        final int childCount = (parentRes.addedChildPackages != null)
1491                                ? parentRes.addedChildPackages.size() : 0;
1492                        for (int i = 0; i < childCount; i++) {
1493                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1494                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1495                                    grantedPermissions, args.observer);
1496                        }
1497
1498                        // Log tracing if needed
1499                        if (args.traceMethod != null) {
1500                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1501                                    args.traceCookie);
1502                        }
1503                    } else {
1504                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1505                    }
1506
1507                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1508                } break;
1509                case UPDATED_MEDIA_STATUS: {
1510                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1511                    boolean reportStatus = msg.arg1 == 1;
1512                    boolean doGc = msg.arg2 == 1;
1513                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1514                    if (doGc) {
1515                        // Force a gc to clear up stale containers.
1516                        Runtime.getRuntime().gc();
1517                    }
1518                    if (msg.obj != null) {
1519                        @SuppressWarnings("unchecked")
1520                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1521                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1522                        // Unload containers
1523                        unloadAllContainers(args);
1524                    }
1525                    if (reportStatus) {
1526                        try {
1527                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1528                            PackageHelper.getMountService().finishMediaUpdate();
1529                        } catch (RemoteException e) {
1530                            Log.e(TAG, "MountService not running?");
1531                        }
1532                    }
1533                } break;
1534                case WRITE_SETTINGS: {
1535                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1536                    synchronized (mPackages) {
1537                        removeMessages(WRITE_SETTINGS);
1538                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1539                        mSettings.writeLPr();
1540                        mDirtyUsers.clear();
1541                    }
1542                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1543                } break;
1544                case WRITE_PACKAGE_RESTRICTIONS: {
1545                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1546                    synchronized (mPackages) {
1547                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1548                        for (int userId : mDirtyUsers) {
1549                            mSettings.writePackageRestrictionsLPr(userId);
1550                        }
1551                        mDirtyUsers.clear();
1552                    }
1553                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1554                } break;
1555                case CHECK_PENDING_VERIFICATION: {
1556                    final int verificationId = msg.arg1;
1557                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1558
1559                    if ((state != null) && !state.timeoutExtended()) {
1560                        final InstallArgs args = state.getInstallArgs();
1561                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1562
1563                        Slog.i(TAG, "Verification timed out for " + originUri);
1564                        mPendingVerification.remove(verificationId);
1565
1566                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1567
1568                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1569                            Slog.i(TAG, "Continuing with installation of " + originUri);
1570                            state.setVerifierResponse(Binder.getCallingUid(),
1571                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1572                            broadcastPackageVerified(verificationId, originUri,
1573                                    PackageManager.VERIFICATION_ALLOW,
1574                                    state.getInstallArgs().getUser());
1575                            try {
1576                                ret = args.copyApk(mContainerService, true);
1577                            } catch (RemoteException e) {
1578                                Slog.e(TAG, "Could not contact the ContainerService");
1579                            }
1580                        } else {
1581                            broadcastPackageVerified(verificationId, originUri,
1582                                    PackageManager.VERIFICATION_REJECT,
1583                                    state.getInstallArgs().getUser());
1584                        }
1585
1586                        Trace.asyncTraceEnd(
1587                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1588
1589                        processPendingInstall(args, ret);
1590                        mHandler.sendEmptyMessage(MCS_UNBIND);
1591                    }
1592                    break;
1593                }
1594                case PACKAGE_VERIFIED: {
1595                    final int verificationId = msg.arg1;
1596
1597                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1598                    if (state == null) {
1599                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1600                        break;
1601                    }
1602
1603                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1604
1605                    state.setVerifierResponse(response.callerUid, response.code);
1606
1607                    if (state.isVerificationComplete()) {
1608                        mPendingVerification.remove(verificationId);
1609
1610                        final InstallArgs args = state.getInstallArgs();
1611                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1612
1613                        int ret;
1614                        if (state.isInstallAllowed()) {
1615                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1616                            broadcastPackageVerified(verificationId, originUri,
1617                                    response.code, state.getInstallArgs().getUser());
1618                            try {
1619                                ret = args.copyApk(mContainerService, true);
1620                            } catch (RemoteException e) {
1621                                Slog.e(TAG, "Could not contact the ContainerService");
1622                            }
1623                        } else {
1624                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1625                        }
1626
1627                        Trace.asyncTraceEnd(
1628                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1629
1630                        processPendingInstall(args, ret);
1631                        mHandler.sendEmptyMessage(MCS_UNBIND);
1632                    }
1633
1634                    break;
1635                }
1636                case START_INTENT_FILTER_VERIFICATIONS: {
1637                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1638                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1639                            params.replacing, params.pkg);
1640                    break;
1641                }
1642                case INTENT_FILTER_VERIFIED: {
1643                    final int verificationId = msg.arg1;
1644
1645                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1646                            verificationId);
1647                    if (state == null) {
1648                        Slog.w(TAG, "Invalid IntentFilter verification token "
1649                                + verificationId + " received");
1650                        break;
1651                    }
1652
1653                    final int userId = state.getUserId();
1654
1655                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1656                            "Processing IntentFilter verification with token:"
1657                            + verificationId + " and userId:" + userId);
1658
1659                    final IntentFilterVerificationResponse response =
1660                            (IntentFilterVerificationResponse) msg.obj;
1661
1662                    state.setVerifierResponse(response.callerUid, response.code);
1663
1664                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1665                            "IntentFilter verification with token:" + verificationId
1666                            + " and userId:" + userId
1667                            + " is settings verifier response with response code:"
1668                            + response.code);
1669
1670                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1671                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1672                                + response.getFailedDomainsString());
1673                    }
1674
1675                    if (state.isVerificationComplete()) {
1676                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1677                    } else {
1678                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1679                                "IntentFilter verification with token:" + verificationId
1680                                + " was not said to be complete");
1681                    }
1682
1683                    break;
1684                }
1685            }
1686        }
1687    }
1688
1689    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1690            boolean killApp, String[] grantedPermissions,
1691            IPackageInstallObserver2 installObserver) {
1692        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1693            // Send the removed broadcasts
1694            if (res.removedInfo != null) {
1695                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1696            }
1697
1698            // Now that we successfully installed the package, grant runtime
1699            // permissions if requested before broadcasting the install.
1700            if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion
1701                    >= Build.VERSION_CODES.M) {
1702                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1703            }
1704
1705            final boolean update = res.removedInfo != null
1706                    && res.removedInfo.removedPackage != null;
1707
1708            // If this is the first time we have child packages for a disabled privileged
1709            // app that had no children, we grant requested runtime permissions to the new
1710            // children if the parent on the system image had them already granted.
1711            if (res.pkg.parentPackage != null) {
1712                synchronized (mPackages) {
1713                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1714                }
1715            }
1716
1717            synchronized (mPackages) {
1718                mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg);
1719            }
1720
1721            final String packageName = res.pkg.applicationInfo.packageName;
1722            Bundle extras = new Bundle(1);
1723            extras.putInt(Intent.EXTRA_UID, res.uid);
1724
1725            // Determine the set of users who are adding this package for
1726            // the first time vs. those who are seeing an update.
1727            int[] firstUsers = EMPTY_INT_ARRAY;
1728            int[] updateUsers = EMPTY_INT_ARRAY;
1729            if (res.origUsers == null || res.origUsers.length == 0) {
1730                firstUsers = res.newUsers;
1731            } else {
1732                for (int newUser : res.newUsers) {
1733                    boolean isNew = true;
1734                    for (int origUser : res.origUsers) {
1735                        if (origUser == newUser) {
1736                            isNew = false;
1737                            break;
1738                        }
1739                    }
1740                    if (isNew) {
1741                        firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1742                    } else {
1743                        updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1744                    }
1745                }
1746            }
1747
1748            // Send installed broadcasts if the install/update is not ephemeral
1749            if (!isEphemeral(res.pkg)) {
1750                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1751
1752                // Send added for users that see the package for the first time
1753                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1754                        extras, 0 /*flags*/, null /*targetPackage*/,
1755                        null /*finishedReceiver*/, firstUsers);
1756
1757                // Send added for users that don't see the package for the first time
1758                if (update) {
1759                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1760                }
1761                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1762                        extras, 0 /*flags*/, null /*targetPackage*/,
1763                        null /*finishedReceiver*/, updateUsers);
1764
1765                // Send replaced for users that don't see the package for the first time
1766                if (update) {
1767                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1768                            packageName, extras, 0 /*flags*/,
1769                            null /*targetPackage*/, null /*finishedReceiver*/,
1770                            updateUsers);
1771                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1772                            null /*package*/, null /*extras*/, 0 /*flags*/,
1773                            packageName /*targetPackage*/,
1774                            null /*finishedReceiver*/, updateUsers);
1775                }
1776
1777                // Send broadcast package appeared if forward locked/external for all users
1778                // treat asec-hosted packages like removable media on upgrade
1779                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1780                    if (DEBUG_INSTALL) {
1781                        Slog.i(TAG, "upgrading pkg " + res.pkg
1782                                + " is ASEC-hosted -> AVAILABLE");
1783                    }
1784                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
1785                    ArrayList<String> pkgList = new ArrayList<>(1);
1786                    pkgList.add(packageName);
1787                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
1788                }
1789            }
1790
1791            // Work that needs to happen on first install within each user
1792            if (firstUsers != null && firstUsers.length > 0) {
1793                synchronized (mPackages) {
1794                    for (int userId : firstUsers) {
1795                        // If this app is a browser and it's newly-installed for some
1796                        // users, clear any default-browser state in those users. The
1797                        // app's nature doesn't depend on the user, so we can just check
1798                        // its browser nature in any user and generalize.
1799                        if (packageIsBrowser(packageName, userId)) {
1800                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
1801                        }
1802
1803                        // We may also need to apply pending (restored) runtime
1804                        // permission grants within these users.
1805                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
1806                    }
1807                }
1808            }
1809
1810            // Log current value of "unknown sources" setting
1811            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1812                    getUnknownSourcesSettings());
1813
1814            // Force a gc to clear up things
1815            Runtime.getRuntime().gc();
1816
1817            // Remove the replaced package's older resources safely now
1818            // We delete after a gc for applications  on sdcard.
1819            if (res.removedInfo != null && res.removedInfo.args != null) {
1820                synchronized (mInstallLock) {
1821                    res.removedInfo.args.doPostDeleteLI(true);
1822                }
1823            }
1824        }
1825
1826        // If someone is watching installs - notify them
1827        if (installObserver != null) {
1828            try {
1829                Bundle extras = extrasForInstallResult(res);
1830                installObserver.onPackageInstalled(res.name, res.returnCode,
1831                        res.returnMsg, extras);
1832            } catch (RemoteException e) {
1833                Slog.i(TAG, "Observer no longer exists.");
1834            }
1835        }
1836    }
1837
1838    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
1839            PackageParser.Package pkg) {
1840        if (pkg.parentPackage == null) {
1841            return;
1842        }
1843        if (pkg.requestedPermissions == null) {
1844            return;
1845        }
1846        final PackageSetting disabledSysParentPs = mSettings
1847                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
1848        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
1849                || !disabledSysParentPs.isPrivileged()
1850                || (disabledSysParentPs.childPackageNames != null
1851                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
1852            return;
1853        }
1854        final int[] allUserIds = sUserManager.getUserIds();
1855        final int permCount = pkg.requestedPermissions.size();
1856        for (int i = 0; i < permCount; i++) {
1857            String permission = pkg.requestedPermissions.get(i);
1858            BasePermission bp = mSettings.mPermissions.get(permission);
1859            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
1860                continue;
1861            }
1862            for (int userId : allUserIds) {
1863                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
1864                        permission, userId)) {
1865                    grantRuntimePermission(pkg.packageName, permission, userId);
1866                }
1867            }
1868        }
1869    }
1870
1871    private StorageEventListener mStorageListener = new StorageEventListener() {
1872        @Override
1873        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1874            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1875                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1876                    final String volumeUuid = vol.getFsUuid();
1877
1878                    // Clean up any users or apps that were removed or recreated
1879                    // while this volume was missing
1880                    reconcileUsers(volumeUuid);
1881                    reconcileApps(volumeUuid);
1882
1883                    // Clean up any install sessions that expired or were
1884                    // cancelled while this volume was missing
1885                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
1886
1887                    loadPrivatePackages(vol);
1888
1889                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1890                    unloadPrivatePackages(vol);
1891                }
1892            }
1893
1894            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1895                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1896                    updateExternalMediaStatus(true, false);
1897                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1898                    updateExternalMediaStatus(false, false);
1899                }
1900            }
1901        }
1902
1903        @Override
1904        public void onVolumeForgotten(String fsUuid) {
1905            if (TextUtils.isEmpty(fsUuid)) {
1906                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
1907                return;
1908            }
1909
1910            // Remove any apps installed on the forgotten volume
1911            synchronized (mPackages) {
1912                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
1913                for (PackageSetting ps : packages) {
1914                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
1915                    deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(),
1916                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
1917                }
1918
1919                mSettings.onVolumeForgotten(fsUuid);
1920                mSettings.writeLPr();
1921            }
1922        }
1923    };
1924
1925    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
1926            String[] grantedPermissions) {
1927        for (int userId : userIds) {
1928            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
1929        }
1930
1931        // We could have touched GID membership, so flush out packages.list
1932        synchronized (mPackages) {
1933            mSettings.writePackageListLPr();
1934        }
1935    }
1936
1937    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
1938            String[] grantedPermissions) {
1939        SettingBase sb = (SettingBase) pkg.mExtras;
1940        if (sb == null) {
1941            return;
1942        }
1943
1944        PermissionsState permissionsState = sb.getPermissionsState();
1945
1946        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
1947                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
1948
1949        synchronized (mPackages) {
1950            for (String permission : pkg.requestedPermissions) {
1951                BasePermission bp = mSettings.mPermissions.get(permission);
1952                if (bp != null && (bp.isRuntime() || bp.isDevelopment())
1953                        && (grantedPermissions == null
1954                               || ArrayUtils.contains(grantedPermissions, permission))) {
1955                    final int flags = permissionsState.getPermissionFlags(permission, userId);
1956                    // Installer cannot change immutable permissions.
1957                    if ((flags & immutableFlags) == 0) {
1958                        grantRuntimePermission(pkg.packageName, permission, userId);
1959                    }
1960                }
1961            }
1962        }
1963    }
1964
1965    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1966        Bundle extras = null;
1967        switch (res.returnCode) {
1968            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1969                extras = new Bundle();
1970                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1971                        res.origPermission);
1972                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1973                        res.origPackage);
1974                break;
1975            }
1976            case PackageManager.INSTALL_SUCCEEDED: {
1977                extras = new Bundle();
1978                extras.putBoolean(Intent.EXTRA_REPLACING,
1979                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1980                break;
1981            }
1982        }
1983        return extras;
1984    }
1985
1986    void scheduleWriteSettingsLocked() {
1987        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1988            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1989        }
1990    }
1991
1992    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
1993        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
1994        scheduleWritePackageRestrictionsLocked(userId);
1995    }
1996
1997    void scheduleWritePackageRestrictionsLocked(int userId) {
1998        final int[] userIds = (userId == UserHandle.USER_ALL)
1999                ? sUserManager.getUserIds() : new int[]{userId};
2000        for (int nextUserId : userIds) {
2001            if (!sUserManager.exists(nextUserId)) return;
2002            mDirtyUsers.add(nextUserId);
2003            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2004                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2005            }
2006        }
2007    }
2008
2009    public static PackageManagerService main(Context context, Installer installer,
2010            boolean factoryTest, boolean onlyCore) {
2011        // Self-check for initial settings.
2012        PackageManagerServiceCompilerMapping.checkProperties();
2013
2014        PackageManagerService m = new PackageManagerService(context, installer,
2015                factoryTest, onlyCore);
2016        m.enableSystemUserPackages();
2017        ServiceManager.addService("package", m);
2018        return m;
2019    }
2020
2021    private void enableSystemUserPackages() {
2022        if (!UserManager.isSplitSystemUser()) {
2023            return;
2024        }
2025        // For system user, enable apps based on the following conditions:
2026        // - app is whitelisted or belong to one of these groups:
2027        //   -- system app which has no launcher icons
2028        //   -- system app which has INTERACT_ACROSS_USERS permission
2029        //   -- system IME app
2030        // - app is not in the blacklist
2031        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2032        Set<String> enableApps = new ArraySet<>();
2033        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2034                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2035                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2036        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2037        enableApps.addAll(wlApps);
2038        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2039                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2040        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2041        enableApps.removeAll(blApps);
2042        Log.i(TAG, "Applications installed for system user: " + enableApps);
2043        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2044                UserHandle.SYSTEM);
2045        final int allAppsSize = allAps.size();
2046        synchronized (mPackages) {
2047            for (int i = 0; i < allAppsSize; i++) {
2048                String pName = allAps.get(i);
2049                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2050                // Should not happen, but we shouldn't be failing if it does
2051                if (pkgSetting == null) {
2052                    continue;
2053                }
2054                boolean install = enableApps.contains(pName);
2055                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2056                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2057                            + " for system user");
2058                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2059                }
2060            }
2061        }
2062    }
2063
2064    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2065        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2066                Context.DISPLAY_SERVICE);
2067        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2068    }
2069
2070    public PackageManagerService(Context context, Installer installer,
2071            boolean factoryTest, boolean onlyCore) {
2072        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2073                SystemClock.uptimeMillis());
2074
2075        if (mSdkVersion <= 0) {
2076            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2077        }
2078
2079        mContext = context;
2080        mFactoryTest = factoryTest;
2081        mOnlyCore = onlyCore;
2082        mMetrics = new DisplayMetrics();
2083        mSettings = new Settings(mPackages);
2084        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2085                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2086        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2087                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2088        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2089                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2090        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2091                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2092        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2093                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2094        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2095                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2096
2097        String separateProcesses = SystemProperties.get("debug.separate_processes");
2098        if (separateProcesses != null && separateProcesses.length() > 0) {
2099            if ("*".equals(separateProcesses)) {
2100                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2101                mSeparateProcesses = null;
2102                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2103            } else {
2104                mDefParseFlags = 0;
2105                mSeparateProcesses = separateProcesses.split(",");
2106                Slog.w(TAG, "Running with debug.separate_processes: "
2107                        + separateProcesses);
2108            }
2109        } else {
2110            mDefParseFlags = 0;
2111            mSeparateProcesses = null;
2112        }
2113
2114        mInstaller = installer;
2115        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2116                "*dexopt*");
2117        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2118
2119        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2120                FgThread.get().getLooper());
2121
2122        getDefaultDisplayMetrics(context, mMetrics);
2123
2124        SystemConfig systemConfig = SystemConfig.getInstance();
2125        mGlobalGids = systemConfig.getGlobalGids();
2126        mSystemPermissions = systemConfig.getSystemPermissions();
2127        mAvailableFeatures = systemConfig.getAvailableFeatures();
2128
2129        synchronized (mInstallLock) {
2130        // writer
2131        synchronized (mPackages) {
2132            mHandlerThread = new ServiceThread(TAG,
2133                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2134            mHandlerThread.start();
2135            mHandler = new PackageHandler(mHandlerThread.getLooper());
2136            mProcessLoggingHandler = new ProcessLoggingHandler();
2137            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2138
2139            File dataDir = Environment.getDataDirectory();
2140            mAppInstallDir = new File(dataDir, "app");
2141            mAppLib32InstallDir = new File(dataDir, "app-lib");
2142            mEphemeralInstallDir = new File(dataDir, "app-ephemeral");
2143            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2144            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2145
2146            sUserManager = new UserManagerService(context, this, mPackages);
2147
2148            // Propagate permission configuration in to package manager.
2149            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2150                    = systemConfig.getPermissions();
2151            for (int i=0; i<permConfig.size(); i++) {
2152                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2153                BasePermission bp = mSettings.mPermissions.get(perm.name);
2154                if (bp == null) {
2155                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2156                    mSettings.mPermissions.put(perm.name, bp);
2157                }
2158                if (perm.gids != null) {
2159                    bp.setGids(perm.gids, perm.perUser);
2160                }
2161            }
2162
2163            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2164            for (int i=0; i<libConfig.size(); i++) {
2165                mSharedLibraries.put(libConfig.keyAt(i),
2166                        new SharedLibraryEntry(libConfig.valueAt(i), null));
2167            }
2168
2169            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2170
2171            mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false));
2172
2173            String customResolverActivity = Resources.getSystem().getString(
2174                    R.string.config_customResolverActivity);
2175            if (TextUtils.isEmpty(customResolverActivity)) {
2176                customResolverActivity = null;
2177            } else {
2178                mCustomResolverComponentName = ComponentName.unflattenFromString(
2179                        customResolverActivity);
2180            }
2181
2182            long startTime = SystemClock.uptimeMillis();
2183
2184            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2185                    startTime);
2186
2187            // Set flag to monitor and not change apk file paths when
2188            // scanning install directories.
2189            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL;
2190
2191            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2192            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2193
2194            if (bootClassPath == null) {
2195                Slog.w(TAG, "No BOOTCLASSPATH found!");
2196            }
2197
2198            if (systemServerClassPath == null) {
2199                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2200            }
2201
2202            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
2203            final String[] dexCodeInstructionSets =
2204                    getDexCodeInstructionSets(
2205                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
2206
2207            /**
2208             * Ensure all external libraries have had dexopt run on them.
2209             */
2210            if (mSharedLibraries.size() > 0) {
2211                // NOTE: For now, we're compiling these system "shared libraries"
2212                // (and framework jars) into all available architectures. It's possible
2213                // to compile them only when we come across an app that uses them (there's
2214                // already logic for that in scanPackageLI) but that adds some complexity.
2215                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
2216                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
2217                        final String lib = libEntry.path;
2218                        if (lib == null) {
2219                            continue;
2220                        }
2221
2222                        try {
2223                            // Shared libraries do not have profiles so we perform a full
2224                            // AOT compilation (if needed).
2225                            int dexoptNeeded = DexFile.getDexOptNeeded(
2226                                    lib, dexCodeInstructionSet,
2227                                    getCompilerFilterForReason(REASON_SHARED_APK),
2228                                    false /* newProfile */);
2229                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
2230                                mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet,
2231                                        dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/,
2232                                        getCompilerFilterForReason(REASON_SHARED_APK),
2233                                        StorageManager.UUID_PRIVATE_INTERNAL);
2234                            }
2235                        } catch (FileNotFoundException e) {
2236                            Slog.w(TAG, "Library not found: " + lib);
2237                        } catch (IOException | InstallerException e) {
2238                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
2239                                    + e.getMessage());
2240                        }
2241                    }
2242                }
2243            }
2244
2245            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2246
2247            final VersionInfo ver = mSettings.getInternalVersion();
2248            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2249
2250            // when upgrading from pre-M, promote system app permissions from install to runtime
2251            mPromoteSystemApps =
2252                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2253
2254            // save off the names of pre-existing system packages prior to scanning; we don't
2255            // want to automatically grant runtime permissions for new system apps
2256            if (mPromoteSystemApps) {
2257                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2258                while (pkgSettingIter.hasNext()) {
2259                    PackageSetting ps = pkgSettingIter.next();
2260                    if (isSystemApp(ps)) {
2261                        mExistingSystemPackages.add(ps.name);
2262                    }
2263                }
2264            }
2265
2266            // When upgrading from pre-N, we need to handle package extraction like first boot,
2267            // as there is no profiling data available.
2268            mIsPreNUpgrade = !mSettings.isNWorkDone();
2269            mSettings.setNWorkDone();
2270
2271            // Collect vendor overlay packages.
2272            // (Do this before scanning any apps.)
2273            // For security and version matching reason, only consider
2274            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
2275            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
2276            scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
2277                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2278
2279            // Find base frameworks (resource packages without code).
2280            scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
2281                    | PackageParser.PARSE_IS_SYSTEM_DIR
2282                    | PackageParser.PARSE_IS_PRIVILEGED,
2283                    scanFlags | SCAN_NO_DEX, 0);
2284
2285            // Collected privileged system packages.
2286            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2287            scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
2288                    | PackageParser.PARSE_IS_SYSTEM_DIR
2289                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2290
2291            // Collect ordinary system packages.
2292            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2293            scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
2294                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2295
2296            // Collect all vendor packages.
2297            File vendorAppDir = new File("/vendor/app");
2298            try {
2299                vendorAppDir = vendorAppDir.getCanonicalFile();
2300            } catch (IOException e) {
2301                // failed to look up canonical path, continue with original one
2302            }
2303            scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
2304                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2305
2306            // Collect all OEM packages.
2307            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2308            scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
2309                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2310
2311            // Prune any system packages that no longer exist.
2312            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2313            if (!mOnlyCore) {
2314                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2315                while (psit.hasNext()) {
2316                    PackageSetting ps = psit.next();
2317
2318                    /*
2319                     * If this is not a system app, it can't be a
2320                     * disable system app.
2321                     */
2322                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2323                        continue;
2324                    }
2325
2326                    /*
2327                     * If the package is scanned, it's not erased.
2328                     */
2329                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2330                    if (scannedPkg != null) {
2331                        /*
2332                         * If the system app is both scanned and in the
2333                         * disabled packages list, then it must have been
2334                         * added via OTA. Remove it from the currently
2335                         * scanned package so the previously user-installed
2336                         * application can be scanned.
2337                         */
2338                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2339                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2340                                    + ps.name + "; removing system app.  Last known codePath="
2341                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2342                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2343                                    + scannedPkg.mVersionCode);
2344                            removePackageLI(scannedPkg, true);
2345                            mExpectingBetter.put(ps.name, ps.codePath);
2346                        }
2347
2348                        continue;
2349                    }
2350
2351                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2352                        psit.remove();
2353                        logCriticalInfo(Log.WARN, "System package " + ps.name
2354                                + " no longer exists; wiping its data");
2355                        removeDataDirsLI(null, ps.name);
2356                    } else {
2357                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2358                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2359                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2360                        }
2361                    }
2362                }
2363            }
2364
2365            //look for any incomplete package installations
2366            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2367            //clean up list
2368            for(int i = 0; i < deletePkgsList.size(); i++) {
2369                //clean up here
2370                cleanupInstallFailedPackage(deletePkgsList.get(i));
2371            }
2372            //delete tmp files
2373            deleteTempPackageFiles();
2374
2375            // Remove any shared userIDs that have no associated packages
2376            mSettings.pruneSharedUsersLPw();
2377
2378            if (!mOnlyCore) {
2379                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2380                        SystemClock.uptimeMillis());
2381                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2382
2383                scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2384                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2385
2386                scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL,
2387                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2388
2389                /**
2390                 * Remove disable package settings for any updated system
2391                 * apps that were removed via an OTA. If they're not a
2392                 * previously-updated app, remove them completely.
2393                 * Otherwise, just revoke their system-level permissions.
2394                 */
2395                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2396                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2397                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2398
2399                    String msg;
2400                    if (deletedPkg == null) {
2401                        msg = "Updated system package " + deletedAppName
2402                                + " no longer exists; wiping its data";
2403                        removeDataDirsLI(null, deletedAppName);
2404                    } else {
2405                        msg = "Updated system app + " + deletedAppName
2406                                + " no longer present; removing system privileges for "
2407                                + deletedAppName;
2408
2409                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2410
2411                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2412                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2413                    }
2414                    logCriticalInfo(Log.WARN, msg);
2415                }
2416
2417                /**
2418                 * Make sure all system apps that we expected to appear on
2419                 * the userdata partition actually showed up. If they never
2420                 * appeared, crawl back and revive the system version.
2421                 */
2422                for (int i = 0; i < mExpectingBetter.size(); i++) {
2423                    final String packageName = mExpectingBetter.keyAt(i);
2424                    if (!mPackages.containsKey(packageName)) {
2425                        final File scanFile = mExpectingBetter.valueAt(i);
2426
2427                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2428                                + " but never showed up; reverting to system");
2429
2430                        final int reparseFlags;
2431                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2432                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2433                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2434                                    | PackageParser.PARSE_IS_PRIVILEGED;
2435                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2436                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2437                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2438                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2439                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2440                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2441                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2442                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2443                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2444                        } else {
2445                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2446                            continue;
2447                        }
2448
2449                        mSettings.enableSystemPackageLPw(packageName);
2450
2451                        try {
2452                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2453                        } catch (PackageManagerException e) {
2454                            Slog.e(TAG, "Failed to parse original system package: "
2455                                    + e.getMessage());
2456                        }
2457                    }
2458                }
2459            }
2460            mExpectingBetter.clear();
2461
2462            // Resolve protected action filters. Only the setup wizard is allowed to
2463            // have a high priority filter for these actions.
2464            mSetupWizardPackage = getSetupWizardPackageName();
2465            if (mProtectedFilters.size() > 0) {
2466                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2467                    Slog.i(TAG, "No setup wizard;"
2468                        + " All protected intents capped to priority 0");
2469                }
2470                for (ActivityIntentInfo filter : mProtectedFilters) {
2471                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2472                        if (DEBUG_FILTERS) {
2473                            Slog.i(TAG, "Found setup wizard;"
2474                                + " allow priority " + filter.getPriority() + ";"
2475                                + " package: " + filter.activity.info.packageName
2476                                + " activity: " + filter.activity.className
2477                                + " priority: " + filter.getPriority());
2478                        }
2479                        // skip setup wizard; allow it to keep the high priority filter
2480                        continue;
2481                    }
2482                    Slog.w(TAG, "Protected action; cap priority to 0;"
2483                            + " package: " + filter.activity.info.packageName
2484                            + " activity: " + filter.activity.className
2485                            + " origPrio: " + filter.getPriority());
2486                    filter.setPriority(0);
2487                }
2488            }
2489            mDeferProtectedFilters = false;
2490            mProtectedFilters.clear();
2491
2492            // Now that we know all of the shared libraries, update all clients to have
2493            // the correct library paths.
2494            updateAllSharedLibrariesLPw();
2495
2496            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2497                // NOTE: We ignore potential failures here during a system scan (like
2498                // the rest of the commands above) because there's precious little we
2499                // can do about it. A settings error is reported, though.
2500                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2501                        false /* boot complete */);
2502            }
2503
2504            // Now that we know all the packages we are keeping,
2505            // read and update their last usage times.
2506            mPackageUsage.readLP();
2507
2508            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2509                    SystemClock.uptimeMillis());
2510            Slog.i(TAG, "Time to scan packages: "
2511                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2512                    + " seconds");
2513
2514            // If the platform SDK has changed since the last time we booted,
2515            // we need to re-grant app permission to catch any new ones that
2516            // appear.  This is really a hack, and means that apps can in some
2517            // cases get permissions that the user didn't initially explicitly
2518            // allow...  it would be nice to have some better way to handle
2519            // this situation.
2520            int updateFlags = UPDATE_PERMISSIONS_ALL;
2521            if (ver.sdkVersion != mSdkVersion) {
2522                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2523                        + mSdkVersion + "; regranting permissions for internal storage");
2524                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2525            }
2526            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2527            ver.sdkVersion = mSdkVersion;
2528
2529            // If this is the first boot or an update from pre-M, and it is a normal
2530            // boot, then we need to initialize the default preferred apps across
2531            // all defined users.
2532            if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) {
2533                for (UserInfo user : sUserManager.getUsers(true)) {
2534                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2535                    applyFactoryDefaultBrowserLPw(user.id);
2536                    primeDomainVerificationsLPw(user.id);
2537                }
2538            }
2539
2540            // Prepare storage for system user really early during boot,
2541            // since core system apps like SettingsProvider and SystemUI
2542            // can't wait for user to start
2543            final int storageFlags;
2544            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2545                storageFlags = StorageManager.FLAG_STORAGE_DE;
2546            } else {
2547                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2548            }
2549            reconcileAppsData(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM,
2550                    storageFlags);
2551
2552            // If this is first boot after an OTA, and a normal boot, then
2553            // we need to clear code cache directories.
2554            if (mIsUpgrade && !onlyCore) {
2555                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2556                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2557                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2558                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2559                        deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2560                    }
2561                }
2562                ver.fingerprint = Build.FINGERPRINT;
2563            }
2564
2565            checkDefaultBrowser();
2566
2567            // clear only after permissions and other defaults have been updated
2568            mExistingSystemPackages.clear();
2569            mPromoteSystemApps = false;
2570
2571            // All the changes are done during package scanning.
2572            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2573
2574            // can downgrade to reader
2575            mSettings.writeLPr();
2576
2577            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2578                    SystemClock.uptimeMillis());
2579
2580            if (!mOnlyCore) {
2581                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2582                mRequiredInstallerPackage = getRequiredInstallerLPr();
2583                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2584                mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2585                        mIntentFilterVerifierComponent);
2586            } else {
2587                mRequiredVerifierPackage = null;
2588                mRequiredInstallerPackage = null;
2589                mIntentFilterVerifierComponent = null;
2590                mIntentFilterVerifier = null;
2591            }
2592
2593            mInstallerService = new PackageInstallerService(context, this);
2594
2595            final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr();
2596            final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr();
2597            // both the installer and resolver must be present to enable ephemeral
2598            if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) {
2599                if (DEBUG_EPHEMERAL) {
2600                    Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent
2601                            + " installer:" + ephemeralInstallerComponent);
2602                }
2603                mEphemeralResolverComponent = ephemeralResolverComponent;
2604                mEphemeralInstallerComponent = ephemeralInstallerComponent;
2605                setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent);
2606                mEphemeralResolverConnection =
2607                        new EphemeralResolverConnection(mContext, mEphemeralResolverComponent);
2608            } else {
2609                if (DEBUG_EPHEMERAL) {
2610                    final String missingComponent =
2611                            (ephemeralResolverComponent == null)
2612                            ? (ephemeralInstallerComponent == null)
2613                                    ? "resolver and installer"
2614                                    : "resolver"
2615                            : "installer";
2616                    Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent);
2617                }
2618                mEphemeralResolverComponent = null;
2619                mEphemeralInstallerComponent = null;
2620                mEphemeralResolverConnection = null;
2621            }
2622
2623            mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this);
2624        } // synchronized (mPackages)
2625        } // synchronized (mInstallLock)
2626
2627        // Now after opening every single application zip, make sure they
2628        // are all flushed.  Not really needed, but keeps things nice and
2629        // tidy.
2630        Runtime.getRuntime().gc();
2631
2632        // The initial scanning above does many calls into installd while
2633        // holding the mPackages lock, but we're mostly interested in yelling
2634        // once we have a booted system.
2635        mInstaller.setWarnIfHeld(mPackages);
2636
2637        // Expose private service for system components to use.
2638        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2639    }
2640
2641    @Override
2642    public boolean isFirstBoot() {
2643        return !mRestoredSettings;
2644    }
2645
2646    @Override
2647    public boolean isOnlyCoreApps() {
2648        return mOnlyCore;
2649    }
2650
2651    @Override
2652    public boolean isUpgrade() {
2653        return mIsUpgrade;
2654    }
2655
2656    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
2657        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2658
2659        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2660                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2661                UserHandle.USER_SYSTEM);
2662        if (matches.size() == 1) {
2663            return matches.get(0).getComponentInfo().packageName;
2664        } else {
2665            Log.e(TAG, "There should probably be exactly one verifier; found " + matches);
2666            return null;
2667        }
2668    }
2669
2670    private @NonNull String getRequiredInstallerLPr() {
2671        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2672        intent.addCategory(Intent.CATEGORY_DEFAULT);
2673        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2674
2675        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2676                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2677                UserHandle.USER_SYSTEM);
2678        if (matches.size() == 1) {
2679            return matches.get(0).getComponentInfo().packageName;
2680        } else {
2681            throw new RuntimeException("There must be exactly one installer; found " + matches);
2682        }
2683    }
2684
2685    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
2686        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2687
2688        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
2689                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2690                UserHandle.USER_SYSTEM);
2691        ResolveInfo best = null;
2692        final int N = matches.size();
2693        for (int i = 0; i < N; i++) {
2694            final ResolveInfo cur = matches.get(i);
2695            final String packageName = cur.getComponentInfo().packageName;
2696            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2697                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2698                continue;
2699            }
2700
2701            if (best == null || cur.priority > best.priority) {
2702                best = cur;
2703            }
2704        }
2705
2706        if (best != null) {
2707            return best.getComponentInfo().getComponentName();
2708        } else {
2709            throw new RuntimeException("There must be at least one intent filter verifier");
2710        }
2711    }
2712
2713    private @Nullable ComponentName getEphemeralResolverLPr() {
2714        final String[] packageArray =
2715                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2716        if (packageArray.length == 0) {
2717            if (DEBUG_EPHEMERAL) {
2718                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2719            }
2720            return null;
2721        }
2722
2723        final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE);
2724        final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
2725                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2726                UserHandle.USER_SYSTEM);
2727
2728        final int N = resolvers.size();
2729        if (N == 0) {
2730            if (DEBUG_EPHEMERAL) {
2731                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2732            }
2733            return null;
2734        }
2735
2736        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2737        for (int i = 0; i < N; i++) {
2738            final ResolveInfo info = resolvers.get(i);
2739
2740            if (info.serviceInfo == null) {
2741                continue;
2742            }
2743
2744            final String packageName = info.serviceInfo.packageName;
2745            if (!possiblePackages.contains(packageName)) {
2746                if (DEBUG_EPHEMERAL) {
2747                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2748                            + " pkg: " + packageName + ", info:" + info);
2749                }
2750                continue;
2751            }
2752
2753            if (DEBUG_EPHEMERAL) {
2754                Slog.v(TAG, "Ephemeral resolver found;"
2755                        + " pkg: " + packageName + ", info:" + info);
2756            }
2757            return new ComponentName(packageName, info.serviceInfo.name);
2758        }
2759        if (DEBUG_EPHEMERAL) {
2760            Slog.v(TAG, "Ephemeral resolver NOT found");
2761        }
2762        return null;
2763    }
2764
2765    private @Nullable ComponentName getEphemeralInstallerLPr() {
2766        final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
2767        intent.addCategory(Intent.CATEGORY_DEFAULT);
2768        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2769
2770        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2771                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2772                UserHandle.USER_SYSTEM);
2773        if (matches.size() == 0) {
2774            return null;
2775        } else if (matches.size() == 1) {
2776            return matches.get(0).getComponentInfo().getComponentName();
2777        } else {
2778            throw new RuntimeException(
2779                    "There must be at most one ephemeral installer; found " + matches);
2780        }
2781    }
2782
2783    private void primeDomainVerificationsLPw(int userId) {
2784        if (DEBUG_DOMAIN_VERIFICATION) {
2785            Slog.d(TAG, "Priming domain verifications in user " + userId);
2786        }
2787
2788        SystemConfig systemConfig = SystemConfig.getInstance();
2789        ArraySet<String> packages = systemConfig.getLinkedApps();
2790        ArraySet<String> domains = new ArraySet<String>();
2791
2792        for (String packageName : packages) {
2793            PackageParser.Package pkg = mPackages.get(packageName);
2794            if (pkg != null) {
2795                if (!pkg.isSystemApp()) {
2796                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
2797                    continue;
2798                }
2799
2800                domains.clear();
2801                for (PackageParser.Activity a : pkg.activities) {
2802                    for (ActivityIntentInfo filter : a.intents) {
2803                        if (hasValidDomains(filter)) {
2804                            domains.addAll(filter.getHostsList());
2805                        }
2806                    }
2807                }
2808
2809                if (domains.size() > 0) {
2810                    if (DEBUG_DOMAIN_VERIFICATION) {
2811                        Slog.v(TAG, "      + " + packageName);
2812                    }
2813                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
2814                    // state w.r.t. the formal app-linkage "no verification attempted" state;
2815                    // and then 'always' in the per-user state actually used for intent resolution.
2816                    final IntentFilterVerificationInfo ivi;
2817                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName,
2818                            new ArrayList<String>(domains));
2819                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
2820                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
2821                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
2822                } else {
2823                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
2824                            + "' does not handle web links");
2825                }
2826            } else {
2827                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
2828            }
2829        }
2830
2831        scheduleWritePackageRestrictionsLocked(userId);
2832        scheduleWriteSettingsLocked();
2833    }
2834
2835    private void applyFactoryDefaultBrowserLPw(int userId) {
2836        // The default browser app's package name is stored in a string resource,
2837        // with a product-specific overlay used for vendor customization.
2838        String browserPkg = mContext.getResources().getString(
2839                com.android.internal.R.string.default_browser);
2840        if (!TextUtils.isEmpty(browserPkg)) {
2841            // non-empty string => required to be a known package
2842            PackageSetting ps = mSettings.mPackages.get(browserPkg);
2843            if (ps == null) {
2844                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
2845                browserPkg = null;
2846            } else {
2847                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2848            }
2849        }
2850
2851        // Nothing valid explicitly set? Make the factory-installed browser the explicit
2852        // default.  If there's more than one, just leave everything alone.
2853        if (browserPkg == null) {
2854            calculateDefaultBrowserLPw(userId);
2855        }
2856    }
2857
2858    private void calculateDefaultBrowserLPw(int userId) {
2859        List<String> allBrowsers = resolveAllBrowserApps(userId);
2860        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
2861        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
2862    }
2863
2864    private List<String> resolveAllBrowserApps(int userId) {
2865        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
2866        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2867                PackageManager.MATCH_ALL, userId);
2868
2869        final int count = list.size();
2870        List<String> result = new ArrayList<String>(count);
2871        for (int i=0; i<count; i++) {
2872            ResolveInfo info = list.get(i);
2873            if (info.activityInfo == null
2874                    || !info.handleAllWebDataURI
2875                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
2876                    || result.contains(info.activityInfo.packageName)) {
2877                continue;
2878            }
2879            result.add(info.activityInfo.packageName);
2880        }
2881
2882        return result;
2883    }
2884
2885    private boolean packageIsBrowser(String packageName, int userId) {
2886        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
2887                PackageManager.MATCH_ALL, userId);
2888        final int N = list.size();
2889        for (int i = 0; i < N; i++) {
2890            ResolveInfo info = list.get(i);
2891            if (packageName.equals(info.activityInfo.packageName)) {
2892                return true;
2893            }
2894        }
2895        return false;
2896    }
2897
2898    private void checkDefaultBrowser() {
2899        final int myUserId = UserHandle.myUserId();
2900        final String packageName = getDefaultBrowserPackageName(myUserId);
2901        if (packageName != null) {
2902            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2903            if (info == null) {
2904                Slog.w(TAG, "Default browser no longer installed: " + packageName);
2905                synchronized (mPackages) {
2906                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
2907                }
2908            }
2909        }
2910    }
2911
2912    @Override
2913    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2914            throws RemoteException {
2915        try {
2916            return super.onTransact(code, data, reply, flags);
2917        } catch (RuntimeException e) {
2918            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2919                Slog.wtf(TAG, "Package Manager Crash", e);
2920            }
2921            throw e;
2922        }
2923    }
2924
2925    void cleanupInstallFailedPackage(PackageSetting ps) {
2926        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2927
2928        removeDataDirsLI(ps.volumeUuid, ps.name);
2929        if (ps.codePath != null) {
2930            removeCodePathLI(ps.codePath);
2931        }
2932        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2933            if (ps.resourcePath.isDirectory()) {
2934                FileUtils.deleteContents(ps.resourcePath);
2935            }
2936            ps.resourcePath.delete();
2937        }
2938        mSettings.removePackageLPw(ps.name);
2939    }
2940
2941    static int[] appendInts(int[] cur, int[] add) {
2942        if (add == null) return cur;
2943        if (cur == null) return add;
2944        final int N = add.length;
2945        for (int i=0; i<N; i++) {
2946            cur = appendInt(cur, add[i]);
2947        }
2948        return cur;
2949    }
2950
2951    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
2952        if (!sUserManager.exists(userId)) return null;
2953        if (ps == null) {
2954            return null;
2955        }
2956        final PackageParser.Package p = ps.pkg;
2957        if (p == null) {
2958            return null;
2959        }
2960
2961        final PermissionsState permissionsState = ps.getPermissionsState();
2962
2963        final int[] gids = permissionsState.computeGids(userId);
2964        final Set<String> permissions = permissionsState.getPermissions(userId);
2965        final PackageUserState state = ps.readUserState(userId);
2966
2967        return PackageParser.generatePackageInfo(p, gids, flags,
2968                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2969    }
2970
2971    @Override
2972    public void checkPackageStartable(String packageName, int userId) {
2973        final boolean userKeyUnlocked = isUserKeyUnlocked(userId);
2974
2975        synchronized (mPackages) {
2976            final PackageSetting ps = mSettings.mPackages.get(packageName);
2977            if (ps == null) {
2978                throw new SecurityException("Package " + packageName + " was not found!");
2979            }
2980
2981            if (!ps.getInstalled(userId)) {
2982                throw new SecurityException(
2983                        "Package " + packageName + " was not installed for user " + userId + "!");
2984            }
2985
2986            if (mSafeMode && !ps.isSystem()) {
2987                throw new SecurityException("Package " + packageName + " not a system app!");
2988            }
2989
2990            if (ps.frozen) {
2991                throw new SecurityException("Package " + packageName + " is currently frozen!");
2992            }
2993
2994            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
2995                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
2996                throw new SecurityException("Package " + packageName + " is not encryption aware!");
2997            }
2998        }
2999    }
3000
3001    @Override
3002    public boolean isPackageAvailable(String packageName, int userId) {
3003        if (!sUserManager.exists(userId)) return false;
3004        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3005                false /* requireFullPermission */, false /* checkShell */, "is package available");
3006        synchronized (mPackages) {
3007            PackageParser.Package p = mPackages.get(packageName);
3008            if (p != null) {
3009                final PackageSetting ps = (PackageSetting) p.mExtras;
3010                if (ps != null) {
3011                    final PackageUserState state = ps.readUserState(userId);
3012                    if (state != null) {
3013                        return PackageParser.isAvailable(state);
3014                    }
3015                }
3016            }
3017        }
3018        return false;
3019    }
3020
3021    @Override
3022    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3023        if (!sUserManager.exists(userId)) return null;
3024        flags = updateFlagsForPackage(flags, userId, packageName);
3025        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3026                false /* requireFullPermission */, false /* checkShell */, "get package info");
3027        // reader
3028        synchronized (mPackages) {
3029            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3030            PackageParser.Package p = null;
3031            if (matchFactoryOnly) {
3032                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3033                if (ps != null) {
3034                    return generatePackageInfo(ps, flags, userId);
3035                }
3036            }
3037            if (p == null) {
3038                p = mPackages.get(packageName);
3039                if (matchFactoryOnly && !isSystemApp(p)) {
3040                    return null;
3041                }
3042            }
3043            if (DEBUG_PACKAGE_INFO)
3044                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3045            if (p != null) {
3046                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3047            }
3048            if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3049                final PackageSetting ps = mSettings.mPackages.get(packageName);
3050                return generatePackageInfo(ps, flags, userId);
3051            }
3052        }
3053        return null;
3054    }
3055
3056    @Override
3057    public String[] currentToCanonicalPackageNames(String[] names) {
3058        String[] out = new String[names.length];
3059        // reader
3060        synchronized (mPackages) {
3061            for (int i=names.length-1; i>=0; i--) {
3062                PackageSetting ps = mSettings.mPackages.get(names[i]);
3063                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
3064            }
3065        }
3066        return out;
3067    }
3068
3069    @Override
3070    public String[] canonicalToCurrentPackageNames(String[] names) {
3071        String[] out = new String[names.length];
3072        // reader
3073        synchronized (mPackages) {
3074            for (int i=names.length-1; i>=0; i--) {
3075                String cur = mSettings.mRenamedPackages.get(names[i]);
3076                out[i] = cur != null ? cur : names[i];
3077            }
3078        }
3079        return out;
3080    }
3081
3082    @Override
3083    public int getPackageUid(String packageName, int flags, int userId) {
3084        if (!sUserManager.exists(userId)) return -1;
3085        flags = updateFlagsForPackage(flags, userId, packageName);
3086        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3087                false /* requireFullPermission */, false /* checkShell */, "get package uid");
3088
3089        // reader
3090        synchronized (mPackages) {
3091            final PackageParser.Package p = mPackages.get(packageName);
3092            if (p != null && p.isMatch(flags)) {
3093                return UserHandle.getUid(userId, p.applicationInfo.uid);
3094            }
3095            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3096                final PackageSetting ps = mSettings.mPackages.get(packageName);
3097                if (ps != null && ps.isMatch(flags)) {
3098                    return UserHandle.getUid(userId, ps.appId);
3099                }
3100            }
3101        }
3102
3103        return -1;
3104    }
3105
3106    @Override
3107    public int[] getPackageGids(String packageName, int flags, int userId) {
3108        if (!sUserManager.exists(userId)) return null;
3109        flags = updateFlagsForPackage(flags, userId, packageName);
3110        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3111                false /* requireFullPermission */, false /* checkShell */,
3112                "getPackageGids");
3113
3114        // reader
3115        synchronized (mPackages) {
3116            final PackageParser.Package p = mPackages.get(packageName);
3117            if (p != null && p.isMatch(flags)) {
3118                PackageSetting ps = (PackageSetting) p.mExtras;
3119                return ps.getPermissionsState().computeGids(userId);
3120            }
3121            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3122                final PackageSetting ps = mSettings.mPackages.get(packageName);
3123                if (ps != null && ps.isMatch(flags)) {
3124                    return ps.getPermissionsState().computeGids(userId);
3125                }
3126            }
3127        }
3128
3129        return null;
3130    }
3131
3132    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3133        if (bp.perm != null) {
3134            return PackageParser.generatePermissionInfo(bp.perm, flags);
3135        }
3136        PermissionInfo pi = new PermissionInfo();
3137        pi.name = bp.name;
3138        pi.packageName = bp.sourcePackage;
3139        pi.nonLocalizedLabel = bp.name;
3140        pi.protectionLevel = bp.protectionLevel;
3141        return pi;
3142    }
3143
3144    @Override
3145    public PermissionInfo getPermissionInfo(String name, int flags) {
3146        // reader
3147        synchronized (mPackages) {
3148            final BasePermission p = mSettings.mPermissions.get(name);
3149            if (p != null) {
3150                return generatePermissionInfo(p, flags);
3151            }
3152            return null;
3153        }
3154    }
3155
3156    @Override
3157    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
3158            int flags) {
3159        // reader
3160        synchronized (mPackages) {
3161            if (group != null && !mPermissionGroups.containsKey(group)) {
3162                // This is thrown as NameNotFoundException
3163                return null;
3164            }
3165
3166            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
3167            for (BasePermission p : mSettings.mPermissions.values()) {
3168                if (group == null) {
3169                    if (p.perm == null || p.perm.info.group == null) {
3170                        out.add(generatePermissionInfo(p, flags));
3171                    }
3172                } else {
3173                    if (p.perm != null && group.equals(p.perm.info.group)) {
3174                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
3175                    }
3176                }
3177            }
3178            return new ParceledListSlice<>(out);
3179        }
3180    }
3181
3182    @Override
3183    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
3184        // reader
3185        synchronized (mPackages) {
3186            return PackageParser.generatePermissionGroupInfo(
3187                    mPermissionGroups.get(name), flags);
3188        }
3189    }
3190
3191    @Override
3192    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
3193        // reader
3194        synchronized (mPackages) {
3195            final int N = mPermissionGroups.size();
3196            ArrayList<PermissionGroupInfo> out
3197                    = new ArrayList<PermissionGroupInfo>(N);
3198            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
3199                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
3200            }
3201            return new ParceledListSlice<>(out);
3202        }
3203    }
3204
3205    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
3206            int userId) {
3207        if (!sUserManager.exists(userId)) return null;
3208        PackageSetting ps = mSettings.mPackages.get(packageName);
3209        if (ps != null) {
3210            if (ps.pkg == null) {
3211                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
3212                if (pInfo != null) {
3213                    return pInfo.applicationInfo;
3214                }
3215                return null;
3216            }
3217            return PackageParser.generateApplicationInfo(ps.pkg, flags,
3218                    ps.readUserState(userId), userId);
3219        }
3220        return null;
3221    }
3222
3223    @Override
3224    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
3225        if (!sUserManager.exists(userId)) return null;
3226        flags = updateFlagsForApplication(flags, userId, packageName);
3227        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3228                false /* requireFullPermission */, false /* checkShell */, "get application info");
3229        // writer
3230        synchronized (mPackages) {
3231            PackageParser.Package p = mPackages.get(packageName);
3232            if (DEBUG_PACKAGE_INFO) Log.v(
3233                    TAG, "getApplicationInfo " + packageName
3234                    + ": " + p);
3235            if (p != null) {
3236                PackageSetting ps = mSettings.mPackages.get(packageName);
3237                if (ps == null) return null;
3238                // Note: isEnabledLP() does not apply here - always return info
3239                return PackageParser.generateApplicationInfo(
3240                        p, flags, ps.readUserState(userId), userId);
3241            }
3242            if ("android".equals(packageName)||"system".equals(packageName)) {
3243                return mAndroidApplication;
3244            }
3245            if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) {
3246                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
3247            }
3248        }
3249        return null;
3250    }
3251
3252    @Override
3253    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
3254            final IPackageDataObserver observer) {
3255        mContext.enforceCallingOrSelfPermission(
3256                android.Manifest.permission.CLEAR_APP_CACHE, null);
3257        // Queue up an async operation since clearing cache may take a little while.
3258        mHandler.post(new Runnable() {
3259            public void run() {
3260                mHandler.removeCallbacks(this);
3261                boolean success = true;
3262                synchronized (mInstallLock) {
3263                    try {
3264                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3265                    } catch (InstallerException e) {
3266                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3267                        success = false;
3268                    }
3269                }
3270                if (observer != null) {
3271                    try {
3272                        observer.onRemoveCompleted(null, success);
3273                    } catch (RemoteException e) {
3274                        Slog.w(TAG, "RemoveException when invoking call back");
3275                    }
3276                }
3277            }
3278        });
3279    }
3280
3281    @Override
3282    public void freeStorage(final String volumeUuid, final long freeStorageSize,
3283            final IntentSender pi) {
3284        mContext.enforceCallingOrSelfPermission(
3285                android.Manifest.permission.CLEAR_APP_CACHE, null);
3286        // Queue up an async operation since clearing cache may take a little while.
3287        mHandler.post(new Runnable() {
3288            public void run() {
3289                mHandler.removeCallbacks(this);
3290                boolean success = true;
3291                synchronized (mInstallLock) {
3292                    try {
3293                        mInstaller.freeCache(volumeUuid, freeStorageSize);
3294                    } catch (InstallerException e) {
3295                        Slog.w(TAG, "Couldn't clear application caches: " + e);
3296                        success = false;
3297                    }
3298                }
3299                if(pi != null) {
3300                    try {
3301                        // Callback via pending intent
3302                        int code = success ? 1 : 0;
3303                        pi.sendIntent(null, code, null,
3304                                null, null);
3305                    } catch (SendIntentException e1) {
3306                        Slog.i(TAG, "Failed to send pending intent");
3307                    }
3308                }
3309            }
3310        });
3311    }
3312
3313    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
3314        synchronized (mInstallLock) {
3315            try {
3316                mInstaller.freeCache(volumeUuid, freeStorageSize);
3317            } catch (InstallerException e) {
3318                throw new IOException("Failed to free enough space", e);
3319            }
3320        }
3321    }
3322
3323    /**
3324     * Return if the user key is currently unlocked.
3325     */
3326    private boolean isUserKeyUnlocked(int userId) {
3327        if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3328            final IMountService mount = IMountService.Stub
3329                    .asInterface(ServiceManager.getService("mount"));
3330            if (mount == null) {
3331                Slog.w(TAG, "Early during boot, assuming locked");
3332                return false;
3333            }
3334            final long token = Binder.clearCallingIdentity();
3335            try {
3336                return mount.isUserKeyUnlocked(userId);
3337            } catch (RemoteException e) {
3338                throw e.rethrowAsRuntimeException();
3339            } finally {
3340                Binder.restoreCallingIdentity(token);
3341            }
3342        } else {
3343            return true;
3344        }
3345    }
3346
3347    /**
3348     * Update given flags based on encryption status of current user.
3349     */
3350    private int updateFlags(int flags, int userId) {
3351        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3352                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
3353            // Caller expressed an explicit opinion about what encryption
3354            // aware/unaware components they want to see, so fall through and
3355            // give them what they want
3356        } else {
3357            // Caller expressed no opinion, so match based on user state
3358            if (isUserKeyUnlocked(userId)) {
3359                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3360            } else {
3361                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
3362            }
3363        }
3364        return flags;
3365    }
3366
3367    /**
3368     * Update given flags when being used to request {@link PackageInfo}.
3369     */
3370    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
3371        boolean triaged = true;
3372        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
3373                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
3374            // Caller is asking for component details, so they'd better be
3375            // asking for specific encryption matching behavior, or be triaged
3376            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3377                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
3378                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3379                triaged = false;
3380            }
3381        }
3382        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
3383                | PackageManager.MATCH_SYSTEM_ONLY
3384                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3385            triaged = false;
3386        }
3387        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3388            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3389                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3390        }
3391        return updateFlags(flags, userId);
3392    }
3393
3394    /**
3395     * Update given flags when being used to request {@link ApplicationInfo}.
3396     */
3397    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
3398        return updateFlagsForPackage(flags, userId, cookie);
3399    }
3400
3401    /**
3402     * Update given flags when being used to request {@link ComponentInfo}.
3403     */
3404    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
3405        if (cookie instanceof Intent) {
3406            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
3407                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
3408            }
3409        }
3410
3411        boolean triaged = true;
3412        // Caller is asking for component details, so they'd better be
3413        // asking for specific encryption matching behavior, or be triaged
3414        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
3415                | PackageManager.MATCH_DIRECT_BOOT_AWARE
3416                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
3417            triaged = false;
3418        }
3419        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
3420            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
3421                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
3422        }
3423
3424        return updateFlags(flags, userId);
3425    }
3426
3427    /**
3428     * Update given flags when being used to request {@link ResolveInfo}.
3429     */
3430    int updateFlagsForResolve(int flags, int userId, Object cookie) {
3431        // Safe mode means we shouldn't match any third-party components
3432        if (mSafeMode) {
3433            flags |= PackageManager.MATCH_SYSTEM_ONLY;
3434        }
3435
3436        return updateFlagsForComponent(flags, userId, cookie);
3437    }
3438
3439    @Override
3440    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
3441        if (!sUserManager.exists(userId)) return null;
3442        flags = updateFlagsForComponent(flags, userId, component);
3443        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3444                false /* requireFullPermission */, false /* checkShell */, "get activity info");
3445        synchronized (mPackages) {
3446            PackageParser.Activity a = mActivities.mActivities.get(component);
3447
3448            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
3449            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3450                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3451                if (ps == null) return null;
3452                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3453                        userId);
3454            }
3455            if (mResolveComponentName.equals(component)) {
3456                return PackageParser.generateActivityInfo(mResolveActivity, flags,
3457                        new PackageUserState(), userId);
3458            }
3459        }
3460        return null;
3461    }
3462
3463    @Override
3464    public boolean activitySupportsIntent(ComponentName component, Intent intent,
3465            String resolvedType) {
3466        synchronized (mPackages) {
3467            if (component.equals(mResolveComponentName)) {
3468                // The resolver supports EVERYTHING!
3469                return true;
3470            }
3471            PackageParser.Activity a = mActivities.mActivities.get(component);
3472            if (a == null) {
3473                return false;
3474            }
3475            for (int i=0; i<a.intents.size(); i++) {
3476                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
3477                        intent.getData(), intent.getCategories(), TAG) >= 0) {
3478                    return true;
3479                }
3480            }
3481            return false;
3482        }
3483    }
3484
3485    @Override
3486    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
3487        if (!sUserManager.exists(userId)) return null;
3488        flags = updateFlagsForComponent(flags, userId, component);
3489        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3490                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
3491        synchronized (mPackages) {
3492            PackageParser.Activity a = mReceivers.mActivities.get(component);
3493            if (DEBUG_PACKAGE_INFO) Log.v(
3494                TAG, "getReceiverInfo " + component + ": " + a);
3495            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
3496                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3497                if (ps == null) return null;
3498                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
3499                        userId);
3500            }
3501        }
3502        return null;
3503    }
3504
3505    @Override
3506    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
3507        if (!sUserManager.exists(userId)) return null;
3508        flags = updateFlagsForComponent(flags, userId, component);
3509        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3510                false /* requireFullPermission */, false /* checkShell */, "get service info");
3511        synchronized (mPackages) {
3512            PackageParser.Service s = mServices.mServices.get(component);
3513            if (DEBUG_PACKAGE_INFO) Log.v(
3514                TAG, "getServiceInfo " + component + ": " + s);
3515            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
3516                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3517                if (ps == null) return null;
3518                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
3519                        userId);
3520            }
3521        }
3522        return null;
3523    }
3524
3525    @Override
3526    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
3527        if (!sUserManager.exists(userId)) return null;
3528        flags = updateFlagsForComponent(flags, userId, component);
3529        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3530                false /* requireFullPermission */, false /* checkShell */, "get provider info");
3531        synchronized (mPackages) {
3532            PackageParser.Provider p = mProviders.mProviders.get(component);
3533            if (DEBUG_PACKAGE_INFO) Log.v(
3534                TAG, "getProviderInfo " + component + ": " + p);
3535            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
3536                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
3537                if (ps == null) return null;
3538                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
3539                        userId);
3540            }
3541        }
3542        return null;
3543    }
3544
3545    @Override
3546    public String[] getSystemSharedLibraryNames() {
3547        Set<String> libSet;
3548        synchronized (mPackages) {
3549            libSet = mSharedLibraries.keySet();
3550            int size = libSet.size();
3551            if (size > 0) {
3552                String[] libs = new String[size];
3553                libSet.toArray(libs);
3554                return libs;
3555            }
3556        }
3557        return null;
3558    }
3559
3560    @Override
3561    public @Nullable String getServicesSystemSharedLibraryPackageName() {
3562        synchronized (mPackages) {
3563            SharedLibraryEntry libraryEntry = mSharedLibraries.get(
3564                    PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES);
3565            if (libraryEntry != null) {
3566                return libraryEntry.apk;
3567            }
3568        }
3569        return null;
3570    }
3571
3572    @Override
3573    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
3574        synchronized (mPackages) {
3575            final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values());
3576
3577            final FeatureInfo fi = new FeatureInfo();
3578            fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
3579                    FeatureInfo.GL_ES_VERSION_UNDEFINED);
3580            res.add(fi);
3581
3582            return new ParceledListSlice<>(res);
3583        }
3584    }
3585
3586    @Override
3587    public boolean hasSystemFeature(String name, int version) {
3588        synchronized (mPackages) {
3589            final FeatureInfo feat = mAvailableFeatures.get(name);
3590            if (feat == null) {
3591                return false;
3592            } else {
3593                return feat.version >= version;
3594            }
3595        }
3596    }
3597
3598    @Override
3599    public int checkPermission(String permName, String pkgName, int userId) {
3600        if (!sUserManager.exists(userId)) {
3601            return PackageManager.PERMISSION_DENIED;
3602        }
3603
3604        synchronized (mPackages) {
3605            final PackageParser.Package p = mPackages.get(pkgName);
3606            if (p != null && p.mExtras != null) {
3607                final PackageSetting ps = (PackageSetting) p.mExtras;
3608                final PermissionsState permissionsState = ps.getPermissionsState();
3609                if (permissionsState.hasPermission(permName, userId)) {
3610                    return PackageManager.PERMISSION_GRANTED;
3611                }
3612                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3613                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3614                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3615                    return PackageManager.PERMISSION_GRANTED;
3616                }
3617            }
3618        }
3619
3620        return PackageManager.PERMISSION_DENIED;
3621    }
3622
3623    @Override
3624    public int checkUidPermission(String permName, int uid) {
3625        final int userId = UserHandle.getUserId(uid);
3626
3627        if (!sUserManager.exists(userId)) {
3628            return PackageManager.PERMISSION_DENIED;
3629        }
3630
3631        synchronized (mPackages) {
3632            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3633            if (obj != null) {
3634                final SettingBase ps = (SettingBase) obj;
3635                final PermissionsState permissionsState = ps.getPermissionsState();
3636                if (permissionsState.hasPermission(permName, userId)) {
3637                    return PackageManager.PERMISSION_GRANTED;
3638                }
3639                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
3640                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
3641                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
3642                    return PackageManager.PERMISSION_GRANTED;
3643                }
3644            } else {
3645                ArraySet<String> perms = mSystemPermissions.get(uid);
3646                if (perms != null) {
3647                    if (perms.contains(permName)) {
3648                        return PackageManager.PERMISSION_GRANTED;
3649                    }
3650                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
3651                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
3652                        return PackageManager.PERMISSION_GRANTED;
3653                    }
3654                }
3655            }
3656        }
3657
3658        return PackageManager.PERMISSION_DENIED;
3659    }
3660
3661    @Override
3662    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
3663        if (UserHandle.getCallingUserId() != userId) {
3664            mContext.enforceCallingPermission(
3665                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
3666                    "isPermissionRevokedByPolicy for user " + userId);
3667        }
3668
3669        if (checkPermission(permission, packageName, userId)
3670                == PackageManager.PERMISSION_GRANTED) {
3671            return false;
3672        }
3673
3674        final long identity = Binder.clearCallingIdentity();
3675        try {
3676            final int flags = getPermissionFlags(permission, packageName, userId);
3677            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
3678        } finally {
3679            Binder.restoreCallingIdentity(identity);
3680        }
3681    }
3682
3683    @Override
3684    public String getPermissionControllerPackageName() {
3685        synchronized (mPackages) {
3686            return mRequiredInstallerPackage;
3687        }
3688    }
3689
3690    /**
3691     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
3692     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
3693     * @param checkShell whether to prevent shell from access if there's a debugging restriction
3694     * @param message the message to log on security exception
3695     */
3696    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
3697            boolean checkShell, String message) {
3698        if (userId < 0) {
3699            throw new IllegalArgumentException("Invalid userId " + userId);
3700        }
3701        if (checkShell) {
3702            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
3703        }
3704        if (userId == UserHandle.getUserId(callingUid)) return;
3705        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
3706            if (requireFullPermission) {
3707                mContext.enforceCallingOrSelfPermission(
3708                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3709            } else {
3710                try {
3711                    mContext.enforceCallingOrSelfPermission(
3712                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
3713                } catch (SecurityException se) {
3714                    mContext.enforceCallingOrSelfPermission(
3715                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
3716                }
3717            }
3718        }
3719    }
3720
3721    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
3722        if (callingUid == Process.SHELL_UID) {
3723            if (userHandle >= 0
3724                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
3725                throw new SecurityException("Shell does not have permission to access user "
3726                        + userHandle);
3727            } else if (userHandle < 0) {
3728                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
3729                        + Debug.getCallers(3));
3730            }
3731        }
3732    }
3733
3734    private BasePermission findPermissionTreeLP(String permName) {
3735        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
3736            if (permName.startsWith(bp.name) &&
3737                    permName.length() > bp.name.length() &&
3738                    permName.charAt(bp.name.length()) == '.') {
3739                return bp;
3740            }
3741        }
3742        return null;
3743    }
3744
3745    private BasePermission checkPermissionTreeLP(String permName) {
3746        if (permName != null) {
3747            BasePermission bp = findPermissionTreeLP(permName);
3748            if (bp != null) {
3749                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
3750                    return bp;
3751                }
3752                throw new SecurityException("Calling uid "
3753                        + Binder.getCallingUid()
3754                        + " is not allowed to add to permission tree "
3755                        + bp.name + " owned by uid " + bp.uid);
3756            }
3757        }
3758        throw new SecurityException("No permission tree found for " + permName);
3759    }
3760
3761    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3762        if (s1 == null) {
3763            return s2 == null;
3764        }
3765        if (s2 == null) {
3766            return false;
3767        }
3768        if (s1.getClass() != s2.getClass()) {
3769            return false;
3770        }
3771        return s1.equals(s2);
3772    }
3773
3774    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3775        if (pi1.icon != pi2.icon) return false;
3776        if (pi1.logo != pi2.logo) return false;
3777        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3778        if (!compareStrings(pi1.name, pi2.name)) return false;
3779        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3780        // We'll take care of setting this one.
3781        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3782        // These are not currently stored in settings.
3783        //if (!compareStrings(pi1.group, pi2.group)) return false;
3784        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3785        //if (pi1.labelRes != pi2.labelRes) return false;
3786        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3787        return true;
3788    }
3789
3790    int permissionInfoFootprint(PermissionInfo info) {
3791        int size = info.name.length();
3792        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3793        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3794        return size;
3795    }
3796
3797    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3798        int size = 0;
3799        for (BasePermission perm : mSettings.mPermissions.values()) {
3800            if (perm.uid == tree.uid) {
3801                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3802            }
3803        }
3804        return size;
3805    }
3806
3807    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3808        // We calculate the max size of permissions defined by this uid and throw
3809        // if that plus the size of 'info' would exceed our stated maximum.
3810        if (tree.uid != Process.SYSTEM_UID) {
3811            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3812            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3813                throw new SecurityException("Permission tree size cap exceeded");
3814            }
3815        }
3816    }
3817
3818    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3819        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3820            throw new SecurityException("Label must be specified in permission");
3821        }
3822        BasePermission tree = checkPermissionTreeLP(info.name);
3823        BasePermission bp = mSettings.mPermissions.get(info.name);
3824        boolean added = bp == null;
3825        boolean changed = true;
3826        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3827        if (added) {
3828            enforcePermissionCapLocked(info, tree);
3829            bp = new BasePermission(info.name, tree.sourcePackage,
3830                    BasePermission.TYPE_DYNAMIC);
3831        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3832            throw new SecurityException(
3833                    "Not allowed to modify non-dynamic permission "
3834                    + info.name);
3835        } else {
3836            if (bp.protectionLevel == fixedLevel
3837                    && bp.perm.owner.equals(tree.perm.owner)
3838                    && bp.uid == tree.uid
3839                    && comparePermissionInfos(bp.perm.info, info)) {
3840                changed = false;
3841            }
3842        }
3843        bp.protectionLevel = fixedLevel;
3844        info = new PermissionInfo(info);
3845        info.protectionLevel = fixedLevel;
3846        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3847        bp.perm.info.packageName = tree.perm.info.packageName;
3848        bp.uid = tree.uid;
3849        if (added) {
3850            mSettings.mPermissions.put(info.name, bp);
3851        }
3852        if (changed) {
3853            if (!async) {
3854                mSettings.writeLPr();
3855            } else {
3856                scheduleWriteSettingsLocked();
3857            }
3858        }
3859        return added;
3860    }
3861
3862    @Override
3863    public boolean addPermission(PermissionInfo info) {
3864        synchronized (mPackages) {
3865            return addPermissionLocked(info, false);
3866        }
3867    }
3868
3869    @Override
3870    public boolean addPermissionAsync(PermissionInfo info) {
3871        synchronized (mPackages) {
3872            return addPermissionLocked(info, true);
3873        }
3874    }
3875
3876    @Override
3877    public void removePermission(String name) {
3878        synchronized (mPackages) {
3879            checkPermissionTreeLP(name);
3880            BasePermission bp = mSettings.mPermissions.get(name);
3881            if (bp != null) {
3882                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3883                    throw new SecurityException(
3884                            "Not allowed to modify non-dynamic permission "
3885                            + name);
3886                }
3887                mSettings.mPermissions.remove(name);
3888                mSettings.writeLPr();
3889            }
3890        }
3891    }
3892
3893    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg,
3894            BasePermission bp) {
3895        int index = pkg.requestedPermissions.indexOf(bp.name);
3896        if (index == -1) {
3897            throw new SecurityException("Package " + pkg.packageName
3898                    + " has not requested permission " + bp.name);
3899        }
3900        if (!bp.isRuntime() && !bp.isDevelopment()) {
3901            throw new SecurityException("Permission " + bp.name
3902                    + " is not a changeable permission type");
3903        }
3904    }
3905
3906    @Override
3907    public void grantRuntimePermission(String packageName, String name, final int userId) {
3908        if (!sUserManager.exists(userId)) {
3909            Log.e(TAG, "No such user:" + userId);
3910            return;
3911        }
3912
3913        mContext.enforceCallingOrSelfPermission(
3914                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
3915                "grantRuntimePermission");
3916
3917        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3918                true /* requireFullPermission */, true /* checkShell */,
3919                "grantRuntimePermission");
3920
3921        final int uid;
3922        final SettingBase sb;
3923
3924        synchronized (mPackages) {
3925            final PackageParser.Package pkg = mPackages.get(packageName);
3926            if (pkg == null) {
3927                throw new IllegalArgumentException("Unknown package: " + packageName);
3928            }
3929
3930            final BasePermission bp = mSettings.mPermissions.get(name);
3931            if (bp == null) {
3932                throw new IllegalArgumentException("Unknown permission: " + name);
3933            }
3934
3935            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
3936
3937            // If a permission review is required for legacy apps we represent
3938            // their permissions as always granted runtime ones since we need
3939            // to keep the review required permission flag per user while an
3940            // install permission's state is shared across all users.
3941            if (Build.PERMISSIONS_REVIEW_REQUIRED
3942                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
3943                    && bp.isRuntime()) {
3944                return;
3945            }
3946
3947            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
3948            sb = (SettingBase) pkg.mExtras;
3949            if (sb == null) {
3950                throw new IllegalArgumentException("Unknown package: " + packageName);
3951            }
3952
3953            final PermissionsState permissionsState = sb.getPermissionsState();
3954
3955            final int flags = permissionsState.getPermissionFlags(name, userId);
3956            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
3957                throw new SecurityException("Cannot grant system fixed permission "
3958                        + name + " for package " + packageName);
3959            }
3960
3961            if (bp.isDevelopment()) {
3962                // Development permissions must be handled specially, since they are not
3963                // normal runtime permissions.  For now they apply to all users.
3964                if (permissionsState.grantInstallPermission(bp) !=
3965                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
3966                    scheduleWriteSettingsLocked();
3967                }
3968                return;
3969            }
3970
3971            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
3972                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
3973                return;
3974            }
3975
3976            final int result = permissionsState.grantRuntimePermission(bp, userId);
3977            switch (result) {
3978                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3979                    return;
3980                }
3981
3982                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3983                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
3984                    mHandler.post(new Runnable() {
3985                        @Override
3986                        public void run() {
3987                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
3988                        }
3989                    });
3990                }
3991                break;
3992            }
3993
3994            mOnPermissionChangeListeners.onPermissionsChanged(uid);
3995
3996            // Not critical if that is lost - app has to request again.
3997            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3998        }
3999
4000        // Only need to do this if user is initialized. Otherwise it's a new user
4001        // and there are no processes running as the user yet and there's no need
4002        // to make an expensive call to remount processes for the changed permissions.
4003        if (READ_EXTERNAL_STORAGE.equals(name)
4004                || WRITE_EXTERNAL_STORAGE.equals(name)) {
4005            final long token = Binder.clearCallingIdentity();
4006            try {
4007                if (sUserManager.isInitialized(userId)) {
4008                    MountServiceInternal mountServiceInternal = LocalServices.getService(
4009                            MountServiceInternal.class);
4010                    mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
4011                }
4012            } finally {
4013                Binder.restoreCallingIdentity(token);
4014            }
4015        }
4016    }
4017
4018    @Override
4019    public void revokeRuntimePermission(String packageName, String name, int userId) {
4020        if (!sUserManager.exists(userId)) {
4021            Log.e(TAG, "No such user:" + userId);
4022            return;
4023        }
4024
4025        mContext.enforceCallingOrSelfPermission(
4026                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4027                "revokeRuntimePermission");
4028
4029        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4030                true /* requireFullPermission */, true /* checkShell */,
4031                "revokeRuntimePermission");
4032
4033        final int appId;
4034
4035        synchronized (mPackages) {
4036            final PackageParser.Package pkg = mPackages.get(packageName);
4037            if (pkg == null) {
4038                throw new IllegalArgumentException("Unknown package: " + packageName);
4039            }
4040
4041            final BasePermission bp = mSettings.mPermissions.get(name);
4042            if (bp == null) {
4043                throw new IllegalArgumentException("Unknown permission: " + name);
4044            }
4045
4046            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
4047
4048            // If a permission review is required for legacy apps we represent
4049            // their permissions as always granted runtime ones since we need
4050            // to keep the review required permission flag per user while an
4051            // install permission's state is shared across all users.
4052            if (Build.PERMISSIONS_REVIEW_REQUIRED
4053                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
4054                    && bp.isRuntime()) {
4055                return;
4056            }
4057
4058            SettingBase sb = (SettingBase) pkg.mExtras;
4059            if (sb == null) {
4060                throw new IllegalArgumentException("Unknown package: " + packageName);
4061            }
4062
4063            final PermissionsState permissionsState = sb.getPermissionsState();
4064
4065            final int flags = permissionsState.getPermissionFlags(name, userId);
4066            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
4067                throw new SecurityException("Cannot revoke system fixed permission "
4068                        + name + " for package " + packageName);
4069            }
4070
4071            if (bp.isDevelopment()) {
4072                // Development permissions must be handled specially, since they are not
4073                // normal runtime permissions.  For now they apply to all users.
4074                if (permissionsState.revokeInstallPermission(bp) !=
4075                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
4076                    scheduleWriteSettingsLocked();
4077                }
4078                return;
4079            }
4080
4081            if (permissionsState.revokeRuntimePermission(bp, userId) ==
4082                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
4083                return;
4084            }
4085
4086            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
4087
4088            // Critical, after this call app should never have the permission.
4089            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
4090
4091            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
4092        }
4093
4094        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
4095    }
4096
4097    @Override
4098    public void resetRuntimePermissions() {
4099        mContext.enforceCallingOrSelfPermission(
4100                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
4101                "revokeRuntimePermission");
4102
4103        int callingUid = Binder.getCallingUid();
4104        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
4105            mContext.enforceCallingOrSelfPermission(
4106                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4107                    "resetRuntimePermissions");
4108        }
4109
4110        synchronized (mPackages) {
4111            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
4112            for (int userId : UserManagerService.getInstance().getUserIds()) {
4113                final int packageCount = mPackages.size();
4114                for (int i = 0; i < packageCount; i++) {
4115                    PackageParser.Package pkg = mPackages.valueAt(i);
4116                    if (!(pkg.mExtras instanceof PackageSetting)) {
4117                        continue;
4118                    }
4119                    PackageSetting ps = (PackageSetting) pkg.mExtras;
4120                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
4121                }
4122            }
4123        }
4124    }
4125
4126    @Override
4127    public int getPermissionFlags(String name, String packageName, int userId) {
4128        if (!sUserManager.exists(userId)) {
4129            return 0;
4130        }
4131
4132        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
4133
4134        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4135                true /* requireFullPermission */, false /* checkShell */,
4136                "getPermissionFlags");
4137
4138        synchronized (mPackages) {
4139            final PackageParser.Package pkg = mPackages.get(packageName);
4140            if (pkg == null) {
4141                throw new IllegalArgumentException("Unknown package: " + packageName);
4142            }
4143
4144            final BasePermission bp = mSettings.mPermissions.get(name);
4145            if (bp == null) {
4146                throw new IllegalArgumentException("Unknown permission: " + name);
4147            }
4148
4149            SettingBase sb = (SettingBase) pkg.mExtras;
4150            if (sb == null) {
4151                throw new IllegalArgumentException("Unknown package: " + packageName);
4152            }
4153
4154            PermissionsState permissionsState = sb.getPermissionsState();
4155            return permissionsState.getPermissionFlags(name, userId);
4156        }
4157    }
4158
4159    @Override
4160    public void updatePermissionFlags(String name, String packageName, int flagMask,
4161            int flagValues, int userId) {
4162        if (!sUserManager.exists(userId)) {
4163            return;
4164        }
4165
4166        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
4167
4168        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4169                true /* requireFullPermission */, true /* checkShell */,
4170                "updatePermissionFlags");
4171
4172        // Only the system can change these flags and nothing else.
4173        if (getCallingUid() != Process.SYSTEM_UID) {
4174            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4175            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4176            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4177            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
4178            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
4179        }
4180
4181        synchronized (mPackages) {
4182            final PackageParser.Package pkg = mPackages.get(packageName);
4183            if (pkg == null) {
4184                throw new IllegalArgumentException("Unknown package: " + packageName);
4185            }
4186
4187            final BasePermission bp = mSettings.mPermissions.get(name);
4188            if (bp == null) {
4189                throw new IllegalArgumentException("Unknown permission: " + name);
4190            }
4191
4192            SettingBase sb = (SettingBase) pkg.mExtras;
4193            if (sb == null) {
4194                throw new IllegalArgumentException("Unknown package: " + packageName);
4195            }
4196
4197            PermissionsState permissionsState = sb.getPermissionsState();
4198
4199            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
4200
4201            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
4202                // Install and runtime permissions are stored in different places,
4203                // so figure out what permission changed and persist the change.
4204                if (permissionsState.getInstallPermissionState(name) != null) {
4205                    scheduleWriteSettingsLocked();
4206                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
4207                        || hadState) {
4208                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4209                }
4210            }
4211        }
4212    }
4213
4214    /**
4215     * Update the permission flags for all packages and runtime permissions of a user in order
4216     * to allow device or profile owner to remove POLICY_FIXED.
4217     */
4218    @Override
4219    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
4220        if (!sUserManager.exists(userId)) {
4221            return;
4222        }
4223
4224        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
4225
4226        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4227                true /* requireFullPermission */, true /* checkShell */,
4228                "updatePermissionFlagsForAllApps");
4229
4230        // Only the system can change system fixed flags.
4231        if (getCallingUid() != Process.SYSTEM_UID) {
4232            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4233            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
4234        }
4235
4236        synchronized (mPackages) {
4237            boolean changed = false;
4238            final int packageCount = mPackages.size();
4239            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
4240                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
4241                SettingBase sb = (SettingBase) pkg.mExtras;
4242                if (sb == null) {
4243                    continue;
4244                }
4245                PermissionsState permissionsState = sb.getPermissionsState();
4246                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
4247                        userId, flagMask, flagValues);
4248            }
4249            if (changed) {
4250                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
4251            }
4252        }
4253    }
4254
4255    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
4256        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
4257                != PackageManager.PERMISSION_GRANTED
4258            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
4259                != PackageManager.PERMISSION_GRANTED) {
4260            throw new SecurityException(message + " requires "
4261                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
4262                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
4263        }
4264    }
4265
4266    @Override
4267    public boolean shouldShowRequestPermissionRationale(String permissionName,
4268            String packageName, int userId) {
4269        if (UserHandle.getCallingUserId() != userId) {
4270            mContext.enforceCallingPermission(
4271                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
4272                    "canShowRequestPermissionRationale for user " + userId);
4273        }
4274
4275        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
4276        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
4277            return false;
4278        }
4279
4280        if (checkPermission(permissionName, packageName, userId)
4281                == PackageManager.PERMISSION_GRANTED) {
4282            return false;
4283        }
4284
4285        final int flags;
4286
4287        final long identity = Binder.clearCallingIdentity();
4288        try {
4289            flags = getPermissionFlags(permissionName,
4290                    packageName, userId);
4291        } finally {
4292            Binder.restoreCallingIdentity(identity);
4293        }
4294
4295        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
4296                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
4297                | PackageManager.FLAG_PERMISSION_USER_FIXED;
4298
4299        if ((flags & fixedFlags) != 0) {
4300            return false;
4301        }
4302
4303        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
4304    }
4305
4306    @Override
4307    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4308        mContext.enforceCallingOrSelfPermission(
4309                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
4310                "addOnPermissionsChangeListener");
4311
4312        synchronized (mPackages) {
4313            mOnPermissionChangeListeners.addListenerLocked(listener);
4314        }
4315    }
4316
4317    @Override
4318    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
4319        synchronized (mPackages) {
4320            mOnPermissionChangeListeners.removeListenerLocked(listener);
4321        }
4322    }
4323
4324    @Override
4325    public boolean isProtectedBroadcast(String actionName) {
4326        synchronized (mPackages) {
4327            if (mProtectedBroadcasts.contains(actionName)) {
4328                return true;
4329            } else if (actionName != null) {
4330                // TODO: remove these terrible hacks
4331                if (actionName.startsWith("android.net.netmon.lingerExpired")
4332                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
4333                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
4334                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
4335                    return true;
4336                }
4337            }
4338        }
4339        return false;
4340    }
4341
4342    @Override
4343    public int checkSignatures(String pkg1, String pkg2) {
4344        synchronized (mPackages) {
4345            final PackageParser.Package p1 = mPackages.get(pkg1);
4346            final PackageParser.Package p2 = mPackages.get(pkg2);
4347            if (p1 == null || p1.mExtras == null
4348                    || p2 == null || p2.mExtras == null) {
4349                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4350            }
4351            return compareSignatures(p1.mSignatures, p2.mSignatures);
4352        }
4353    }
4354
4355    @Override
4356    public int checkUidSignatures(int uid1, int uid2) {
4357        // Map to base uids.
4358        uid1 = UserHandle.getAppId(uid1);
4359        uid2 = UserHandle.getAppId(uid2);
4360        // reader
4361        synchronized (mPackages) {
4362            Signature[] s1;
4363            Signature[] s2;
4364            Object obj = mSettings.getUserIdLPr(uid1);
4365            if (obj != null) {
4366                if (obj instanceof SharedUserSetting) {
4367                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
4368                } else if (obj instanceof PackageSetting) {
4369                    s1 = ((PackageSetting)obj).signatures.mSignatures;
4370                } else {
4371                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4372                }
4373            } else {
4374                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4375            }
4376            obj = mSettings.getUserIdLPr(uid2);
4377            if (obj != null) {
4378                if (obj instanceof SharedUserSetting) {
4379                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
4380                } else if (obj instanceof PackageSetting) {
4381                    s2 = ((PackageSetting)obj).signatures.mSignatures;
4382                } else {
4383                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4384                }
4385            } else {
4386                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
4387            }
4388            return compareSignatures(s1, s2);
4389        }
4390    }
4391
4392    private void killUid(int appId, int userId, String reason) {
4393        final long identity = Binder.clearCallingIdentity();
4394        try {
4395            IActivityManager am = ActivityManagerNative.getDefault();
4396            if (am != null) {
4397                try {
4398                    am.killUid(appId, userId, reason);
4399                } catch (RemoteException e) {
4400                    /* ignore - same process */
4401                }
4402            }
4403        } finally {
4404            Binder.restoreCallingIdentity(identity);
4405        }
4406    }
4407
4408    /**
4409     * Compares two sets of signatures. Returns:
4410     * <br />
4411     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
4412     * <br />
4413     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
4414     * <br />
4415     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
4416     * <br />
4417     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
4418     * <br />
4419     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
4420     */
4421    static int compareSignatures(Signature[] s1, Signature[] s2) {
4422        if (s1 == null) {
4423            return s2 == null
4424                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
4425                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
4426        }
4427
4428        if (s2 == null) {
4429            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
4430        }
4431
4432        if (s1.length != s2.length) {
4433            return PackageManager.SIGNATURE_NO_MATCH;
4434        }
4435
4436        // Since both signature sets are of size 1, we can compare without HashSets.
4437        if (s1.length == 1) {
4438            return s1[0].equals(s2[0]) ?
4439                    PackageManager.SIGNATURE_MATCH :
4440                    PackageManager.SIGNATURE_NO_MATCH;
4441        }
4442
4443        ArraySet<Signature> set1 = new ArraySet<Signature>();
4444        for (Signature sig : s1) {
4445            set1.add(sig);
4446        }
4447        ArraySet<Signature> set2 = new ArraySet<Signature>();
4448        for (Signature sig : s2) {
4449            set2.add(sig);
4450        }
4451        // Make sure s2 contains all signatures in s1.
4452        if (set1.equals(set2)) {
4453            return PackageManager.SIGNATURE_MATCH;
4454        }
4455        return PackageManager.SIGNATURE_NO_MATCH;
4456    }
4457
4458    /**
4459     * If the database version for this type of package (internal storage or
4460     * external storage) is less than the version where package signatures
4461     * were updated, return true.
4462     */
4463    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4464        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4465        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
4466    }
4467
4468    /**
4469     * Used for backward compatibility to make sure any packages with
4470     * certificate chains get upgraded to the new style. {@code existingSigs}
4471     * will be in the old format (since they were stored on disk from before the
4472     * system upgrade) and {@code scannedSigs} will be in the newer format.
4473     */
4474    private int compareSignaturesCompat(PackageSignatures existingSigs,
4475            PackageParser.Package scannedPkg) {
4476        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
4477            return PackageManager.SIGNATURE_NO_MATCH;
4478        }
4479
4480        ArraySet<Signature> existingSet = new ArraySet<Signature>();
4481        for (Signature sig : existingSigs.mSignatures) {
4482            existingSet.add(sig);
4483        }
4484        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
4485        for (Signature sig : scannedPkg.mSignatures) {
4486            try {
4487                Signature[] chainSignatures = sig.getChainSignatures();
4488                for (Signature chainSig : chainSignatures) {
4489                    scannedCompatSet.add(chainSig);
4490                }
4491            } catch (CertificateEncodingException e) {
4492                scannedCompatSet.add(sig);
4493            }
4494        }
4495        /*
4496         * Make sure the expanded scanned set contains all signatures in the
4497         * existing one.
4498         */
4499        if (scannedCompatSet.equals(existingSet)) {
4500            // Migrate the old signatures to the new scheme.
4501            existingSigs.assignSignatures(scannedPkg.mSignatures);
4502            // The new KeySets will be re-added later in the scanning process.
4503            synchronized (mPackages) {
4504                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
4505            }
4506            return PackageManager.SIGNATURE_MATCH;
4507        }
4508        return PackageManager.SIGNATURE_NO_MATCH;
4509    }
4510
4511    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
4512        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
4513        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
4514    }
4515
4516    private int compareSignaturesRecover(PackageSignatures existingSigs,
4517            PackageParser.Package scannedPkg) {
4518        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
4519            return PackageManager.SIGNATURE_NO_MATCH;
4520        }
4521
4522        String msg = null;
4523        try {
4524            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
4525                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
4526                        + scannedPkg.packageName);
4527                return PackageManager.SIGNATURE_MATCH;
4528            }
4529        } catch (CertificateException e) {
4530            msg = e.getMessage();
4531        }
4532
4533        logCriticalInfo(Log.INFO,
4534                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
4535        return PackageManager.SIGNATURE_NO_MATCH;
4536    }
4537
4538    @Override
4539    public List<String> getAllPackages() {
4540        synchronized (mPackages) {
4541            return new ArrayList<String>(mPackages.keySet());
4542        }
4543    }
4544
4545    @Override
4546    public String[] getPackagesForUid(int uid) {
4547        uid = UserHandle.getAppId(uid);
4548        // reader
4549        synchronized (mPackages) {
4550            Object obj = mSettings.getUserIdLPr(uid);
4551            if (obj instanceof SharedUserSetting) {
4552                final SharedUserSetting sus = (SharedUserSetting) obj;
4553                final int N = sus.packages.size();
4554                final String[] res = new String[N];
4555                final Iterator<PackageSetting> it = sus.packages.iterator();
4556                int i = 0;
4557                while (it.hasNext()) {
4558                    res[i++] = it.next().name;
4559                }
4560                return res;
4561            } else if (obj instanceof PackageSetting) {
4562                final PackageSetting ps = (PackageSetting) obj;
4563                return new String[] { ps.name };
4564            }
4565        }
4566        return null;
4567    }
4568
4569    @Override
4570    public String getNameForUid(int uid) {
4571        // reader
4572        synchronized (mPackages) {
4573            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4574            if (obj instanceof SharedUserSetting) {
4575                final SharedUserSetting sus = (SharedUserSetting) obj;
4576                return sus.name + ":" + sus.userId;
4577            } else if (obj instanceof PackageSetting) {
4578                final PackageSetting ps = (PackageSetting) obj;
4579                return ps.name;
4580            }
4581        }
4582        return null;
4583    }
4584
4585    @Override
4586    public int getUidForSharedUser(String sharedUserName) {
4587        if(sharedUserName == null) {
4588            return -1;
4589        }
4590        // reader
4591        synchronized (mPackages) {
4592            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
4593            if (suid == null) {
4594                return -1;
4595            }
4596            return suid.userId;
4597        }
4598    }
4599
4600    @Override
4601    public int getFlagsForUid(int uid) {
4602        synchronized (mPackages) {
4603            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4604            if (obj instanceof SharedUserSetting) {
4605                final SharedUserSetting sus = (SharedUserSetting) obj;
4606                return sus.pkgFlags;
4607            } else if (obj instanceof PackageSetting) {
4608                final PackageSetting ps = (PackageSetting) obj;
4609                return ps.pkgFlags;
4610            }
4611        }
4612        return 0;
4613    }
4614
4615    @Override
4616    public int getPrivateFlagsForUid(int uid) {
4617        synchronized (mPackages) {
4618            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
4619            if (obj instanceof SharedUserSetting) {
4620                final SharedUserSetting sus = (SharedUserSetting) obj;
4621                return sus.pkgPrivateFlags;
4622            } else if (obj instanceof PackageSetting) {
4623                final PackageSetting ps = (PackageSetting) obj;
4624                return ps.pkgPrivateFlags;
4625            }
4626        }
4627        return 0;
4628    }
4629
4630    @Override
4631    public boolean isUidPrivileged(int uid) {
4632        uid = UserHandle.getAppId(uid);
4633        // reader
4634        synchronized (mPackages) {
4635            Object obj = mSettings.getUserIdLPr(uid);
4636            if (obj instanceof SharedUserSetting) {
4637                final SharedUserSetting sus = (SharedUserSetting) obj;
4638                final Iterator<PackageSetting> it = sus.packages.iterator();
4639                while (it.hasNext()) {
4640                    if (it.next().isPrivileged()) {
4641                        return true;
4642                    }
4643                }
4644            } else if (obj instanceof PackageSetting) {
4645                final PackageSetting ps = (PackageSetting) obj;
4646                return ps.isPrivileged();
4647            }
4648        }
4649        return false;
4650    }
4651
4652    @Override
4653    public String[] getAppOpPermissionPackages(String permissionName) {
4654        synchronized (mPackages) {
4655            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
4656            if (pkgs == null) {
4657                return null;
4658            }
4659            return pkgs.toArray(new String[pkgs.size()]);
4660        }
4661    }
4662
4663    @Override
4664    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
4665            int flags, int userId) {
4666        if (!sUserManager.exists(userId)) return null;
4667        flags = updateFlagsForResolve(flags, userId, intent);
4668        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4669                false /* requireFullPermission */, false /* checkShell */, "resolve intent");
4670        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4671                userId);
4672        final ResolveInfo bestChoice =
4673                chooseBestActivity(intent, resolvedType, flags, query, userId);
4674
4675        if (isEphemeralAllowed(intent, query, userId)) {
4676            final EphemeralResolveInfo ai =
4677                    getEphemeralResolveInfo(intent, resolvedType, userId);
4678            if (ai != null) {
4679                if (DEBUG_EPHEMERAL) {
4680                    Slog.v(TAG, "Returning an EphemeralResolveInfo");
4681                }
4682                bestChoice.ephemeralInstaller = mEphemeralInstallerInfo;
4683                bestChoice.ephemeralResolveInfo = ai;
4684            }
4685        }
4686        return bestChoice;
4687    }
4688
4689    @Override
4690    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
4691            IntentFilter filter, int match, ComponentName activity) {
4692        final int userId = UserHandle.getCallingUserId();
4693        if (DEBUG_PREFERRED) {
4694            Log.v(TAG, "setLastChosenActivity intent=" + intent
4695                + " resolvedType=" + resolvedType
4696                + " flags=" + flags
4697                + " filter=" + filter
4698                + " match=" + match
4699                + " activity=" + activity);
4700            filter.dump(new PrintStreamPrinter(System.out), "    ");
4701        }
4702        intent.setComponent(null);
4703        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4704                userId);
4705        // Find any earlier preferred or last chosen entries and nuke them
4706        findPreferredActivity(intent, resolvedType,
4707                flags, query, 0, false, true, false, userId);
4708        // Add the new activity as the last chosen for this filter
4709        addPreferredActivityInternal(filter, match, null, activity, false, userId,
4710                "Setting last chosen");
4711    }
4712
4713    @Override
4714    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
4715        final int userId = UserHandle.getCallingUserId();
4716        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
4717        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
4718                userId);
4719        return findPreferredActivity(intent, resolvedType, flags, query, 0,
4720                false, false, false, userId);
4721    }
4722
4723
4724    private boolean isEphemeralAllowed(
4725            Intent intent, List<ResolveInfo> resolvedActivites, int userId) {
4726        // Short circuit and return early if possible.
4727        if (DISABLE_EPHEMERAL_APPS) {
4728            return false;
4729        }
4730        final int callingUser = UserHandle.getCallingUserId();
4731        if (callingUser != UserHandle.USER_SYSTEM) {
4732            return false;
4733        }
4734        if (mEphemeralResolverConnection == null) {
4735            return false;
4736        }
4737        if (intent.getComponent() != null) {
4738            return false;
4739        }
4740        if (intent.getPackage() != null) {
4741            return false;
4742        }
4743        final boolean isWebUri = hasWebURI(intent);
4744        if (!isWebUri) {
4745            return false;
4746        }
4747        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
4748        synchronized (mPackages) {
4749            final int count = resolvedActivites.size();
4750            for (int n = 0; n < count; n++) {
4751                ResolveInfo info = resolvedActivites.get(n);
4752                String packageName = info.activityInfo.packageName;
4753                PackageSetting ps = mSettings.mPackages.get(packageName);
4754                if (ps != null) {
4755                    // Try to get the status from User settings first
4756                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
4757                    int status = (int) (packedStatus >> 32);
4758                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
4759                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
4760                        if (DEBUG_EPHEMERAL) {
4761                            Slog.v(TAG, "DENY ephemeral apps;"
4762                                + " pkg: " + packageName + ", status: " + status);
4763                        }
4764                        return false;
4765                    }
4766                }
4767            }
4768        }
4769        // We've exhausted all ways to deny ephemeral application; let the system look for them.
4770        return true;
4771    }
4772
4773    private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType,
4774            int userId) {
4775        MessageDigest digest = null;
4776        try {
4777            digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM);
4778        } catch (NoSuchAlgorithmException e) {
4779            // If we can't create a digest, ignore ephemeral apps.
4780            return null;
4781        }
4782
4783        final byte[] hostBytes = intent.getData().getHost().getBytes();
4784        final byte[] digestBytes = digest.digest(hostBytes);
4785        int shaPrefix =
4786                digestBytes[0] << 24
4787                | digestBytes[1] << 16
4788                | digestBytes[2] << 8
4789                | digestBytes[3] << 0;
4790        final List<EphemeralResolveInfo> ephemeralResolveInfoList =
4791                mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix);
4792        if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) {
4793            // No hash prefix match; there are no ephemeral apps for this domain.
4794            return null;
4795        }
4796        for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) {
4797            EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i);
4798            if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) {
4799                continue;
4800            }
4801            final List<IntentFilter> filters = ephemeralApplication.getFilters();
4802            // No filters; this should never happen.
4803            if (filters.isEmpty()) {
4804                continue;
4805            }
4806            // We have a domain match; resolve the filters to see if anything matches.
4807            final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver();
4808            for (int j = filters.size() - 1; j >= 0; --j) {
4809                final EphemeralResolveIntentInfo intentInfo =
4810                        new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication);
4811                ephemeralResolver.addFilter(intentInfo);
4812            }
4813            List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent(
4814                    intent, resolvedType, false /*defaultOnly*/, userId);
4815            if (!matchedResolveInfoList.isEmpty()) {
4816                return matchedResolveInfoList.get(0);
4817            }
4818        }
4819        // Hash or filter mis-match; no ephemeral apps for this domain.
4820        return null;
4821    }
4822
4823    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
4824            int flags, List<ResolveInfo> query, int userId) {
4825        if (query != null) {
4826            final int N = query.size();
4827            if (N == 1) {
4828                return query.get(0);
4829            } else if (N > 1) {
4830                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
4831                // If there is more than one activity with the same priority,
4832                // then let the user decide between them.
4833                ResolveInfo r0 = query.get(0);
4834                ResolveInfo r1 = query.get(1);
4835                if (DEBUG_INTENT_MATCHING || debug) {
4836                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
4837                            + r1.activityInfo.name + "=" + r1.priority);
4838                }
4839                // If the first activity has a higher priority, or a different
4840                // default, then it is always desirable to pick it.
4841                if (r0.priority != r1.priority
4842                        || r0.preferredOrder != r1.preferredOrder
4843                        || r0.isDefault != r1.isDefault) {
4844                    return query.get(0);
4845                }
4846                // If we have saved a preference for a preferred activity for
4847                // this Intent, use that.
4848                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
4849                        flags, query, r0.priority, true, false, debug, userId);
4850                if (ri != null) {
4851                    return ri;
4852                }
4853                ri = new ResolveInfo(mResolveInfo);
4854                ri.activityInfo = new ActivityInfo(ri.activityInfo);
4855                ri.activityInfo.applicationInfo = new ApplicationInfo(
4856                        ri.activityInfo.applicationInfo);
4857                if (userId != 0) {
4858                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
4859                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
4860                }
4861                // Make sure that the resolver is displayable in car mode
4862                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
4863                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
4864                return ri;
4865            }
4866        }
4867        return null;
4868    }
4869
4870    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
4871            int flags, List<ResolveInfo> query, boolean debug, int userId) {
4872        final int N = query.size();
4873        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
4874                .get(userId);
4875        // Get the list of persistent preferred activities that handle the intent
4876        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
4877        List<PersistentPreferredActivity> pprefs = ppir != null
4878                ? ppir.queryIntent(intent, resolvedType,
4879                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4880                : null;
4881        if (pprefs != null && pprefs.size() > 0) {
4882            final int M = pprefs.size();
4883            for (int i=0; i<M; i++) {
4884                final PersistentPreferredActivity ppa = pprefs.get(i);
4885                if (DEBUG_PREFERRED || debug) {
4886                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
4887                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
4888                            + "\n  component=" + ppa.mComponent);
4889                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4890                }
4891                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
4892                        flags | MATCH_DISABLED_COMPONENTS, userId);
4893                if (DEBUG_PREFERRED || debug) {
4894                    Slog.v(TAG, "Found persistent preferred activity:");
4895                    if (ai != null) {
4896                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4897                    } else {
4898                        Slog.v(TAG, "  null");
4899                    }
4900                }
4901                if (ai == null) {
4902                    // This previously registered persistent preferred activity
4903                    // component is no longer known. Ignore it and do NOT remove it.
4904                    continue;
4905                }
4906                for (int j=0; j<N; j++) {
4907                    final ResolveInfo ri = query.get(j);
4908                    if (!ri.activityInfo.applicationInfo.packageName
4909                            .equals(ai.applicationInfo.packageName)) {
4910                        continue;
4911                    }
4912                    if (!ri.activityInfo.name.equals(ai.name)) {
4913                        continue;
4914                    }
4915                    //  Found a persistent preference that can handle the intent.
4916                    if (DEBUG_PREFERRED || debug) {
4917                        Slog.v(TAG, "Returning persistent preferred activity: " +
4918                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
4919                    }
4920                    return ri;
4921                }
4922            }
4923        }
4924        return null;
4925    }
4926
4927    // TODO: handle preferred activities missing while user has amnesia
4928    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
4929            List<ResolveInfo> query, int priority, boolean always,
4930            boolean removeMatches, boolean debug, int userId) {
4931        if (!sUserManager.exists(userId)) return null;
4932        flags = updateFlagsForResolve(flags, userId, intent);
4933        // writer
4934        synchronized (mPackages) {
4935            if (intent.getSelector() != null) {
4936                intent = intent.getSelector();
4937            }
4938            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4939
4940            // Try to find a matching persistent preferred activity.
4941            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
4942                    debug, userId);
4943
4944            // If a persistent preferred activity matched, use it.
4945            if (pri != null) {
4946                return pri;
4947            }
4948
4949            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
4950            // Get the list of preferred activities that handle the intent
4951            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
4952            List<PreferredActivity> prefs = pir != null
4953                    ? pir.queryIntent(intent, resolvedType,
4954                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
4955                    : null;
4956            if (prefs != null && prefs.size() > 0) {
4957                boolean changed = false;
4958                try {
4959                    // First figure out how good the original match set is.
4960                    // We will only allow preferred activities that came
4961                    // from the same match quality.
4962                    int match = 0;
4963
4964                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
4965
4966                    final int N = query.size();
4967                    for (int j=0; j<N; j++) {
4968                        final ResolveInfo ri = query.get(j);
4969                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
4970                                + ": 0x" + Integer.toHexString(match));
4971                        if (ri.match > match) {
4972                            match = ri.match;
4973                        }
4974                    }
4975
4976                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
4977                            + Integer.toHexString(match));
4978
4979                    match &= IntentFilter.MATCH_CATEGORY_MASK;
4980                    final int M = prefs.size();
4981                    for (int i=0; i<M; i++) {
4982                        final PreferredActivity pa = prefs.get(i);
4983                        if (DEBUG_PREFERRED || debug) {
4984                            Slog.v(TAG, "Checking PreferredActivity ds="
4985                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
4986                                    + "\n  component=" + pa.mPref.mComponent);
4987                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
4988                        }
4989                        if (pa.mPref.mMatch != match) {
4990                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
4991                                    + Integer.toHexString(pa.mPref.mMatch));
4992                            continue;
4993                        }
4994                        // If it's not an "always" type preferred activity and that's what we're
4995                        // looking for, skip it.
4996                        if (always && !pa.mPref.mAlways) {
4997                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
4998                            continue;
4999                        }
5000                        final ActivityInfo ai = getActivityInfo(
5001                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
5002                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
5003                                userId);
5004                        if (DEBUG_PREFERRED || debug) {
5005                            Slog.v(TAG, "Found preferred activity:");
5006                            if (ai != null) {
5007                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
5008                            } else {
5009                                Slog.v(TAG, "  null");
5010                            }
5011                        }
5012                        if (ai == null) {
5013                            // This previously registered preferred activity
5014                            // component is no longer known.  Most likely an update
5015                            // to the app was installed and in the new version this
5016                            // component no longer exists.  Clean it up by removing
5017                            // it from the preferred activities list, and skip it.
5018                            Slog.w(TAG, "Removing dangling preferred activity: "
5019                                    + pa.mPref.mComponent);
5020                            pir.removeFilter(pa);
5021                            changed = true;
5022                            continue;
5023                        }
5024                        for (int j=0; j<N; j++) {
5025                            final ResolveInfo ri = query.get(j);
5026                            if (!ri.activityInfo.applicationInfo.packageName
5027                                    .equals(ai.applicationInfo.packageName)) {
5028                                continue;
5029                            }
5030                            if (!ri.activityInfo.name.equals(ai.name)) {
5031                                continue;
5032                            }
5033
5034                            if (removeMatches) {
5035                                pir.removeFilter(pa);
5036                                changed = true;
5037                                if (DEBUG_PREFERRED) {
5038                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
5039                                }
5040                                break;
5041                            }
5042
5043                            // Okay we found a previously set preferred or last chosen app.
5044                            // If the result set is different from when this
5045                            // was created, we need to clear it and re-ask the
5046                            // user their preference, if we're looking for an "always" type entry.
5047                            if (always && !pa.mPref.sameSet(query)) {
5048                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
5049                                        + intent + " type " + resolvedType);
5050                                if (DEBUG_PREFERRED) {
5051                                    Slog.v(TAG, "Removing preferred activity since set changed "
5052                                            + pa.mPref.mComponent);
5053                                }
5054                                pir.removeFilter(pa);
5055                                // Re-add the filter as a "last chosen" entry (!always)
5056                                PreferredActivity lastChosen = new PreferredActivity(
5057                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
5058                                pir.addFilter(lastChosen);
5059                                changed = true;
5060                                return null;
5061                            }
5062
5063                            // Yay! Either the set matched or we're looking for the last chosen
5064                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
5065                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
5066                            return ri;
5067                        }
5068                    }
5069                } finally {
5070                    if (changed) {
5071                        if (DEBUG_PREFERRED) {
5072                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
5073                        }
5074                        scheduleWritePackageRestrictionsLocked(userId);
5075                    }
5076                }
5077            }
5078        }
5079        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
5080        return null;
5081    }
5082
5083    /*
5084     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
5085     */
5086    @Override
5087    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
5088            int targetUserId) {
5089        mContext.enforceCallingOrSelfPermission(
5090                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
5091        List<CrossProfileIntentFilter> matches =
5092                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
5093        if (matches != null) {
5094            int size = matches.size();
5095            for (int i = 0; i < size; i++) {
5096                if (matches.get(i).getTargetUserId() == targetUserId) return true;
5097            }
5098        }
5099        if (hasWebURI(intent)) {
5100            // cross-profile app linking works only towards the parent.
5101            final UserInfo parent = getProfileParent(sourceUserId);
5102            synchronized(mPackages) {
5103                int flags = updateFlagsForResolve(0, parent.id, intent);
5104                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
5105                        intent, resolvedType, flags, sourceUserId, parent.id);
5106                return xpDomainInfo != null;
5107            }
5108        }
5109        return false;
5110    }
5111
5112    private UserInfo getProfileParent(int userId) {
5113        final long identity = Binder.clearCallingIdentity();
5114        try {
5115            return sUserManager.getProfileParent(userId);
5116        } finally {
5117            Binder.restoreCallingIdentity(identity);
5118        }
5119    }
5120
5121    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
5122            String resolvedType, int userId) {
5123        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
5124        if (resolver != null) {
5125            return resolver.queryIntent(intent, resolvedType, false, userId);
5126        }
5127        return null;
5128    }
5129
5130    @Override
5131    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
5132            String resolvedType, int flags, int userId) {
5133        return new ParceledListSlice<>(
5134                queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
5135    }
5136
5137    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
5138            String resolvedType, int flags, int userId) {
5139        if (!sUserManager.exists(userId)) return Collections.emptyList();
5140        flags = updateFlagsForResolve(flags, userId, intent);
5141        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5142                false /* requireFullPermission */, false /* checkShell */,
5143                "query intent activities");
5144        ComponentName comp = intent.getComponent();
5145        if (comp == null) {
5146            if (intent.getSelector() != null) {
5147                intent = intent.getSelector();
5148                comp = intent.getComponent();
5149            }
5150        }
5151
5152        if (comp != null) {
5153            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5154            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
5155            if (ai != null) {
5156                final ResolveInfo ri = new ResolveInfo();
5157                ri.activityInfo = ai;
5158                list.add(ri);
5159            }
5160            return list;
5161        }
5162
5163        // reader
5164        synchronized (mPackages) {
5165            final String pkgName = intent.getPackage();
5166            if (pkgName == null) {
5167                List<CrossProfileIntentFilter> matchingFilters =
5168                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
5169                // Check for results that need to skip the current profile.
5170                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
5171                        resolvedType, flags, userId);
5172                if (xpResolveInfo != null) {
5173                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
5174                    result.add(xpResolveInfo);
5175                    return filterIfNotSystemUser(result, userId);
5176                }
5177
5178                // Check for results in the current profile.
5179                List<ResolveInfo> result = mActivities.queryIntent(
5180                        intent, resolvedType, flags, userId);
5181                result = filterIfNotSystemUser(result, userId);
5182
5183                // Check for cross profile results.
5184                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
5185                xpResolveInfo = queryCrossProfileIntents(
5186                        matchingFilters, intent, resolvedType, flags, userId,
5187                        hasNonNegativePriorityResult);
5188                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
5189                    boolean isVisibleToUser = filterIfNotSystemUser(
5190                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
5191                    if (isVisibleToUser) {
5192                        result.add(xpResolveInfo);
5193                        Collections.sort(result, mResolvePrioritySorter);
5194                    }
5195                }
5196                if (hasWebURI(intent)) {
5197                    CrossProfileDomainInfo xpDomainInfo = null;
5198                    final UserInfo parent = getProfileParent(userId);
5199                    if (parent != null) {
5200                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
5201                                flags, userId, parent.id);
5202                    }
5203                    if (xpDomainInfo != null) {
5204                        if (xpResolveInfo != null) {
5205                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
5206                            // in the result.
5207                            result.remove(xpResolveInfo);
5208                        }
5209                        if (result.size() == 0) {
5210                            result.add(xpDomainInfo.resolveInfo);
5211                            return result;
5212                        }
5213                    } else if (result.size() <= 1) {
5214                        return result;
5215                    }
5216                    result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result,
5217                            xpDomainInfo, userId);
5218                    Collections.sort(result, mResolvePrioritySorter);
5219                }
5220                return result;
5221            }
5222            final PackageParser.Package pkg = mPackages.get(pkgName);
5223            if (pkg != null) {
5224                return filterIfNotSystemUser(
5225                        mActivities.queryIntentForPackage(
5226                                intent, resolvedType, flags, pkg.activities, userId),
5227                        userId);
5228            }
5229            return new ArrayList<ResolveInfo>();
5230        }
5231    }
5232
5233    private static class CrossProfileDomainInfo {
5234        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
5235        ResolveInfo resolveInfo;
5236        /* Best domain verification status of the activities found in the other profile */
5237        int bestDomainVerificationStatus;
5238    }
5239
5240    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
5241            String resolvedType, int flags, int sourceUserId, int parentUserId) {
5242        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
5243                sourceUserId)) {
5244            return null;
5245        }
5246        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5247                resolvedType, flags, parentUserId);
5248
5249        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
5250            return null;
5251        }
5252        CrossProfileDomainInfo result = null;
5253        int size = resultTargetUser.size();
5254        for (int i = 0; i < size; i++) {
5255            ResolveInfo riTargetUser = resultTargetUser.get(i);
5256            // Intent filter verification is only for filters that specify a host. So don't return
5257            // those that handle all web uris.
5258            if (riTargetUser.handleAllWebDataURI) {
5259                continue;
5260            }
5261            String packageName = riTargetUser.activityInfo.packageName;
5262            PackageSetting ps = mSettings.mPackages.get(packageName);
5263            if (ps == null) {
5264                continue;
5265            }
5266            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
5267            int status = (int)(verificationState >> 32);
5268            if (result == null) {
5269                result = new CrossProfileDomainInfo();
5270                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
5271                        sourceUserId, parentUserId);
5272                result.bestDomainVerificationStatus = status;
5273            } else {
5274                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
5275                        result.bestDomainVerificationStatus);
5276            }
5277        }
5278        // Don't consider matches with status NEVER across profiles.
5279        if (result != null && result.bestDomainVerificationStatus
5280                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5281            return null;
5282        }
5283        return result;
5284    }
5285
5286    /**
5287     * Verification statuses are ordered from the worse to the best, except for
5288     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
5289     */
5290    private int bestDomainVerificationStatus(int status1, int status2) {
5291        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5292            return status2;
5293        }
5294        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5295            return status1;
5296        }
5297        return (int) MathUtils.max(status1, status2);
5298    }
5299
5300    private boolean isUserEnabled(int userId) {
5301        long callingId = Binder.clearCallingIdentity();
5302        try {
5303            UserInfo userInfo = sUserManager.getUserInfo(userId);
5304            return userInfo != null && userInfo.isEnabled();
5305        } finally {
5306            Binder.restoreCallingIdentity(callingId);
5307        }
5308    }
5309
5310    /**
5311     * Filter out activities with systemUserOnly flag set, when current user is not System.
5312     *
5313     * @return filtered list
5314     */
5315    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
5316        if (userId == UserHandle.USER_SYSTEM) {
5317            return resolveInfos;
5318        }
5319        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
5320            ResolveInfo info = resolveInfos.get(i);
5321            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
5322                resolveInfos.remove(i);
5323            }
5324        }
5325        return resolveInfos;
5326    }
5327
5328    /**
5329     * @param resolveInfos list of resolve infos in descending priority order
5330     * @return if the list contains a resolve info with non-negative priority
5331     */
5332    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
5333        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
5334    }
5335
5336    private static boolean hasWebURI(Intent intent) {
5337        if (intent.getData() == null) {
5338            return false;
5339        }
5340        final String scheme = intent.getScheme();
5341        if (TextUtils.isEmpty(scheme)) {
5342            return false;
5343        }
5344        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
5345    }
5346
5347    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
5348            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
5349            int userId) {
5350        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
5351
5352        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5353            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
5354                    candidates.size());
5355        }
5356
5357        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
5358        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
5359        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
5360        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
5361        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
5362        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
5363
5364        synchronized (mPackages) {
5365            final int count = candidates.size();
5366            // First, try to use linked apps. Partition the candidates into four lists:
5367            // one for the final results, one for the "do not use ever", one for "undefined status"
5368            // and finally one for "browser app type".
5369            for (int n=0; n<count; n++) {
5370                ResolveInfo info = candidates.get(n);
5371                String packageName = info.activityInfo.packageName;
5372                PackageSetting ps = mSettings.mPackages.get(packageName);
5373                if (ps != null) {
5374                    // Add to the special match all list (Browser use case)
5375                    if (info.handleAllWebDataURI) {
5376                        matchAllList.add(info);
5377                        continue;
5378                    }
5379                    // Try to get the status from User settings first
5380                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
5381                    int status = (int)(packedStatus >> 32);
5382                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
5383                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
5384                        if (DEBUG_DOMAIN_VERIFICATION) {
5385                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
5386                                    + " : linkgen=" + linkGeneration);
5387                        }
5388                        // Use link-enabled generation as preferredOrder, i.e.
5389                        // prefer newly-enabled over earlier-enabled.
5390                        info.preferredOrder = linkGeneration;
5391                        alwaysList.add(info);
5392                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
5393                        if (DEBUG_DOMAIN_VERIFICATION) {
5394                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
5395                        }
5396                        neverList.add(info);
5397                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
5398                        if (DEBUG_DOMAIN_VERIFICATION) {
5399                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
5400                        }
5401                        alwaysAskList.add(info);
5402                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
5403                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
5404                        if (DEBUG_DOMAIN_VERIFICATION) {
5405                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
5406                        }
5407                        undefinedList.add(info);
5408                    }
5409                }
5410            }
5411
5412            // We'll want to include browser possibilities in a few cases
5413            boolean includeBrowser = false;
5414
5415            // First try to add the "always" resolution(s) for the current user, if any
5416            if (alwaysList.size() > 0) {
5417                result.addAll(alwaysList);
5418            } else {
5419                // Add all undefined apps as we want them to appear in the disambiguation dialog.
5420                result.addAll(undefinedList);
5421                // Maybe add one for the other profile.
5422                if (xpDomainInfo != null && (
5423                        xpDomainInfo.bestDomainVerificationStatus
5424                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
5425                    result.add(xpDomainInfo.resolveInfo);
5426                }
5427                includeBrowser = true;
5428            }
5429
5430            // The presence of any 'always ask' alternatives means we'll also offer browsers.
5431            // If there were 'always' entries their preferred order has been set, so we also
5432            // back that off to make the alternatives equivalent
5433            if (alwaysAskList.size() > 0) {
5434                for (ResolveInfo i : result) {
5435                    i.preferredOrder = 0;
5436                }
5437                result.addAll(alwaysAskList);
5438                includeBrowser = true;
5439            }
5440
5441            if (includeBrowser) {
5442                // Also add browsers (all of them or only the default one)
5443                if (DEBUG_DOMAIN_VERIFICATION) {
5444                    Slog.v(TAG, "   ...including browsers in candidate set");
5445                }
5446                if ((matchFlags & MATCH_ALL) != 0) {
5447                    result.addAll(matchAllList);
5448                } else {
5449                    // Browser/generic handling case.  If there's a default browser, go straight
5450                    // to that (but only if there is no other higher-priority match).
5451                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
5452                    int maxMatchPrio = 0;
5453                    ResolveInfo defaultBrowserMatch = null;
5454                    final int numCandidates = matchAllList.size();
5455                    for (int n = 0; n < numCandidates; n++) {
5456                        ResolveInfo info = matchAllList.get(n);
5457                        // track the highest overall match priority...
5458                        if (info.priority > maxMatchPrio) {
5459                            maxMatchPrio = info.priority;
5460                        }
5461                        // ...and the highest-priority default browser match
5462                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
5463                            if (defaultBrowserMatch == null
5464                                    || (defaultBrowserMatch.priority < info.priority)) {
5465                                if (debug) {
5466                                    Slog.v(TAG, "Considering default browser match " + info);
5467                                }
5468                                defaultBrowserMatch = info;
5469                            }
5470                        }
5471                    }
5472                    if (defaultBrowserMatch != null
5473                            && defaultBrowserMatch.priority >= maxMatchPrio
5474                            && !TextUtils.isEmpty(defaultBrowserPackageName))
5475                    {
5476                        if (debug) {
5477                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
5478                        }
5479                        result.add(defaultBrowserMatch);
5480                    } else {
5481                        result.addAll(matchAllList);
5482                    }
5483                }
5484
5485                // If there is nothing selected, add all candidates and remove the ones that the user
5486                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
5487                if (result.size() == 0) {
5488                    result.addAll(candidates);
5489                    result.removeAll(neverList);
5490                }
5491            }
5492        }
5493        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
5494            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
5495                    result.size());
5496            for (ResolveInfo info : result) {
5497                Slog.v(TAG, "  + " + info.activityInfo);
5498            }
5499        }
5500        return result;
5501    }
5502
5503    // Returns a packed value as a long:
5504    //
5505    // high 'int'-sized word: link status: undefined/ask/never/always.
5506    // low 'int'-sized word: relative priority among 'always' results.
5507    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
5508        long result = ps.getDomainVerificationStatusForUser(userId);
5509        // if none available, get the master status
5510        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
5511            if (ps.getIntentFilterVerificationInfo() != null) {
5512                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
5513            }
5514        }
5515        return result;
5516    }
5517
5518    private ResolveInfo querySkipCurrentProfileIntents(
5519            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5520            int flags, int sourceUserId) {
5521        if (matchingFilters != null) {
5522            int size = matchingFilters.size();
5523            for (int i = 0; i < size; i ++) {
5524                CrossProfileIntentFilter filter = matchingFilters.get(i);
5525                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
5526                    // Checking if there are activities in the target user that can handle the
5527                    // intent.
5528                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5529                            resolvedType, flags, sourceUserId);
5530                    if (resolveInfo != null) {
5531                        return resolveInfo;
5532                    }
5533                }
5534            }
5535        }
5536        return null;
5537    }
5538
5539    // Return matching ResolveInfo in target user if any.
5540    private ResolveInfo queryCrossProfileIntents(
5541            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
5542            int flags, int sourceUserId, boolean matchInCurrentProfile) {
5543        if (matchingFilters != null) {
5544            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
5545            // match the same intent. For performance reasons, it is better not to
5546            // run queryIntent twice for the same userId
5547            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
5548            int size = matchingFilters.size();
5549            for (int i = 0; i < size; i++) {
5550                CrossProfileIntentFilter filter = matchingFilters.get(i);
5551                int targetUserId = filter.getTargetUserId();
5552                boolean skipCurrentProfile =
5553                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
5554                boolean skipCurrentProfileIfNoMatchFound =
5555                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
5556                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
5557                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
5558                    // Checking if there are activities in the target user that can handle the
5559                    // intent.
5560                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
5561                            resolvedType, flags, sourceUserId);
5562                    if (resolveInfo != null) return resolveInfo;
5563                    alreadyTriedUserIds.put(targetUserId, true);
5564                }
5565            }
5566        }
5567        return null;
5568    }
5569
5570    /**
5571     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
5572     * will forward the intent to the filter's target user.
5573     * Otherwise, returns null.
5574     */
5575    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
5576            String resolvedType, int flags, int sourceUserId) {
5577        int targetUserId = filter.getTargetUserId();
5578        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
5579                resolvedType, flags, targetUserId);
5580        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
5581            // If all the matches in the target profile are suspended, return null.
5582            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
5583                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
5584                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
5585                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
5586                            targetUserId);
5587                }
5588            }
5589        }
5590        return null;
5591    }
5592
5593    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
5594            int sourceUserId, int targetUserId) {
5595        ResolveInfo forwardingResolveInfo = new ResolveInfo();
5596        long ident = Binder.clearCallingIdentity();
5597        boolean targetIsProfile;
5598        try {
5599            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
5600        } finally {
5601            Binder.restoreCallingIdentity(ident);
5602        }
5603        String className;
5604        if (targetIsProfile) {
5605            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
5606        } else {
5607            className = FORWARD_INTENT_TO_PARENT;
5608        }
5609        ComponentName forwardingActivityComponentName = new ComponentName(
5610                mAndroidApplication.packageName, className);
5611        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
5612                sourceUserId);
5613        if (!targetIsProfile) {
5614            forwardingActivityInfo.showUserIcon = targetUserId;
5615            forwardingResolveInfo.noResourceId = true;
5616        }
5617        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
5618        forwardingResolveInfo.priority = 0;
5619        forwardingResolveInfo.preferredOrder = 0;
5620        forwardingResolveInfo.match = 0;
5621        forwardingResolveInfo.isDefault = true;
5622        forwardingResolveInfo.filter = filter;
5623        forwardingResolveInfo.targetUserId = targetUserId;
5624        return forwardingResolveInfo;
5625    }
5626
5627    @Override
5628    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
5629            Intent[] specifics, String[] specificTypes, Intent intent,
5630            String resolvedType, int flags, int userId) {
5631        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
5632                specificTypes, intent, resolvedType, flags, userId));
5633    }
5634
5635    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
5636            Intent[] specifics, String[] specificTypes, Intent intent,
5637            String resolvedType, int flags, int userId) {
5638        if (!sUserManager.exists(userId)) return Collections.emptyList();
5639        flags = updateFlagsForResolve(flags, userId, intent);
5640        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5641                false /* requireFullPermission */, false /* checkShell */,
5642                "query intent activity options");
5643        final String resultsAction = intent.getAction();
5644
5645        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
5646                | PackageManager.GET_RESOLVED_FILTER, userId);
5647
5648        if (DEBUG_INTENT_MATCHING) {
5649            Log.v(TAG, "Query " + intent + ": " + results);
5650        }
5651
5652        int specificsPos = 0;
5653        int N;
5654
5655        // todo: note that the algorithm used here is O(N^2).  This
5656        // isn't a problem in our current environment, but if we start running
5657        // into situations where we have more than 5 or 10 matches then this
5658        // should probably be changed to something smarter...
5659
5660        // First we go through and resolve each of the specific items
5661        // that were supplied, taking care of removing any corresponding
5662        // duplicate items in the generic resolve list.
5663        if (specifics != null) {
5664            for (int i=0; i<specifics.length; i++) {
5665                final Intent sintent = specifics[i];
5666                if (sintent == null) {
5667                    continue;
5668                }
5669
5670                if (DEBUG_INTENT_MATCHING) {
5671                    Log.v(TAG, "Specific #" + i + ": " + sintent);
5672                }
5673
5674                String action = sintent.getAction();
5675                if (resultsAction != null && resultsAction.equals(action)) {
5676                    // If this action was explicitly requested, then don't
5677                    // remove things that have it.
5678                    action = null;
5679                }
5680
5681                ResolveInfo ri = null;
5682                ActivityInfo ai = null;
5683
5684                ComponentName comp = sintent.getComponent();
5685                if (comp == null) {
5686                    ri = resolveIntent(
5687                        sintent,
5688                        specificTypes != null ? specificTypes[i] : null,
5689                            flags, userId);
5690                    if (ri == null) {
5691                        continue;
5692                    }
5693                    if (ri == mResolveInfo) {
5694                        // ACK!  Must do something better with this.
5695                    }
5696                    ai = ri.activityInfo;
5697                    comp = new ComponentName(ai.applicationInfo.packageName,
5698                            ai.name);
5699                } else {
5700                    ai = getActivityInfo(comp, flags, userId);
5701                    if (ai == null) {
5702                        continue;
5703                    }
5704                }
5705
5706                // Look for any generic query activities that are duplicates
5707                // of this specific one, and remove them from the results.
5708                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
5709                N = results.size();
5710                int j;
5711                for (j=specificsPos; j<N; j++) {
5712                    ResolveInfo sri = results.get(j);
5713                    if ((sri.activityInfo.name.equals(comp.getClassName())
5714                            && sri.activityInfo.applicationInfo.packageName.equals(
5715                                    comp.getPackageName()))
5716                        || (action != null && sri.filter.matchAction(action))) {
5717                        results.remove(j);
5718                        if (DEBUG_INTENT_MATCHING) Log.v(
5719                            TAG, "Removing duplicate item from " + j
5720                            + " due to specific " + specificsPos);
5721                        if (ri == null) {
5722                            ri = sri;
5723                        }
5724                        j--;
5725                        N--;
5726                    }
5727                }
5728
5729                // Add this specific item to its proper place.
5730                if (ri == null) {
5731                    ri = new ResolveInfo();
5732                    ri.activityInfo = ai;
5733                }
5734                results.add(specificsPos, ri);
5735                ri.specificIndex = i;
5736                specificsPos++;
5737            }
5738        }
5739
5740        // Now we go through the remaining generic results and remove any
5741        // duplicate actions that are found here.
5742        N = results.size();
5743        for (int i=specificsPos; i<N-1; i++) {
5744            final ResolveInfo rii = results.get(i);
5745            if (rii.filter == null) {
5746                continue;
5747            }
5748
5749            // Iterate over all of the actions of this result's intent
5750            // filter...  typically this should be just one.
5751            final Iterator<String> it = rii.filter.actionsIterator();
5752            if (it == null) {
5753                continue;
5754            }
5755            while (it.hasNext()) {
5756                final String action = it.next();
5757                if (resultsAction != null && resultsAction.equals(action)) {
5758                    // If this action was explicitly requested, then don't
5759                    // remove things that have it.
5760                    continue;
5761                }
5762                for (int j=i+1; j<N; j++) {
5763                    final ResolveInfo rij = results.get(j);
5764                    if (rij.filter != null && rij.filter.hasAction(action)) {
5765                        results.remove(j);
5766                        if (DEBUG_INTENT_MATCHING) Log.v(
5767                            TAG, "Removing duplicate item from " + j
5768                            + " due to action " + action + " at " + i);
5769                        j--;
5770                        N--;
5771                    }
5772                }
5773            }
5774
5775            // If the caller didn't request filter information, drop it now
5776            // so we don't have to marshall/unmarshall it.
5777            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5778                rii.filter = null;
5779            }
5780        }
5781
5782        // Filter out the caller activity if so requested.
5783        if (caller != null) {
5784            N = results.size();
5785            for (int i=0; i<N; i++) {
5786                ActivityInfo ainfo = results.get(i).activityInfo;
5787                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
5788                        && caller.getClassName().equals(ainfo.name)) {
5789                    results.remove(i);
5790                    break;
5791                }
5792            }
5793        }
5794
5795        // If the caller didn't request filter information,
5796        // drop them now so we don't have to
5797        // marshall/unmarshall it.
5798        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
5799            N = results.size();
5800            for (int i=0; i<N; i++) {
5801                results.get(i).filter = null;
5802            }
5803        }
5804
5805        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
5806        return results;
5807    }
5808
5809    @Override
5810    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
5811            String resolvedType, int flags, int userId) {
5812        return new ParceledListSlice<>(
5813                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
5814    }
5815
5816    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
5817            String resolvedType, int flags, int userId) {
5818        if (!sUserManager.exists(userId)) return Collections.emptyList();
5819        flags = updateFlagsForResolve(flags, userId, intent);
5820        ComponentName comp = intent.getComponent();
5821        if (comp == null) {
5822            if (intent.getSelector() != null) {
5823                intent = intent.getSelector();
5824                comp = intent.getComponent();
5825            }
5826        }
5827        if (comp != null) {
5828            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5829            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
5830            if (ai != null) {
5831                ResolveInfo ri = new ResolveInfo();
5832                ri.activityInfo = ai;
5833                list.add(ri);
5834            }
5835            return list;
5836        }
5837
5838        // reader
5839        synchronized (mPackages) {
5840            String pkgName = intent.getPackage();
5841            if (pkgName == null) {
5842                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
5843            }
5844            final PackageParser.Package pkg = mPackages.get(pkgName);
5845            if (pkg != null) {
5846                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
5847                        userId);
5848            }
5849            return Collections.emptyList();
5850        }
5851    }
5852
5853    @Override
5854    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
5855        if (!sUserManager.exists(userId)) return null;
5856        flags = updateFlagsForResolve(flags, userId, intent);
5857        List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId);
5858        if (query != null) {
5859            if (query.size() >= 1) {
5860                // If there is more than one service with the same priority,
5861                // just arbitrarily pick the first one.
5862                return query.get(0);
5863            }
5864        }
5865        return null;
5866    }
5867
5868    @Override
5869    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
5870            String resolvedType, int flags, int userId) {
5871        return new ParceledListSlice<>(
5872                queryIntentServicesInternal(intent, resolvedType, flags, userId));
5873    }
5874
5875    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
5876            String resolvedType, int flags, int userId) {
5877        if (!sUserManager.exists(userId)) return Collections.emptyList();
5878        flags = updateFlagsForResolve(flags, userId, intent);
5879        ComponentName comp = intent.getComponent();
5880        if (comp == null) {
5881            if (intent.getSelector() != null) {
5882                intent = intent.getSelector();
5883                comp = intent.getComponent();
5884            }
5885        }
5886        if (comp != null) {
5887            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5888            final ServiceInfo si = getServiceInfo(comp, flags, userId);
5889            if (si != null) {
5890                final ResolveInfo ri = new ResolveInfo();
5891                ri.serviceInfo = si;
5892                list.add(ri);
5893            }
5894            return list;
5895        }
5896
5897        // reader
5898        synchronized (mPackages) {
5899            String pkgName = intent.getPackage();
5900            if (pkgName == null) {
5901                return mServices.queryIntent(intent, resolvedType, flags, userId);
5902            }
5903            final PackageParser.Package pkg = mPackages.get(pkgName);
5904            if (pkg != null) {
5905                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
5906                        userId);
5907            }
5908            return Collections.emptyList();
5909        }
5910    }
5911
5912    @Override
5913    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
5914            String resolvedType, int flags, int userId) {
5915        return new ParceledListSlice<>(
5916                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
5917    }
5918
5919    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
5920            Intent intent, String resolvedType, int flags, int userId) {
5921        if (!sUserManager.exists(userId)) return Collections.emptyList();
5922        flags = updateFlagsForResolve(flags, userId, intent);
5923        ComponentName comp = intent.getComponent();
5924        if (comp == null) {
5925            if (intent.getSelector() != null) {
5926                intent = intent.getSelector();
5927                comp = intent.getComponent();
5928            }
5929        }
5930        if (comp != null) {
5931            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
5932            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
5933            if (pi != null) {
5934                final ResolveInfo ri = new ResolveInfo();
5935                ri.providerInfo = pi;
5936                list.add(ri);
5937            }
5938            return list;
5939        }
5940
5941        // reader
5942        synchronized (mPackages) {
5943            String pkgName = intent.getPackage();
5944            if (pkgName == null) {
5945                return mProviders.queryIntent(intent, resolvedType, flags, userId);
5946            }
5947            final PackageParser.Package pkg = mPackages.get(pkgName);
5948            if (pkg != null) {
5949                return mProviders.queryIntentForPackage(
5950                        intent, resolvedType, flags, pkg.providers, userId);
5951            }
5952            return Collections.emptyList();
5953        }
5954    }
5955
5956    @Override
5957    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
5958        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
5959        flags = updateFlagsForPackage(flags, userId, null);
5960        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
5961        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5962                true /* requireFullPermission */, false /* checkShell */,
5963                "get installed packages");
5964
5965        // writer
5966        synchronized (mPackages) {
5967            ArrayList<PackageInfo> list;
5968            if (listUninstalled) {
5969                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
5970                for (PackageSetting ps : mSettings.mPackages.values()) {
5971                    final PackageInfo pi;
5972                    if (ps.pkg != null) {
5973                        pi = generatePackageInfo(ps, flags, userId);
5974                    } else {
5975                        pi = generatePackageInfo(ps, flags, userId);
5976                    }
5977                    if (pi != null) {
5978                        list.add(pi);
5979                    }
5980                }
5981            } else {
5982                list = new ArrayList<PackageInfo>(mPackages.size());
5983                for (PackageParser.Package p : mPackages.values()) {
5984                    final PackageInfo pi =
5985                            generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
5986                    if (pi != null) {
5987                        list.add(pi);
5988                    }
5989                }
5990            }
5991
5992            return new ParceledListSlice<PackageInfo>(list);
5993        }
5994    }
5995
5996    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
5997            String[] permissions, boolean[] tmp, int flags, int userId) {
5998        int numMatch = 0;
5999        final PermissionsState permissionsState = ps.getPermissionsState();
6000        for (int i=0; i<permissions.length; i++) {
6001            final String permission = permissions[i];
6002            if (permissionsState.hasPermission(permission, userId)) {
6003                tmp[i] = true;
6004                numMatch++;
6005            } else {
6006                tmp[i] = false;
6007            }
6008        }
6009        if (numMatch == 0) {
6010            return;
6011        }
6012        final PackageInfo pi;
6013        if (ps.pkg != null) {
6014            pi = generatePackageInfo(ps, flags, userId);
6015        } else {
6016            pi = generatePackageInfo(ps, flags, userId);
6017        }
6018        // The above might return null in cases of uninstalled apps or install-state
6019        // skew across users/profiles.
6020        if (pi != null) {
6021            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
6022                if (numMatch == permissions.length) {
6023                    pi.requestedPermissions = permissions;
6024                } else {
6025                    pi.requestedPermissions = new String[numMatch];
6026                    numMatch = 0;
6027                    for (int i=0; i<permissions.length; i++) {
6028                        if (tmp[i]) {
6029                            pi.requestedPermissions[numMatch] = permissions[i];
6030                            numMatch++;
6031                        }
6032                    }
6033                }
6034            }
6035            list.add(pi);
6036        }
6037    }
6038
6039    @Override
6040    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
6041            String[] permissions, int flags, int userId) {
6042        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6043        flags = updateFlagsForPackage(flags, userId, permissions);
6044        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6045
6046        // writer
6047        synchronized (mPackages) {
6048            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
6049            boolean[] tmpBools = new boolean[permissions.length];
6050            if (listUninstalled) {
6051                for (PackageSetting ps : mSettings.mPackages.values()) {
6052                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
6053                }
6054            } else {
6055                for (PackageParser.Package pkg : mPackages.values()) {
6056                    PackageSetting ps = (PackageSetting)pkg.mExtras;
6057                    if (ps != null) {
6058                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
6059                                userId);
6060                    }
6061                }
6062            }
6063
6064            return new ParceledListSlice<PackageInfo>(list);
6065        }
6066    }
6067
6068    @Override
6069    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
6070        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6071        flags = updateFlagsForApplication(flags, userId, null);
6072        final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0;
6073
6074        // writer
6075        synchronized (mPackages) {
6076            ArrayList<ApplicationInfo> list;
6077            if (listUninstalled) {
6078                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
6079                for (PackageSetting ps : mSettings.mPackages.values()) {
6080                    ApplicationInfo ai;
6081                    if (ps.pkg != null) {
6082                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
6083                                ps.readUserState(userId), userId);
6084                    } else {
6085                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
6086                    }
6087                    if (ai != null) {
6088                        list.add(ai);
6089                    }
6090                }
6091            } else {
6092                list = new ArrayList<ApplicationInfo>(mPackages.size());
6093                for (PackageParser.Package p : mPackages.values()) {
6094                    if (p.mExtras != null) {
6095                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6096                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
6097                        if (ai != null) {
6098                            list.add(ai);
6099                        }
6100                    }
6101                }
6102            }
6103
6104            return new ParceledListSlice<ApplicationInfo>(list);
6105        }
6106    }
6107
6108    @Override
6109    public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) {
6110        if (DISABLE_EPHEMERAL_APPS) {
6111            return null;
6112        }
6113
6114        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6115                "getEphemeralApplications");
6116        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6117                true /* requireFullPermission */, false /* checkShell */,
6118                "getEphemeralApplications");
6119        synchronized (mPackages) {
6120            List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry
6121                    .getEphemeralApplicationsLPw(userId);
6122            if (ephemeralApps != null) {
6123                return new ParceledListSlice<>(ephemeralApps);
6124            }
6125        }
6126        return null;
6127    }
6128
6129    @Override
6130    public boolean isEphemeralApplication(String packageName, int userId) {
6131        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6132                true /* requireFullPermission */, false /* checkShell */,
6133                "isEphemeral");
6134        if (DISABLE_EPHEMERAL_APPS) {
6135            return false;
6136        }
6137
6138        if (!isCallerSameApp(packageName)) {
6139            return false;
6140        }
6141        synchronized (mPackages) {
6142            PackageParser.Package pkg = mPackages.get(packageName);
6143            if (pkg != null) {
6144                return pkg.applicationInfo.isEphemeralApp();
6145            }
6146        }
6147        return false;
6148    }
6149
6150    @Override
6151    public byte[] getEphemeralApplicationCookie(String packageName, int userId) {
6152        if (DISABLE_EPHEMERAL_APPS) {
6153            return null;
6154        }
6155
6156        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6157                true /* requireFullPermission */, false /* checkShell */,
6158                "getCookie");
6159        if (!isCallerSameApp(packageName)) {
6160            return null;
6161        }
6162        synchronized (mPackages) {
6163            return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw(
6164                    packageName, userId);
6165        }
6166    }
6167
6168    @Override
6169    public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) {
6170        if (DISABLE_EPHEMERAL_APPS) {
6171            return true;
6172        }
6173
6174        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6175                true /* requireFullPermission */, true /* checkShell */,
6176                "setCookie");
6177        if (!isCallerSameApp(packageName)) {
6178            return false;
6179        }
6180        synchronized (mPackages) {
6181            return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw(
6182                    packageName, cookie, userId);
6183        }
6184    }
6185
6186    @Override
6187    public Bitmap getEphemeralApplicationIcon(String packageName, int userId) {
6188        if (DISABLE_EPHEMERAL_APPS) {
6189            return null;
6190        }
6191
6192        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS,
6193                "getEphemeralApplicationIcon");
6194        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6195                true /* requireFullPermission */, false /* checkShell */,
6196                "getEphemeralApplicationIcon");
6197        synchronized (mPackages) {
6198            return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw(
6199                    packageName, userId);
6200        }
6201    }
6202
6203    private boolean isCallerSameApp(String packageName) {
6204        PackageParser.Package pkg = mPackages.get(packageName);
6205        return pkg != null
6206                && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid;
6207    }
6208
6209    @Override
6210    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
6211        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
6212    }
6213
6214    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
6215        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
6216
6217        // reader
6218        synchronized (mPackages) {
6219            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
6220            final int userId = UserHandle.getCallingUserId();
6221            while (i.hasNext()) {
6222                final PackageParser.Package p = i.next();
6223                if (p.applicationInfo == null) continue;
6224
6225                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
6226                        && !p.applicationInfo.isDirectBootAware();
6227                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
6228                        && p.applicationInfo.isDirectBootAware();
6229
6230                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
6231                        && (!mSafeMode || isSystemApp(p))
6232                        && (matchesUnaware || matchesAware)) {
6233                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
6234                    if (ps != null) {
6235                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
6236                                ps.readUserState(userId), userId);
6237                        if (ai != null) {
6238                            finalList.add(ai);
6239                        }
6240                    }
6241                }
6242            }
6243        }
6244
6245        return finalList;
6246    }
6247
6248    @Override
6249    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
6250        if (!sUserManager.exists(userId)) return null;
6251        flags = updateFlagsForComponent(flags, userId, name);
6252        // reader
6253        synchronized (mPackages) {
6254            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
6255            PackageSetting ps = provider != null
6256                    ? mSettings.mPackages.get(provider.owner.packageName)
6257                    : null;
6258            return ps != null
6259                    && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)
6260                    ? PackageParser.generateProviderInfo(provider, flags,
6261                            ps.readUserState(userId), userId)
6262                    : null;
6263        }
6264    }
6265
6266    /**
6267     * @deprecated
6268     */
6269    @Deprecated
6270    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
6271        // reader
6272        synchronized (mPackages) {
6273            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
6274                    .entrySet().iterator();
6275            final int userId = UserHandle.getCallingUserId();
6276            while (i.hasNext()) {
6277                Map.Entry<String, PackageParser.Provider> entry = i.next();
6278                PackageParser.Provider p = entry.getValue();
6279                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6280
6281                if (ps != null && p.syncable
6282                        && (!mSafeMode || (p.info.applicationInfo.flags
6283                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
6284                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
6285                            ps.readUserState(userId), userId);
6286                    if (info != null) {
6287                        outNames.add(entry.getKey());
6288                        outInfo.add(info);
6289                    }
6290                }
6291            }
6292        }
6293    }
6294
6295    @Override
6296    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
6297            int uid, int flags) {
6298        final int userId = processName != null ? UserHandle.getUserId(uid)
6299                : UserHandle.getCallingUserId();
6300        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
6301        flags = updateFlagsForComponent(flags, userId, processName);
6302
6303        ArrayList<ProviderInfo> finalList = null;
6304        // reader
6305        synchronized (mPackages) {
6306            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
6307            while (i.hasNext()) {
6308                final PackageParser.Provider p = i.next();
6309                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
6310                if (ps != null && p.info.authority != null
6311                        && (processName == null
6312                                || (p.info.processName.equals(processName)
6313                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
6314                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
6315                    if (finalList == null) {
6316                        finalList = new ArrayList<ProviderInfo>(3);
6317                    }
6318                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
6319                            ps.readUserState(userId), userId);
6320                    if (info != null) {
6321                        finalList.add(info);
6322                    }
6323                }
6324            }
6325        }
6326
6327        if (finalList != null) {
6328            Collections.sort(finalList, mProviderInitOrderSorter);
6329            return new ParceledListSlice<ProviderInfo>(finalList);
6330        }
6331
6332        return ParceledListSlice.emptyList();
6333    }
6334
6335    @Override
6336    public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) {
6337        // reader
6338        synchronized (mPackages) {
6339            final PackageParser.Instrumentation i = mInstrumentation.get(name);
6340            return PackageParser.generateInstrumentationInfo(i, flags);
6341        }
6342    }
6343
6344    @Override
6345    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
6346            String targetPackage, int flags) {
6347        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
6348    }
6349
6350    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
6351            int flags) {
6352        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
6353
6354        // reader
6355        synchronized (mPackages) {
6356            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
6357            while (i.hasNext()) {
6358                final PackageParser.Instrumentation p = i.next();
6359                if (targetPackage == null
6360                        || targetPackage.equals(p.info.targetPackage)) {
6361                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
6362                            flags);
6363                    if (ii != null) {
6364                        finalList.add(ii);
6365                    }
6366                }
6367            }
6368        }
6369
6370        return finalList;
6371    }
6372
6373    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
6374        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
6375        if (overlays == null) {
6376            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
6377            return;
6378        }
6379        for (PackageParser.Package opkg : overlays.values()) {
6380            // Not much to do if idmap fails: we already logged the error
6381            // and we certainly don't want to abort installation of pkg simply
6382            // because an overlay didn't fit properly. For these reasons,
6383            // ignore the return value of createIdmapForPackagePairLI.
6384            createIdmapForPackagePairLI(pkg, opkg);
6385        }
6386    }
6387
6388    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
6389            PackageParser.Package opkg) {
6390        if (!opkg.mTrustedOverlay) {
6391            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
6392                    opkg.baseCodePath + ": overlay not trusted");
6393            return false;
6394        }
6395        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
6396        if (overlaySet == null) {
6397            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
6398                    opkg.baseCodePath + " but target package has no known overlays");
6399            return false;
6400        }
6401        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
6402        // TODO: generate idmap for split APKs
6403        try {
6404            mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid);
6405        } catch (InstallerException e) {
6406            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
6407                    + opkg.baseCodePath);
6408            return false;
6409        }
6410        PackageParser.Package[] overlayArray =
6411            overlaySet.values().toArray(new PackageParser.Package[0]);
6412        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
6413            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
6414                return p1.mOverlayPriority - p2.mOverlayPriority;
6415            }
6416        };
6417        Arrays.sort(overlayArray, cmp);
6418
6419        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
6420        int i = 0;
6421        for (PackageParser.Package p : overlayArray) {
6422            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
6423        }
6424        return true;
6425    }
6426
6427    private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6428        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir");
6429        try {
6430            scanDirLI(dir, parseFlags, scanFlags, currentTime);
6431        } finally {
6432            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6433        }
6434    }
6435
6436    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
6437        final File[] files = dir.listFiles();
6438        if (ArrayUtils.isEmpty(files)) {
6439            Log.d(TAG, "No files in app dir " + dir);
6440            return;
6441        }
6442
6443        if (DEBUG_PACKAGE_SCANNING) {
6444            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
6445                    + " flags=0x" + Integer.toHexString(parseFlags));
6446        }
6447
6448        for (File file : files) {
6449            final boolean isPackage = (isApkFile(file) || file.isDirectory())
6450                    && !PackageInstallerService.isStageName(file.getName());
6451            if (!isPackage) {
6452                // Ignore entries which are not packages
6453                continue;
6454            }
6455            try {
6456                scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
6457                        scanFlags, currentTime, null);
6458            } catch (PackageManagerException e) {
6459                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
6460
6461                // Delete invalid userdata apps
6462                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
6463                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
6464                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
6465                    removeCodePathLI(file);
6466                }
6467            }
6468        }
6469    }
6470
6471    private static File getSettingsProblemFile() {
6472        File dataDir = Environment.getDataDirectory();
6473        File systemDir = new File(dataDir, "system");
6474        File fname = new File(systemDir, "uiderrors.txt");
6475        return fname;
6476    }
6477
6478    static void reportSettingsProblem(int priority, String msg) {
6479        logCriticalInfo(priority, msg);
6480    }
6481
6482    static void logCriticalInfo(int priority, String msg) {
6483        Slog.println(priority, TAG, msg);
6484        EventLogTags.writePmCriticalInfo(msg);
6485        try {
6486            File fname = getSettingsProblemFile();
6487            FileOutputStream out = new FileOutputStream(fname, true);
6488            PrintWriter pw = new FastPrintWriter(out);
6489            SimpleDateFormat formatter = new SimpleDateFormat();
6490            String dateString = formatter.format(new Date(System.currentTimeMillis()));
6491            pw.println(dateString + ": " + msg);
6492            pw.close();
6493            FileUtils.setPermissions(
6494                    fname.toString(),
6495                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
6496                    -1, -1);
6497        } catch (java.io.IOException e) {
6498        }
6499    }
6500
6501    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
6502            int parseFlags) throws PackageManagerException {
6503        if (ps != null
6504                && ps.codePath.equals(srcFile)
6505                && ps.timeStamp == srcFile.lastModified()
6506                && !isCompatSignatureUpdateNeeded(pkg)
6507                && !isRecoverSignatureUpdateNeeded(pkg)) {
6508            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
6509            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6510            ArraySet<PublicKey> signingKs;
6511            synchronized (mPackages) {
6512                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
6513            }
6514            if (ps.signatures.mSignatures != null
6515                    && ps.signatures.mSignatures.length != 0
6516                    && signingKs != null) {
6517                // Optimization: reuse the existing cached certificates
6518                // if the package appears to be unchanged.
6519                pkg.mSignatures = ps.signatures.mSignatures;
6520                pkg.mSigningKeys = signingKs;
6521                return;
6522            }
6523
6524            Slog.w(TAG, "PackageSetting for " + ps.name
6525                    + " is missing signatures.  Collecting certs again to recover them.");
6526        } else {
6527            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
6528        }
6529
6530        try {
6531            PackageParser.collectCertificates(pkg, parseFlags);
6532        } catch (PackageParserException e) {
6533            throw PackageManagerException.from(e);
6534        }
6535    }
6536
6537    /**
6538     *  Traces a package scan.
6539     *  @see #scanPackageLI(File, int, int, long, UserHandle)
6540     */
6541    private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags,
6542            long currentTime, UserHandle user) throws PackageManagerException {
6543        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
6544        try {
6545            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
6546        } finally {
6547            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6548        }
6549    }
6550
6551    /**
6552     *  Scans a package and returns the newly parsed package.
6553     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
6554     */
6555    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
6556            long currentTime, UserHandle user) throws PackageManagerException {
6557        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
6558        parseFlags |= mDefParseFlags;
6559        PackageParser pp = new PackageParser();
6560        pp.setSeparateProcesses(mSeparateProcesses);
6561        pp.setOnlyCoreApps(mOnlyCore);
6562        pp.setDisplayMetrics(mMetrics);
6563
6564        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
6565            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
6566        }
6567
6568        final PackageParser.Package pkg;
6569        try {
6570            pkg = pp.parsePackage(scanFile, parseFlags);
6571        } catch (PackageParserException e) {
6572            throw PackageManagerException.from(e);
6573        }
6574
6575        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6576    }
6577
6578    /**
6579     *  Scans a package and returns the newly parsed package.
6580     *  @throws PackageManagerException on a parse error.
6581     */
6582    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
6583            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6584            throws PackageManagerException {
6585        // If the package has children and this is the first dive in the function
6586        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
6587        // packages (parent and children) would be successfully scanned before the
6588        // actual scan since scanning mutates internal state and we want to atomically
6589        // install the package and its children.
6590        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
6591            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
6592                scanFlags |= SCAN_CHECK_ONLY;
6593            }
6594        } else {
6595            scanFlags &= ~SCAN_CHECK_ONLY;
6596        }
6597
6598        // Scan the parent
6599        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags,
6600                scanFlags, currentTime, user);
6601
6602        // Scan the children
6603        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
6604        for (int i = 0; i < childCount; i++) {
6605            PackageParser.Package childPackage = pkg.childPackages.get(i);
6606            scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags,
6607                    currentTime, user);
6608        }
6609
6610
6611        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
6612            return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
6613        }
6614
6615        return scannedPkg;
6616    }
6617
6618    /**
6619     *  Scans a package and returns the newly parsed package.
6620     *  @throws PackageManagerException on a parse error.
6621     */
6622    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
6623            int parseFlags, int scanFlags, long currentTime, UserHandle user)
6624            throws PackageManagerException {
6625        PackageSetting ps = null;
6626        PackageSetting updatedPkg;
6627        // reader
6628        synchronized (mPackages) {
6629            // Look to see if we already know about this package.
6630            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
6631            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
6632                // This package has been renamed to its original name.  Let's
6633                // use that.
6634                ps = mSettings.peekPackageLPr(oldName);
6635            }
6636            // If there was no original package, see one for the real package name.
6637            if (ps == null) {
6638                ps = mSettings.peekPackageLPr(pkg.packageName);
6639            }
6640            // Check to see if this package could be hiding/updating a system
6641            // package.  Must look for it either under the original or real
6642            // package name depending on our state.
6643            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
6644            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
6645
6646            // If this is a package we don't know about on the system partition, we
6647            // may need to remove disabled child packages on the system partition
6648            // or may need to not add child packages if the parent apk is updated
6649            // on the data partition and no longer defines this child package.
6650            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6651                // If this is a parent package for an updated system app and this system
6652                // app got an OTA update which no longer defines some of the child packages
6653                // we have to prune them from the disabled system packages.
6654                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
6655                if (disabledPs != null) {
6656                    final int scannedChildCount = (pkg.childPackages != null)
6657                            ? pkg.childPackages.size() : 0;
6658                    final int disabledChildCount = disabledPs.childPackageNames != null
6659                            ? disabledPs.childPackageNames.size() : 0;
6660                    for (int i = 0; i < disabledChildCount; i++) {
6661                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
6662                        boolean disabledPackageAvailable = false;
6663                        for (int j = 0; j < scannedChildCount; j++) {
6664                            PackageParser.Package childPkg = pkg.childPackages.get(j);
6665                            if (childPkg.packageName.equals(disabledChildPackageName)) {
6666                                disabledPackageAvailable = true;
6667                                break;
6668                            }
6669                         }
6670                         if (!disabledPackageAvailable) {
6671                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
6672                         }
6673                    }
6674                }
6675            }
6676        }
6677
6678        boolean updatedPkgBetter = false;
6679        // First check if this is a system package that may involve an update
6680        if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
6681            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
6682            // it needs to drop FLAG_PRIVILEGED.
6683            if (locationIsPrivileged(scanFile)) {
6684                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6685            } else {
6686                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
6687            }
6688
6689            if (ps != null && !ps.codePath.equals(scanFile)) {
6690                // The path has changed from what was last scanned...  check the
6691                // version of the new path against what we have stored to determine
6692                // what to do.
6693                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
6694                if (pkg.mVersionCode <= ps.versionCode) {
6695                    // The system package has been updated and the code path does not match
6696                    // Ignore entry. Skip it.
6697                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
6698                            + " ignored: updated version " + ps.versionCode
6699                            + " better than this " + pkg.mVersionCode);
6700                    if (!updatedPkg.codePath.equals(scanFile)) {
6701                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
6702                                + ps.name + " changing from " + updatedPkg.codePathString
6703                                + " to " + scanFile);
6704                        updatedPkg.codePath = scanFile;
6705                        updatedPkg.codePathString = scanFile.toString();
6706                        updatedPkg.resourcePath = scanFile;
6707                        updatedPkg.resourcePathString = scanFile.toString();
6708                    }
6709                    updatedPkg.pkg = pkg;
6710                    updatedPkg.versionCode = pkg.mVersionCode;
6711
6712                    // Update the disabled system child packages to point to the package too.
6713                    final int childCount = updatedPkg.childPackageNames != null
6714                            ? updatedPkg.childPackageNames.size() : 0;
6715                    for (int i = 0; i < childCount; i++) {
6716                        String childPackageName = updatedPkg.childPackageNames.get(i);
6717                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
6718                                childPackageName);
6719                        if (updatedChildPkg != null) {
6720                            updatedChildPkg.pkg = pkg;
6721                            updatedChildPkg.versionCode = pkg.mVersionCode;
6722                        }
6723                    }
6724
6725                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
6726                            + scanFile + " ignored: updated version " + ps.versionCode
6727                            + " better than this " + pkg.mVersionCode);
6728                } else {
6729                    // The current app on the system partition is better than
6730                    // what we have updated to on the data partition; switch
6731                    // back to the system partition version.
6732                    // At this point, its safely assumed that package installation for
6733                    // apps in system partition will go through. If not there won't be a working
6734                    // version of the app
6735                    // writer
6736                    synchronized (mPackages) {
6737                        // Just remove the loaded entries from package lists.
6738                        mPackages.remove(ps.name);
6739                    }
6740
6741                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6742                            + " reverting from " + ps.codePathString
6743                            + ": new version " + pkg.mVersionCode
6744                            + " better than installed " + ps.versionCode);
6745
6746                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6747                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6748                    synchronized (mInstallLock) {
6749                        args.cleanUpResourcesLI();
6750                    }
6751                    synchronized (mPackages) {
6752                        mSettings.enableSystemPackageLPw(ps.name);
6753                    }
6754                    updatedPkgBetter = true;
6755                }
6756            }
6757        }
6758
6759        if (updatedPkg != null) {
6760            // An updated system app will not have the PARSE_IS_SYSTEM flag set
6761            // initially
6762            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
6763
6764            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
6765            // flag set initially
6766            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
6767                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
6768            }
6769        }
6770
6771        // Verify certificates against what was last scanned
6772        collectCertificatesLI(ps, pkg, scanFile, parseFlags);
6773
6774        /*
6775         * A new system app appeared, but we already had a non-system one of the
6776         * same name installed earlier.
6777         */
6778        boolean shouldHideSystemApp = false;
6779        if (updatedPkg == null && ps != null
6780                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
6781            /*
6782             * Check to make sure the signatures match first. If they don't,
6783             * wipe the installed application and its data.
6784             */
6785            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
6786                    != PackageManager.SIGNATURE_MATCH) {
6787                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
6788                        + " signatures don't match existing userdata copy; removing");
6789                deletePackageLI(pkg.packageName, null, true, null, 0, null, false, null);
6790                ps = null;
6791            } else {
6792                /*
6793                 * If the newly-added system app is an older version than the
6794                 * already installed version, hide it. It will be scanned later
6795                 * and re-added like an update.
6796                 */
6797                if (pkg.mVersionCode <= ps.versionCode) {
6798                    shouldHideSystemApp = true;
6799                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
6800                            + " but new version " + pkg.mVersionCode + " better than installed "
6801                            + ps.versionCode + "; hiding system");
6802                } else {
6803                    /*
6804                     * The newly found system app is a newer version that the
6805                     * one previously installed. Simply remove the
6806                     * already-installed application and replace it with our own
6807                     * while keeping the application data.
6808                     */
6809                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
6810                            + " reverting from " + ps.codePathString + ": new version "
6811                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
6812                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
6813                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
6814                    synchronized (mInstallLock) {
6815                        args.cleanUpResourcesLI();
6816                    }
6817                }
6818            }
6819        }
6820
6821        // The apk is forward locked (not public) if its code and resources
6822        // are kept in different files. (except for app in either system or
6823        // vendor path).
6824        // TODO grab this value from PackageSettings
6825        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6826            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
6827                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
6828            }
6829        }
6830
6831        // TODO: extend to support forward-locked splits
6832        String resourcePath = null;
6833        String baseResourcePath = null;
6834        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
6835            if (ps != null && ps.resourcePathString != null) {
6836                resourcePath = ps.resourcePathString;
6837                baseResourcePath = ps.resourcePathString;
6838            } else {
6839                // Should not happen at all. Just log an error.
6840                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
6841            }
6842        } else {
6843            resourcePath = pkg.codePath;
6844            baseResourcePath = pkg.baseCodePath;
6845        }
6846
6847        // Set application objects path explicitly.
6848        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
6849        pkg.setApplicationInfoCodePath(pkg.codePath);
6850        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
6851        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
6852        pkg.setApplicationInfoResourcePath(resourcePath);
6853        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
6854        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
6855
6856        // Note that we invoke the following method only if we are about to unpack an application
6857        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
6858                | SCAN_UPDATE_SIGNATURE, currentTime, user);
6859
6860        /*
6861         * If the system app should be overridden by a previously installed
6862         * data, hide the system app now and let the /data/app scan pick it up
6863         * again.
6864         */
6865        if (shouldHideSystemApp) {
6866            synchronized (mPackages) {
6867                mSettings.disableSystemPackageLPw(pkg.packageName, true);
6868            }
6869        }
6870
6871        return scannedPkg;
6872    }
6873
6874    private static String fixProcessName(String defProcessName,
6875            String processName, int uid) {
6876        if (processName == null) {
6877            return defProcessName;
6878        }
6879        return processName;
6880    }
6881
6882    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
6883            throws PackageManagerException {
6884        if (pkgSetting.signatures.mSignatures != null) {
6885            // Already existing package. Make sure signatures match
6886            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
6887                    == PackageManager.SIGNATURE_MATCH;
6888            if (!match) {
6889                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
6890                        == PackageManager.SIGNATURE_MATCH;
6891            }
6892            if (!match) {
6893                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
6894                        == PackageManager.SIGNATURE_MATCH;
6895            }
6896            if (!match) {
6897                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6898                        + pkg.packageName + " signatures do not match the "
6899                        + "previously installed version; ignoring!");
6900            }
6901        }
6902
6903        // Check for shared user signatures
6904        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
6905            // Already existing package. Make sure signatures match
6906            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6907                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
6908            if (!match) {
6909                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
6910                        == PackageManager.SIGNATURE_MATCH;
6911            }
6912            if (!match) {
6913                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
6914                        == PackageManager.SIGNATURE_MATCH;
6915            }
6916            if (!match) {
6917                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
6918                        "Package " + pkg.packageName
6919                        + " has no signatures that match those in shared user "
6920                        + pkgSetting.sharedUser.name + "; ignoring!");
6921            }
6922        }
6923    }
6924
6925    /**
6926     * Enforces that only the system UID or root's UID can call a method exposed
6927     * via Binder.
6928     *
6929     * @param message used as message if SecurityException is thrown
6930     * @throws SecurityException if the caller is not system or root
6931     */
6932    private static final void enforceSystemOrRoot(String message) {
6933        final int uid = Binder.getCallingUid();
6934        if (uid != Process.SYSTEM_UID && uid != 0) {
6935            throw new SecurityException(message);
6936        }
6937    }
6938
6939    @Override
6940    public void performFstrimIfNeeded() {
6941        enforceSystemOrRoot("Only the system can request fstrim");
6942
6943        // Before everything else, see whether we need to fstrim.
6944        try {
6945            IMountService ms = PackageHelper.getMountService();
6946            if (ms != null) {
6947                final boolean isUpgrade = isUpgrade();
6948                boolean doTrim = isUpgrade;
6949                if (doTrim) {
6950                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
6951                } else {
6952                    final long interval = android.provider.Settings.Global.getLong(
6953                            mContext.getContentResolver(),
6954                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
6955                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
6956                    if (interval > 0) {
6957                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
6958                        if (timeSinceLast > interval) {
6959                            doTrim = true;
6960                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
6961                                    + "; running immediately");
6962                        }
6963                    }
6964                }
6965                if (doTrim) {
6966                    if (!isFirstBoot()) {
6967                        try {
6968                            ActivityManagerNative.getDefault().showBootMessage(
6969                                    mContext.getResources().getString(
6970                                            R.string.android_upgrading_fstrim), true);
6971                        } catch (RemoteException e) {
6972                        }
6973                    }
6974                    ms.runMaintenance();
6975                }
6976            } else {
6977                Slog.e(TAG, "Mount service unavailable!");
6978            }
6979        } catch (RemoteException e) {
6980            // Can't happen; MountService is local
6981        }
6982    }
6983
6984    @Override
6985    public void updatePackagesIfNeeded() {
6986        enforceSystemOrRoot("Only the system can request package update");
6987
6988        // We need to re-extract after an OTA.
6989        boolean causeUpgrade = isUpgrade();
6990
6991        // First boot or factory reset.
6992        // Note: we also handle devices that are upgrading to N right now as if it is their
6993        //       first boot, as they do not have profile data.
6994        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
6995
6996        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
6997        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
6998
6999        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
7000            return;
7001        }
7002
7003        List<PackageParser.Package> pkgs;
7004        synchronized (mPackages) {
7005            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
7006        }
7007
7008        int curr = 0;
7009        int total = pkgs.size();
7010        for (PackageParser.Package pkg : pkgs) {
7011            curr++;
7012
7013            if (DEBUG_DEXOPT) {
7014                Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName);
7015            }
7016
7017            if (PackageDexOptimizer.canOptimizePackage(pkg)) {
7018                // If the cache was pruned, any compiled odex files will likely be out of date
7019                // and would have to be patched (would be SELF_PATCHOAT, which is deprecated).
7020                // Instead, force the extraction in this case.
7021                performDexOpt(pkg.packageName,
7022                        null /* instructionSet */,
7023                        false /* checkProfiles */,
7024                        causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
7025                        false /* force */);
7026            }
7027        }
7028    }
7029
7030    @Override
7031    public void notifyPackageUse(String packageName) {
7032        synchronized (mPackages) {
7033            PackageParser.Package p = mPackages.get(packageName);
7034            if (p == null) {
7035                return;
7036            }
7037            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
7038        }
7039    }
7040
7041    // TODO: this is not used nor needed. Delete it.
7042    @Override
7043    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
7044        return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */,
7045                getFullCompilerFilter(), false /* force */);
7046    }
7047
7048    @Override
7049    public boolean performDexOpt(String packageName, String instructionSet,
7050            boolean checkProfiles, int compileReason, boolean force) {
7051        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7052                getCompilerFilterForReason(compileReason), force);
7053    }
7054
7055    @Override
7056    public boolean performDexOptMode(String packageName, String instructionSet,
7057            boolean checkProfiles, String targetCompilerFilter, boolean force) {
7058        return performDexOptTraced(packageName, instructionSet, checkProfiles,
7059                targetCompilerFilter, force);
7060    }
7061
7062    private boolean performDexOptTraced(String packageName, String instructionSet,
7063                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7064        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7065        try {
7066            return performDexOptInternal(packageName, instructionSet, checkProfiles,
7067                    targetCompilerFilter, force);
7068        } finally {
7069            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7070        }
7071    }
7072
7073    private boolean performDexOptInternal(String packageName, String instructionSet,
7074                boolean checkProfiles, String targetCompilerFilter, boolean force) {
7075        PackageParser.Package p;
7076        final String targetInstructionSet;
7077        synchronized (mPackages) {
7078            p = mPackages.get(packageName);
7079            if (p == null) {
7080                return false;
7081            }
7082            mPackageUsage.write(false);
7083
7084            targetInstructionSet = instructionSet != null ? instructionSet :
7085                    getPrimaryInstructionSet(p.applicationInfo);
7086        }
7087        long callingId = Binder.clearCallingIdentity();
7088        try {
7089            synchronized (mInstallLock) {
7090                final String[] instructionSets = new String[] { targetInstructionSet };
7091                int result = performDexOptInternalWithDependenciesLI(p, instructionSets,
7092                        checkProfiles, targetCompilerFilter, force);
7093                return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
7094            }
7095        } finally {
7096            Binder.restoreCallingIdentity(callingId);
7097        }
7098    }
7099
7100    public ArraySet<String> getOptimizablePackages() {
7101        ArraySet<String> pkgs = new ArraySet<String>();
7102        synchronized (mPackages) {
7103            for (PackageParser.Package p : mPackages.values()) {
7104                if (PackageDexOptimizer.canOptimizePackage(p)) {
7105                    pkgs.add(p.packageName);
7106                }
7107            }
7108        }
7109        return pkgs;
7110    }
7111
7112    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
7113            String instructionSets[], boolean checkProfiles, String targetCompilerFilter,
7114            boolean force) {
7115        // Select the dex optimizer based on the force parameter.
7116        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
7117        //       allocate an object here.
7118        PackageDexOptimizer pdo = force
7119                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
7120                : mPackageDexOptimizer;
7121
7122        // Optimize all dependencies first. Note: we ignore the return value and march on
7123        // on errors.
7124        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
7125        if (!deps.isEmpty()) {
7126            for (PackageParser.Package depPackage : deps) {
7127                // TODO: Analyze and investigate if we (should) profile libraries.
7128                // Currently this will do a full compilation of the library by default.
7129                pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */,
7130                        getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY));
7131            }
7132        }
7133
7134        return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter);
7135    }
7136
7137    Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
7138        if (p.usesLibraries != null || p.usesOptionalLibraries != null) {
7139            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
7140            Set<String> collectedNames = new HashSet<>();
7141            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
7142
7143            retValue.remove(p);
7144
7145            return retValue;
7146        } else {
7147            return Collections.emptyList();
7148        }
7149    }
7150
7151    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
7152            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7153        if (!collectedNames.contains(p.packageName)) {
7154            collectedNames.add(p.packageName);
7155            collected.add(p);
7156
7157            if (p.usesLibraries != null) {
7158                findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames);
7159            }
7160            if (p.usesOptionalLibraries != null) {
7161                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected,
7162                        collectedNames);
7163            }
7164        }
7165    }
7166
7167    private void findSharedNonSystemLibrariesRecursive(Collection<String> libs,
7168            Collection<PackageParser.Package> collected, Set<String> collectedNames) {
7169        for (String libName : libs) {
7170            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName);
7171            if (libPkg != null) {
7172                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
7173            }
7174        }
7175    }
7176
7177    private PackageParser.Package findSharedNonSystemLibrary(String libName) {
7178        synchronized (mPackages) {
7179            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
7180            if (lib != null && lib.apk != null) {
7181                return mPackages.get(lib.apk);
7182            }
7183        }
7184        return null;
7185    }
7186
7187    public void shutdown() {
7188        mPackageUsage.write(true);
7189    }
7190
7191    @Override
7192    public void forceDexOpt(String packageName) {
7193        enforceSystemOrRoot("forceDexOpt");
7194
7195        PackageParser.Package pkg;
7196        synchronized (mPackages) {
7197            pkg = mPackages.get(packageName);
7198            if (pkg == null) {
7199                throw new IllegalArgumentException("Unknown package: " + packageName);
7200            }
7201        }
7202
7203        synchronized (mInstallLock) {
7204            final String[] instructionSets = new String[] {
7205                    getPrimaryInstructionSet(pkg.applicationInfo) };
7206
7207            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
7208
7209            // Whoever is calling forceDexOpt wants a fully compiled package.
7210            // Don't use profiles since that may cause compilation to be skipped.
7211            final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets,
7212                    false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT),
7213                    true /* force */);
7214
7215            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7216            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
7217                throw new IllegalStateException("Failed to dexopt: " + res);
7218            }
7219        }
7220    }
7221
7222    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
7223        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
7224            Slog.w(TAG, "Unable to update from " + oldPkg.name
7225                    + " to " + newPkg.packageName
7226                    + ": old package not in system partition");
7227            return false;
7228        } else if (mPackages.get(oldPkg.name) != null) {
7229            Slog.w(TAG, "Unable to update from " + oldPkg.name
7230                    + " to " + newPkg.packageName
7231                    + ": old package still exists");
7232            return false;
7233        }
7234        return true;
7235    }
7236
7237    private boolean removeDataDirsLI(String volumeUuid, String packageName) {
7238        // TODO: triage flags as part of 26466827
7239        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7240
7241        boolean res = true;
7242        final int[] users = sUserManager.getUserIds();
7243        for (int user : users) {
7244            try {
7245                mInstaller.destroyAppData(volumeUuid, packageName, user, flags);
7246            } catch (InstallerException e) {
7247                Slog.w(TAG, "Failed to delete data directory", e);
7248                res = false;
7249            }
7250        }
7251        return res;
7252    }
7253
7254    void removeCodePathLI(File codePath) {
7255        if (codePath.isDirectory()) {
7256            try {
7257                mInstaller.rmPackageDir(codePath.getAbsolutePath());
7258            } catch (InstallerException e) {
7259                Slog.w(TAG, "Failed to remove code path", e);
7260            }
7261        } else {
7262            codePath.delete();
7263        }
7264    }
7265
7266    void destroyAppDataLI(String volumeUuid, String packageName, int userId, int flags) {
7267        try {
7268            mInstaller.destroyAppData(volumeUuid, packageName, userId, flags);
7269        } catch (InstallerException e) {
7270            Slog.w(TAG, "Failed to destroy app data", e);
7271        }
7272    }
7273
7274    void restoreconAppDataLI(String volumeUuid, String packageName, int userId, int flags,
7275            int appId, String seinfo) {
7276        try {
7277            mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, seinfo);
7278        } catch (InstallerException e) {
7279            Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e);
7280        }
7281    }
7282
7283    private void deleteProfilesLI(String packageName, boolean destroy) {
7284        final PackageParser.Package pkg;
7285        synchronized (mPackages) {
7286            pkg = mPackages.get(packageName);
7287        }
7288        if (pkg == null) {
7289            Slog.w(TAG, "Failed to delete profiles. No package: " + packageName);
7290            return;
7291        }
7292        deleteProfilesLI(pkg, destroy);
7293    }
7294
7295    private void deleteProfilesLI(PackageParser.Package pkg, boolean destroy) {
7296        try {
7297            if (destroy) {
7298                mInstaller.destroyAppProfiles(pkg.packageName);
7299            } else {
7300                mInstaller.clearAppProfiles(pkg.packageName);
7301            }
7302        } catch (InstallerException ex) {
7303            Log.e(TAG, "Could not delete profiles for package " + pkg.packageName);
7304        }
7305    }
7306
7307    private void deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
7308        final PackageParser.Package pkg;
7309        synchronized (mPackages) {
7310            pkg = mPackages.get(packageName);
7311        }
7312        if (pkg == null) {
7313            Slog.w(TAG, "Failed to delete code cache directory. No package: " + packageName);
7314            return;
7315        }
7316        deleteCodeCacheDirsLI(pkg);
7317    }
7318
7319    private void deleteCodeCacheDirsLI(PackageParser.Package pkg) {
7320        // TODO: triage flags as part of 26466827
7321        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
7322
7323        int[] users = sUserManager.getUserIds();
7324        int res = 0;
7325        for (int user : users) {
7326            // Remove the parent code cache
7327            try {
7328                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, user,
7329                        flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7330            } catch (InstallerException e) {
7331                Slog.w(TAG, "Failed to delete code cache directory", e);
7332            }
7333            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7334            for (int i = 0; i < childCount; i++) {
7335                PackageParser.Package childPkg = pkg.childPackages.get(i);
7336                // Remove the child code cache
7337                try {
7338                    mInstaller.clearAppData(childPkg.volumeUuid, childPkg.packageName,
7339                            user, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
7340                } catch (InstallerException e) {
7341                    Slog.w(TAG, "Failed to delete code cache directory", e);
7342                }
7343            }
7344        }
7345    }
7346
7347    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
7348            long lastUpdateTime) {
7349        // Set parent install/update time
7350        PackageSetting ps = (PackageSetting) pkg.mExtras;
7351        if (ps != null) {
7352            ps.firstInstallTime = firstInstallTime;
7353            ps.lastUpdateTime = lastUpdateTime;
7354        }
7355        // Set children install/update time
7356        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7357        for (int i = 0; i < childCount; i++) {
7358            PackageParser.Package childPkg = pkg.childPackages.get(i);
7359            ps = (PackageSetting) childPkg.mExtras;
7360            if (ps != null) {
7361                ps.firstInstallTime = firstInstallTime;
7362                ps.lastUpdateTime = lastUpdateTime;
7363            }
7364        }
7365    }
7366
7367    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
7368            PackageParser.Package changingLib) {
7369        if (file.path != null) {
7370            usesLibraryFiles.add(file.path);
7371            return;
7372        }
7373        PackageParser.Package p = mPackages.get(file.apk);
7374        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
7375            // If we are doing this while in the middle of updating a library apk,
7376            // then we need to make sure to use that new apk for determining the
7377            // dependencies here.  (We haven't yet finished committing the new apk
7378            // to the package manager state.)
7379            if (p == null || p.packageName.equals(changingLib.packageName)) {
7380                p = changingLib;
7381            }
7382        }
7383        if (p != null) {
7384            usesLibraryFiles.addAll(p.getAllCodePaths());
7385        }
7386    }
7387
7388    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
7389            PackageParser.Package changingLib) throws PackageManagerException {
7390        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
7391            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
7392            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
7393            for (int i=0; i<N; i++) {
7394                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
7395                if (file == null) {
7396                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
7397                            "Package " + pkg.packageName + " requires unavailable shared library "
7398                            + pkg.usesLibraries.get(i) + "; failing!");
7399                }
7400                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7401            }
7402            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
7403            for (int i=0; i<N; i++) {
7404                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
7405                if (file == null) {
7406                    Slog.w(TAG, "Package " + pkg.packageName
7407                            + " desires unavailable shared library "
7408                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
7409                } else {
7410                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
7411                }
7412            }
7413            N = usesLibraryFiles.size();
7414            if (N > 0) {
7415                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
7416            } else {
7417                pkg.usesLibraryFiles = null;
7418            }
7419        }
7420    }
7421
7422    private static boolean hasString(List<String> list, List<String> which) {
7423        if (list == null) {
7424            return false;
7425        }
7426        for (int i=list.size()-1; i>=0; i--) {
7427            for (int j=which.size()-1; j>=0; j--) {
7428                if (which.get(j).equals(list.get(i))) {
7429                    return true;
7430                }
7431            }
7432        }
7433        return false;
7434    }
7435
7436    private void updateAllSharedLibrariesLPw() {
7437        for (PackageParser.Package pkg : mPackages.values()) {
7438            try {
7439                updateSharedLibrariesLPw(pkg, null);
7440            } catch (PackageManagerException e) {
7441                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7442            }
7443        }
7444    }
7445
7446    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
7447            PackageParser.Package changingPkg) {
7448        ArrayList<PackageParser.Package> res = null;
7449        for (PackageParser.Package pkg : mPackages.values()) {
7450            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
7451                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
7452                if (res == null) {
7453                    res = new ArrayList<PackageParser.Package>();
7454                }
7455                res.add(pkg);
7456                try {
7457                    updateSharedLibrariesLPw(pkg, changingPkg);
7458                } catch (PackageManagerException e) {
7459                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
7460                }
7461            }
7462        }
7463        return res;
7464    }
7465
7466    /**
7467     * Derive the value of the {@code cpuAbiOverride} based on the provided
7468     * value and an optional stored value from the package settings.
7469     */
7470    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
7471        String cpuAbiOverride = null;
7472
7473        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
7474            cpuAbiOverride = null;
7475        } else if (abiOverride != null) {
7476            cpuAbiOverride = abiOverride;
7477        } else if (settings != null) {
7478            cpuAbiOverride = settings.cpuAbiOverrideString;
7479        }
7480
7481        return cpuAbiOverride;
7482    }
7483
7484    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags,
7485            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7486        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
7487        // If the package has children and this is the first dive in the function
7488        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
7489        // whether all packages (parent and children) would be successfully scanned
7490        // before the actual scan since scanning mutates internal state and we want
7491        // to atomically install the package and its children.
7492        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7493            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
7494                scanFlags |= SCAN_CHECK_ONLY;
7495            }
7496        } else {
7497            scanFlags &= ~SCAN_CHECK_ONLY;
7498        }
7499
7500        final PackageParser.Package scannedPkg;
7501        try {
7502            // Scan the parent
7503            scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user);
7504            // Scan the children
7505            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
7506            for (int i = 0; i < childCount; i++) {
7507                PackageParser.Package childPkg = pkg.childPackages.get(i);
7508                scanPackageLI(childPkg, parseFlags,
7509                        scanFlags, currentTime, user);
7510            }
7511        } finally {
7512            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7513        }
7514
7515        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7516            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
7517        }
7518
7519        return scannedPkg;
7520    }
7521
7522    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
7523            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
7524        boolean success = false;
7525        try {
7526            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
7527                    currentTime, user);
7528            success = true;
7529            return res;
7530        } finally {
7531            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
7532                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
7533            }
7534        }
7535    }
7536
7537    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
7538            int scanFlags, long currentTime, UserHandle user)
7539            throws PackageManagerException {
7540        final File scanFile = new File(pkg.codePath);
7541        if (pkg.applicationInfo.getCodePath() == null ||
7542                pkg.applicationInfo.getResourcePath() == null) {
7543            // Bail out. The resource and code paths haven't been set.
7544            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
7545                    "Code and resource paths haven't been set correctly");
7546        }
7547
7548        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
7549            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
7550        } else {
7551            // Only allow system apps to be flagged as core apps.
7552            pkg.coreApp = false;
7553        }
7554
7555        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
7556            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
7557        }
7558
7559        if (mCustomResolverComponentName != null &&
7560                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
7561            setUpCustomResolverActivity(pkg);
7562        }
7563
7564        if (pkg.packageName.equals("android")) {
7565            synchronized (mPackages) {
7566                if (mAndroidApplication != null) {
7567                    Slog.w(TAG, "*************************************************");
7568                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
7569                    Slog.w(TAG, " file=" + scanFile);
7570                    Slog.w(TAG, "*************************************************");
7571                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7572                            "Core android package being redefined.  Skipping.");
7573                }
7574
7575                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7576                    // Set up information for our fall-back user intent resolution activity.
7577                    mPlatformPackage = pkg;
7578                    pkg.mVersionCode = mSdkVersion;
7579                    mAndroidApplication = pkg.applicationInfo;
7580
7581                    if (!mResolverReplaced) {
7582                        mResolveActivity.applicationInfo = mAndroidApplication;
7583                        mResolveActivity.name = ResolverActivity.class.getName();
7584                        mResolveActivity.packageName = mAndroidApplication.packageName;
7585                        mResolveActivity.processName = "system:ui";
7586                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7587                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7588                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
7589                        mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
7590                        mResolveActivity.exported = true;
7591                        mResolveActivity.enabled = true;
7592                        mResolveInfo.activityInfo = mResolveActivity;
7593                        mResolveInfo.priority = 0;
7594                        mResolveInfo.preferredOrder = 0;
7595                        mResolveInfo.match = 0;
7596                        mResolveComponentName = new ComponentName(
7597                                mAndroidApplication.packageName, mResolveActivity.name);
7598                    }
7599                }
7600            }
7601        }
7602
7603        if (DEBUG_PACKAGE_SCANNING) {
7604            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7605                Log.d(TAG, "Scanning package " + pkg.packageName);
7606        }
7607
7608        synchronized (mPackages) {
7609            if (mPackages.containsKey(pkg.packageName)
7610                    || mSharedLibraries.containsKey(pkg.packageName)) {
7611                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
7612                        "Application package " + pkg.packageName
7613                                + " already installed.  Skipping duplicate.");
7614            }
7615
7616            // If we're only installing presumed-existing packages, require that the
7617            // scanned APK is both already known and at the path previously established
7618            // for it.  Previously unknown packages we pick up normally, but if we have an
7619            // a priori expectation about this package's install presence, enforce it.
7620            // With a singular exception for new system packages. When an OTA contains
7621            // a new system package, we allow the codepath to change from a system location
7622            // to the user-installed location. If we don't allow this change, any newer,
7623            // user-installed version of the application will be ignored.
7624            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
7625                if (mExpectingBetter.containsKey(pkg.packageName)) {
7626                    logCriticalInfo(Log.WARN,
7627                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
7628                } else {
7629                    PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
7630                    if (known != null) {
7631                        if (DEBUG_PACKAGE_SCANNING) {
7632                            Log.d(TAG, "Examining " + pkg.codePath
7633                                    + " and requiring known paths " + known.codePathString
7634                                    + " & " + known.resourcePathString);
7635                        }
7636                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
7637                                || !pkg.applicationInfo.getResourcePath().equals(
7638                                known.resourcePathString)) {
7639                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
7640                                    "Application package " + pkg.packageName
7641                                            + " found at " + pkg.applicationInfo.getCodePath()
7642                                            + " but expected at " + known.codePathString
7643                                            + "; ignoring.");
7644                        }
7645                    }
7646                }
7647            }
7648        }
7649
7650        // Initialize package source and resource directories
7651        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
7652        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
7653
7654        SharedUserSetting suid = null;
7655        PackageSetting pkgSetting = null;
7656
7657        if (!isSystemApp(pkg)) {
7658            // Only system apps can use these features.
7659            pkg.mOriginalPackages = null;
7660            pkg.mRealPackage = null;
7661            pkg.mAdoptPermissions = null;
7662        }
7663
7664        // Getting the package setting may have a side-effect, so if we
7665        // are only checking if scan would succeed, stash a copy of the
7666        // old setting to restore at the end.
7667        PackageSetting nonMutatedPs = null;
7668
7669        // writer
7670        synchronized (mPackages) {
7671            if (pkg.mSharedUserId != null) {
7672                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
7673                if (suid == null) {
7674                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7675                            "Creating application package " + pkg.packageName
7676                            + " for shared user failed");
7677                }
7678                if (DEBUG_PACKAGE_SCANNING) {
7679                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
7680                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
7681                                + "): packages=" + suid.packages);
7682                }
7683            }
7684
7685            // Check if we are renaming from an original package name.
7686            PackageSetting origPackage = null;
7687            String realName = null;
7688            if (pkg.mOriginalPackages != null) {
7689                // This package may need to be renamed to a previously
7690                // installed name.  Let's check on that...
7691                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
7692                if (pkg.mOriginalPackages.contains(renamed)) {
7693                    // This package had originally been installed as the
7694                    // original name, and we have already taken care of
7695                    // transitioning to the new one.  Just update the new
7696                    // one to continue using the old name.
7697                    realName = pkg.mRealPackage;
7698                    if (!pkg.packageName.equals(renamed)) {
7699                        // Callers into this function may have already taken
7700                        // care of renaming the package; only do it here if
7701                        // it is not already done.
7702                        pkg.setPackageName(renamed);
7703                    }
7704
7705                } else {
7706                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
7707                        if ((origPackage = mSettings.peekPackageLPr(
7708                                pkg.mOriginalPackages.get(i))) != null) {
7709                            // We do have the package already installed under its
7710                            // original name...  should we use it?
7711                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
7712                                // New package is not compatible with original.
7713                                origPackage = null;
7714                                continue;
7715                            } else if (origPackage.sharedUser != null) {
7716                                // Make sure uid is compatible between packages.
7717                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
7718                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
7719                                            + " to " + pkg.packageName + ": old uid "
7720                                            + origPackage.sharedUser.name
7721                                            + " differs from " + pkg.mSharedUserId);
7722                                    origPackage = null;
7723                                    continue;
7724                                }
7725                            } else {
7726                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
7727                                        + pkg.packageName + " to old name " + origPackage.name);
7728                            }
7729                            break;
7730                        }
7731                    }
7732                }
7733            }
7734
7735            if (mTransferedPackages.contains(pkg.packageName)) {
7736                Slog.w(TAG, "Package " + pkg.packageName
7737                        + " was transferred to another, but its .apk remains");
7738            }
7739
7740            // See comments in nonMutatedPs declaration
7741            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
7742                PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName);
7743                if (foundPs != null) {
7744                    nonMutatedPs = new PackageSetting(foundPs);
7745                }
7746            }
7747
7748            // Just create the setting, don't add it yet. For already existing packages
7749            // the PkgSetting exists already and doesn't have to be created.
7750            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
7751                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
7752                    pkg.applicationInfo.primaryCpuAbi,
7753                    pkg.applicationInfo.secondaryCpuAbi,
7754                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
7755                    user, false);
7756            if (pkgSetting == null) {
7757                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
7758                        "Creating application package " + pkg.packageName + " failed");
7759            }
7760
7761            if (pkgSetting.origPackage != null) {
7762                // If we are first transitioning from an original package,
7763                // fix up the new package's name now.  We need to do this after
7764                // looking up the package under its new name, so getPackageLP
7765                // can take care of fiddling things correctly.
7766                pkg.setPackageName(origPackage.name);
7767
7768                // File a report about this.
7769                String msg = "New package " + pkgSetting.realName
7770                        + " renamed to replace old package " + pkgSetting.name;
7771                reportSettingsProblem(Log.WARN, msg);
7772
7773                // Make a note of it.
7774                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
7775                    mTransferedPackages.add(origPackage.name);
7776                }
7777
7778                // No longer need to retain this.
7779                pkgSetting.origPackage = null;
7780            }
7781
7782            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
7783                // Make a note of it.
7784                mTransferedPackages.add(pkg.packageName);
7785            }
7786
7787            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
7788                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7789            }
7790
7791            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7792                // Check all shared libraries and map to their actual file path.
7793                // We only do this here for apps not on a system dir, because those
7794                // are the only ones that can fail an install due to this.  We
7795                // will take care of the system apps by updating all of their
7796                // library paths after the scan is done.
7797                updateSharedLibrariesLPw(pkg, null);
7798            }
7799
7800            if (mFoundPolicyFile) {
7801                SELinuxMMAC.assignSeinfoValue(pkg);
7802            }
7803
7804            pkg.applicationInfo.uid = pkgSetting.appId;
7805            pkg.mExtras = pkgSetting;
7806            if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) {
7807                if (checkUpgradeKeySetLP(pkgSetting, pkg)) {
7808                    // We just determined the app is signed correctly, so bring
7809                    // over the latest parsed certs.
7810                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7811                } else {
7812                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7813                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
7814                                "Package " + pkg.packageName + " upgrade keys do not match the "
7815                                + "previously installed version");
7816                    } else {
7817                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
7818                        String msg = "System package " + pkg.packageName
7819                            + " signature changed; retaining data.";
7820                        reportSettingsProblem(Log.WARN, msg);
7821                    }
7822                }
7823            } else {
7824                try {
7825                    verifySignaturesLP(pkgSetting, pkg);
7826                    // We just determined the app is signed correctly, so bring
7827                    // over the latest parsed certs.
7828                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7829                } catch (PackageManagerException e) {
7830                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
7831                        throw e;
7832                    }
7833                    // The signature has changed, but this package is in the system
7834                    // image...  let's recover!
7835                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
7836                    // However...  if this package is part of a shared user, but it
7837                    // doesn't match the signature of the shared user, let's fail.
7838                    // What this means is that you can't change the signatures
7839                    // associated with an overall shared user, which doesn't seem all
7840                    // that unreasonable.
7841                    if (pkgSetting.sharedUser != null) {
7842                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
7843                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
7844                            throw new PackageManagerException(
7845                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
7846                                            "Signature mismatch for shared user: "
7847                                            + pkgSetting.sharedUser);
7848                        }
7849                    }
7850                    // File a report about this.
7851                    String msg = "System package " + pkg.packageName
7852                        + " signature changed; retaining data.";
7853                    reportSettingsProblem(Log.WARN, msg);
7854                }
7855            }
7856            // Verify that this new package doesn't have any content providers
7857            // that conflict with existing packages.  Only do this if the
7858            // package isn't already installed, since we don't want to break
7859            // things that are installed.
7860            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
7861                final int N = pkg.providers.size();
7862                int i;
7863                for (i=0; i<N; i++) {
7864                    PackageParser.Provider p = pkg.providers.get(i);
7865                    if (p.info.authority != null) {
7866                        String names[] = p.info.authority.split(";");
7867                        for (int j = 0; j < names.length; j++) {
7868                            if (mProvidersByAuthority.containsKey(names[j])) {
7869                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
7870                                final String otherPackageName =
7871                                        ((other != null && other.getComponentName() != null) ?
7872                                                other.getComponentName().getPackageName() : "?");
7873                                throw new PackageManagerException(
7874                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
7875                                                "Can't install because provider name " + names[j]
7876                                                + " (in package " + pkg.applicationInfo.packageName
7877                                                + ") is already used by " + otherPackageName);
7878                            }
7879                        }
7880                    }
7881                }
7882            }
7883
7884            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
7885                // This package wants to adopt ownership of permissions from
7886                // another package.
7887                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
7888                    final String origName = pkg.mAdoptPermissions.get(i);
7889                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
7890                    if (orig != null) {
7891                        if (verifyPackageUpdateLPr(orig, pkg)) {
7892                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
7893                                    + pkg.packageName);
7894                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
7895                        }
7896                    }
7897                }
7898            }
7899        }
7900
7901        final String pkgName = pkg.packageName;
7902
7903        final long scanFileTime = scanFile.lastModified();
7904        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
7905        pkg.applicationInfo.processName = fixProcessName(
7906                pkg.applicationInfo.packageName,
7907                pkg.applicationInfo.processName,
7908                pkg.applicationInfo.uid);
7909
7910        if (pkg != mPlatformPackage) {
7911            // Get all of our default paths setup
7912            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
7913        }
7914
7915        final String path = scanFile.getPath();
7916        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
7917
7918        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
7919            derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */);
7920
7921            // Some system apps still use directory structure for native libraries
7922            // in which case we might end up not detecting abi solely based on apk
7923            // structure. Try to detect abi based on directory structure.
7924            if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
7925                    pkg.applicationInfo.primaryCpuAbi == null) {
7926                setBundledAppAbisAndRoots(pkg, pkgSetting);
7927                setNativeLibraryPaths(pkg);
7928            }
7929
7930        } else {
7931            if ((scanFlags & SCAN_MOVE) != 0) {
7932                // We haven't run dex-opt for this move (since we've moved the compiled output too)
7933                // but we already have this packages package info in the PackageSetting. We just
7934                // use that and derive the native library path based on the new codepath.
7935                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
7936                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
7937            }
7938
7939            // Set native library paths again. For moves, the path will be updated based on the
7940            // ABIs we've determined above. For non-moves, the path will be updated based on the
7941            // ABIs we determined during compilation, but the path will depend on the final
7942            // package path (after the rename away from the stage path).
7943            setNativeLibraryPaths(pkg);
7944        }
7945
7946        // This is a special case for the "system" package, where the ABI is
7947        // dictated by the zygote configuration (and init.rc). We should keep track
7948        // of this ABI so that we can deal with "normal" applications that run under
7949        // the same UID correctly.
7950        if (mPlatformPackage == pkg) {
7951            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
7952                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
7953        }
7954
7955        // If there's a mismatch between the abi-override in the package setting
7956        // and the abiOverride specified for the install. Warn about this because we
7957        // would've already compiled the app without taking the package setting into
7958        // account.
7959        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
7960            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
7961                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
7962                        " for package " + pkg.packageName);
7963            }
7964        }
7965
7966        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7967        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7968        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
7969
7970        // Copy the derived override back to the parsed package, so that we can
7971        // update the package settings accordingly.
7972        pkg.cpuAbiOverride = cpuAbiOverride;
7973
7974        if (DEBUG_ABI_SELECTION) {
7975            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
7976                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
7977                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
7978        }
7979
7980        // Push the derived path down into PackageSettings so we know what to
7981        // clean up at uninstall time.
7982        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
7983
7984        if (DEBUG_ABI_SELECTION) {
7985            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
7986                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
7987                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
7988        }
7989
7990        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
7991            // We don't do this here during boot because we can do it all
7992            // at once after scanning all existing packages.
7993            //
7994            // We also do this *before* we perform dexopt on this package, so that
7995            // we can avoid redundant dexopts, and also to make sure we've got the
7996            // code and package path correct.
7997            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
7998                    pkg, true /* boot complete */);
7999        }
8000
8001        if (mFactoryTest && pkg.requestedPermissions.contains(
8002                android.Manifest.permission.FACTORY_TEST)) {
8003            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
8004        }
8005
8006        ArrayList<PackageParser.Package> clientLibPkgs = null;
8007
8008        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8009            if (nonMutatedPs != null) {
8010                synchronized (mPackages) {
8011                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
8012                }
8013            }
8014            return pkg;
8015        }
8016
8017        // Only privileged apps and updated privileged apps can add child packages.
8018        if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
8019            if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) {
8020                throw new PackageManagerException("Only privileged apps and updated "
8021                        + "privileged apps can add child packages. Ignoring package "
8022                        + pkg.packageName);
8023            }
8024            final int childCount = pkg.childPackages.size();
8025            for (int i = 0; i < childCount; i++) {
8026                PackageParser.Package childPkg = pkg.childPackages.get(i);
8027                if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
8028                        childPkg.packageName)) {
8029                    throw new PackageManagerException("Cannot override a child package of "
8030                            + "another disabled system app. Ignoring package " + pkg.packageName);
8031                }
8032            }
8033        }
8034
8035        // writer
8036        synchronized (mPackages) {
8037            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8038                // Only system apps can add new shared libraries.
8039                if (pkg.libraryNames != null) {
8040                    for (int i=0; i<pkg.libraryNames.size(); i++) {
8041                        String name = pkg.libraryNames.get(i);
8042                        boolean allowed = false;
8043                        if (pkg.isUpdatedSystemApp()) {
8044                            // New library entries can only be added through the
8045                            // system image.  This is important to get rid of a lot
8046                            // of nasty edge cases: for example if we allowed a non-
8047                            // system update of the app to add a library, then uninstalling
8048                            // the update would make the library go away, and assumptions
8049                            // we made such as through app install filtering would now
8050                            // have allowed apps on the device which aren't compatible
8051                            // with it.  Better to just have the restriction here, be
8052                            // conservative, and create many fewer cases that can negatively
8053                            // impact the user experience.
8054                            final PackageSetting sysPs = mSettings
8055                                    .getDisabledSystemPkgLPr(pkg.packageName);
8056                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
8057                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
8058                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
8059                                        allowed = true;
8060                                        break;
8061                                    }
8062                                }
8063                            }
8064                        } else {
8065                            allowed = true;
8066                        }
8067                        if (allowed) {
8068                            if (!mSharedLibraries.containsKey(name)) {
8069                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
8070                            } else if (!name.equals(pkg.packageName)) {
8071                                Slog.w(TAG, "Package " + pkg.packageName + " library "
8072                                        + name + " already exists; skipping");
8073                            }
8074                        } else {
8075                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
8076                                    + name + " that is not declared on system image; skipping");
8077                        }
8078                    }
8079                    if ((scanFlags & SCAN_BOOTING) == 0) {
8080                        // If we are not booting, we need to update any applications
8081                        // that are clients of our shared library.  If we are booting,
8082                        // this will all be done once the scan is complete.
8083                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
8084                    }
8085                }
8086            }
8087        }
8088
8089        // Request the ActivityManager to kill the process(only for existing packages)
8090        // so that we do not end up in a confused state while the user is still using the older
8091        // version of the application while the new one gets installed.
8092        final boolean isReplacing = (scanFlags & SCAN_REPLACING) != 0;
8093        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
8094        if (killApp) {
8095            if (isReplacing) {
8096                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "killApplication");
8097
8098                killApplication(pkg.applicationInfo.packageName,
8099                            pkg.applicationInfo.uid, "replace pkg");
8100
8101                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8102            }
8103        }
8104
8105        // Also need to kill any apps that are dependent on the library.
8106        if (clientLibPkgs != null) {
8107            for (int i=0; i<clientLibPkgs.size(); i++) {
8108                PackageParser.Package clientPkg = clientLibPkgs.get(i);
8109                killApplication(clientPkg.applicationInfo.packageName,
8110                        clientPkg.applicationInfo.uid, "update lib");
8111            }
8112        }
8113
8114        // Make sure we're not adding any bogus keyset info
8115        KeySetManagerService ksms = mSettings.mKeySetManagerService;
8116        ksms.assertScannedPackageValid(pkg);
8117
8118        // writer
8119        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
8120
8121        boolean createIdmapFailed = false;
8122        synchronized (mPackages) {
8123            // We don't expect installation to fail beyond this point
8124
8125            // Add the new setting to mSettings
8126            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
8127            // Add the new setting to mPackages
8128            mPackages.put(pkg.applicationInfo.packageName, pkg);
8129            // Make sure we don't accidentally delete its data.
8130            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
8131            while (iter.hasNext()) {
8132                PackageCleanItem item = iter.next();
8133                if (pkgName.equals(item.packageName)) {
8134                    iter.remove();
8135                }
8136            }
8137
8138            // Take care of first install / last update times.
8139            if (currentTime != 0) {
8140                if (pkgSetting.firstInstallTime == 0) {
8141                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
8142                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
8143                    pkgSetting.lastUpdateTime = currentTime;
8144                }
8145            } else if (pkgSetting.firstInstallTime == 0) {
8146                // We need *something*.  Take time time stamp of the file.
8147                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
8148            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
8149                if (scanFileTime != pkgSetting.timeStamp) {
8150                    // A package on the system image has changed; consider this
8151                    // to be an update.
8152                    pkgSetting.lastUpdateTime = scanFileTime;
8153                }
8154            }
8155
8156            // Add the package's KeySets to the global KeySetManagerService
8157            ksms.addScannedPackageLPw(pkg);
8158
8159            int N = pkg.providers.size();
8160            StringBuilder r = null;
8161            int i;
8162            for (i=0; i<N; i++) {
8163                PackageParser.Provider p = pkg.providers.get(i);
8164                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
8165                        p.info.processName, pkg.applicationInfo.uid);
8166                mProviders.addProvider(p);
8167                p.syncable = p.info.isSyncable;
8168                if (p.info.authority != null) {
8169                    String names[] = p.info.authority.split(";");
8170                    p.info.authority = null;
8171                    for (int j = 0; j < names.length; j++) {
8172                        if (j == 1 && p.syncable) {
8173                            // We only want the first authority for a provider to possibly be
8174                            // syncable, so if we already added this provider using a different
8175                            // authority clear the syncable flag. We copy the provider before
8176                            // changing it because the mProviders object contains a reference
8177                            // to a provider that we don't want to change.
8178                            // Only do this for the second authority since the resulting provider
8179                            // object can be the same for all future authorities for this provider.
8180                            p = new PackageParser.Provider(p);
8181                            p.syncable = false;
8182                        }
8183                        if (!mProvidersByAuthority.containsKey(names[j])) {
8184                            mProvidersByAuthority.put(names[j], p);
8185                            if (p.info.authority == null) {
8186                                p.info.authority = names[j];
8187                            } else {
8188                                p.info.authority = p.info.authority + ";" + names[j];
8189                            }
8190                            if (DEBUG_PACKAGE_SCANNING) {
8191                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
8192                                    Log.d(TAG, "Registered content provider: " + names[j]
8193                                            + ", className = " + p.info.name + ", isSyncable = "
8194                                            + p.info.isSyncable);
8195                            }
8196                        } else {
8197                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
8198                            Slog.w(TAG, "Skipping provider name " + names[j] +
8199                                    " (in package " + pkg.applicationInfo.packageName +
8200                                    "): name already used by "
8201                                    + ((other != null && other.getComponentName() != null)
8202                                            ? other.getComponentName().getPackageName() : "?"));
8203                        }
8204                    }
8205                }
8206                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8207                    if (r == null) {
8208                        r = new StringBuilder(256);
8209                    } else {
8210                        r.append(' ');
8211                    }
8212                    r.append(p.info.name);
8213                }
8214            }
8215            if (r != null) {
8216                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
8217            }
8218
8219            N = pkg.services.size();
8220            r = null;
8221            for (i=0; i<N; i++) {
8222                PackageParser.Service s = pkg.services.get(i);
8223                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
8224                        s.info.processName, pkg.applicationInfo.uid);
8225                mServices.addService(s);
8226                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8227                    if (r == null) {
8228                        r = new StringBuilder(256);
8229                    } else {
8230                        r.append(' ');
8231                    }
8232                    r.append(s.info.name);
8233                }
8234            }
8235            if (r != null) {
8236                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
8237            }
8238
8239            N = pkg.receivers.size();
8240            r = null;
8241            for (i=0; i<N; i++) {
8242                PackageParser.Activity a = pkg.receivers.get(i);
8243                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8244                        a.info.processName, pkg.applicationInfo.uid);
8245                mReceivers.addActivity(a, "receiver");
8246                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8247                    if (r == null) {
8248                        r = new StringBuilder(256);
8249                    } else {
8250                        r.append(' ');
8251                    }
8252                    r.append(a.info.name);
8253                }
8254            }
8255            if (r != null) {
8256                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
8257            }
8258
8259            N = pkg.activities.size();
8260            r = null;
8261            for (i=0; i<N; i++) {
8262                PackageParser.Activity a = pkg.activities.get(i);
8263                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
8264                        a.info.processName, pkg.applicationInfo.uid);
8265                mActivities.addActivity(a, "activity");
8266                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8267                    if (r == null) {
8268                        r = new StringBuilder(256);
8269                    } else {
8270                        r.append(' ');
8271                    }
8272                    r.append(a.info.name);
8273                }
8274            }
8275            if (r != null) {
8276                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
8277            }
8278
8279            N = pkg.permissionGroups.size();
8280            r = null;
8281            for (i=0; i<N; i++) {
8282                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
8283                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
8284                if (cur == null) {
8285                    mPermissionGroups.put(pg.info.name, pg);
8286                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8287                        if (r == null) {
8288                            r = new StringBuilder(256);
8289                        } else {
8290                            r.append(' ');
8291                        }
8292                        r.append(pg.info.name);
8293                    }
8294                } else {
8295                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
8296                            + pg.info.packageName + " ignored: original from "
8297                            + cur.info.packageName);
8298                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8299                        if (r == null) {
8300                            r = new StringBuilder(256);
8301                        } else {
8302                            r.append(' ');
8303                        }
8304                        r.append("DUP:");
8305                        r.append(pg.info.name);
8306                    }
8307                }
8308            }
8309            if (r != null) {
8310                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
8311            }
8312
8313            N = pkg.permissions.size();
8314            r = null;
8315            for (i=0; i<N; i++) {
8316                PackageParser.Permission p = pkg.permissions.get(i);
8317
8318                // Assume by default that we did not install this permission into the system.
8319                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
8320
8321                // Now that permission groups have a special meaning, we ignore permission
8322                // groups for legacy apps to prevent unexpected behavior. In particular,
8323                // permissions for one app being granted to someone just becase they happen
8324                // to be in a group defined by another app (before this had no implications).
8325                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
8326                    p.group = mPermissionGroups.get(p.info.group);
8327                    // Warn for a permission in an unknown group.
8328                    if (p.info.group != null && p.group == null) {
8329                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8330                                + p.info.packageName + " in an unknown group " + p.info.group);
8331                    }
8332                }
8333
8334                ArrayMap<String, BasePermission> permissionMap =
8335                        p.tree ? mSettings.mPermissionTrees
8336                                : mSettings.mPermissions;
8337                BasePermission bp = permissionMap.get(p.info.name);
8338
8339                // Allow system apps to redefine non-system permissions
8340                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
8341                    final boolean currentOwnerIsSystem = (bp.perm != null
8342                            && isSystemApp(bp.perm.owner));
8343                    if (isSystemApp(p.owner)) {
8344                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
8345                            // It's a built-in permission and no owner, take ownership now
8346                            bp.packageSetting = pkgSetting;
8347                            bp.perm = p;
8348                            bp.uid = pkg.applicationInfo.uid;
8349                            bp.sourcePackage = p.info.packageName;
8350                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8351                        } else if (!currentOwnerIsSystem) {
8352                            String msg = "New decl " + p.owner + " of permission  "
8353                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
8354                            reportSettingsProblem(Log.WARN, msg);
8355                            bp = null;
8356                        }
8357                    }
8358                }
8359
8360                if (bp == null) {
8361                    bp = new BasePermission(p.info.name, p.info.packageName,
8362                            BasePermission.TYPE_NORMAL);
8363                    permissionMap.put(p.info.name, bp);
8364                }
8365
8366                if (bp.perm == null) {
8367                    if (bp.sourcePackage == null
8368                            || bp.sourcePackage.equals(p.info.packageName)) {
8369                        BasePermission tree = findPermissionTreeLP(p.info.name);
8370                        if (tree == null
8371                                || tree.sourcePackage.equals(p.info.packageName)) {
8372                            bp.packageSetting = pkgSetting;
8373                            bp.perm = p;
8374                            bp.uid = pkg.applicationInfo.uid;
8375                            bp.sourcePackage = p.info.packageName;
8376                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
8377                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8378                                if (r == null) {
8379                                    r = new StringBuilder(256);
8380                                } else {
8381                                    r.append(' ');
8382                                }
8383                                r.append(p.info.name);
8384                            }
8385                        } else {
8386                            Slog.w(TAG, "Permission " + p.info.name + " from package "
8387                                    + p.info.packageName + " ignored: base tree "
8388                                    + tree.name + " is from package "
8389                                    + tree.sourcePackage);
8390                        }
8391                    } else {
8392                        Slog.w(TAG, "Permission " + p.info.name + " from package "
8393                                + p.info.packageName + " ignored: original from "
8394                                + bp.sourcePackage);
8395                    }
8396                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8397                    if (r == null) {
8398                        r = new StringBuilder(256);
8399                    } else {
8400                        r.append(' ');
8401                    }
8402                    r.append("DUP:");
8403                    r.append(p.info.name);
8404                }
8405                if (bp.perm == p) {
8406                    bp.protectionLevel = p.info.protectionLevel;
8407                }
8408            }
8409
8410            if (r != null) {
8411                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
8412            }
8413
8414            N = pkg.instrumentation.size();
8415            r = null;
8416            for (i=0; i<N; i++) {
8417                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
8418                a.info.packageName = pkg.applicationInfo.packageName;
8419                a.info.sourceDir = pkg.applicationInfo.sourceDir;
8420                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
8421                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
8422                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
8423                a.info.dataDir = pkg.applicationInfo.dataDir;
8424                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
8425                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
8426
8427                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
8428                // need other information about the application, like the ABI and what not ?
8429                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
8430                mInstrumentation.put(a.getComponentName(), a);
8431                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
8432                    if (r == null) {
8433                        r = new StringBuilder(256);
8434                    } else {
8435                        r.append(' ');
8436                    }
8437                    r.append(a.info.name);
8438                }
8439            }
8440            if (r != null) {
8441                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
8442            }
8443
8444            if (pkg.protectedBroadcasts != null) {
8445                N = pkg.protectedBroadcasts.size();
8446                for (i=0; i<N; i++) {
8447                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
8448                }
8449            }
8450
8451            pkgSetting.setTimeStamp(scanFileTime);
8452
8453            // Create idmap files for pairs of (packages, overlay packages).
8454            // Note: "android", ie framework-res.apk, is handled by native layers.
8455            if (pkg.mOverlayTarget != null) {
8456                // This is an overlay package.
8457                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
8458                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
8459                        mOverlays.put(pkg.mOverlayTarget,
8460                                new ArrayMap<String, PackageParser.Package>());
8461                    }
8462                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
8463                    map.put(pkg.packageName, pkg);
8464                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
8465                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
8466                        createIdmapFailed = true;
8467                    }
8468                }
8469            } else if (mOverlays.containsKey(pkg.packageName) &&
8470                    !pkg.packageName.equals("android")) {
8471                // This is a regular package, with one or more known overlay packages.
8472                createIdmapsForPackageLI(pkg);
8473            }
8474        }
8475
8476        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8477
8478        if (createIdmapFailed) {
8479            throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
8480                    "scanPackageLI failed to createIdmap");
8481        }
8482        return pkg;
8483    }
8484
8485    /**
8486     * Derive the ABI of a non-system package located at {@code scanFile}. This information
8487     * is derived purely on the basis of the contents of {@code scanFile} and
8488     * {@code cpuAbiOverride}.
8489     *
8490     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
8491     */
8492    private void derivePackageAbi(PackageParser.Package pkg, File scanFile,
8493                                 String cpuAbiOverride, boolean extractLibs)
8494            throws PackageManagerException {
8495        // TODO: We can probably be smarter about this stuff. For installed apps,
8496        // we can calculate this information at install time once and for all. For
8497        // system apps, we can probably assume that this information doesn't change
8498        // after the first boot scan. As things stand, we do lots of unnecessary work.
8499
8500        // Give ourselves some initial paths; we'll come back for another
8501        // pass once we've determined ABI below.
8502        setNativeLibraryPaths(pkg);
8503
8504        // We would never need to extract libs for forward-locked and external packages,
8505        // since the container service will do it for us. We shouldn't attempt to
8506        // extract libs from system app when it was not updated.
8507        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
8508                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
8509            extractLibs = false;
8510        }
8511
8512        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
8513        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
8514
8515        NativeLibraryHelper.Handle handle = null;
8516        try {
8517            handle = NativeLibraryHelper.Handle.create(pkg);
8518            // TODO(multiArch): This can be null for apps that didn't go through the
8519            // usual installation process. We can calculate it again, like we
8520            // do during install time.
8521            //
8522            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
8523            // unnecessary.
8524            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
8525
8526            // Null out the abis so that they can be recalculated.
8527            pkg.applicationInfo.primaryCpuAbi = null;
8528            pkg.applicationInfo.secondaryCpuAbi = null;
8529            if (isMultiArch(pkg.applicationInfo)) {
8530                // Warn if we've set an abiOverride for multi-lib packages..
8531                // By definition, we need to copy both 32 and 64 bit libraries for
8532                // such packages.
8533                if (pkg.cpuAbiOverride != null
8534                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
8535                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
8536                }
8537
8538                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
8539                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
8540                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
8541                    if (extractLibs) {
8542                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8543                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
8544                                useIsaSpecificSubdirs);
8545                    } else {
8546                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
8547                    }
8548                }
8549
8550                maybeThrowExceptionForMultiArchCopy(
8551                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
8552
8553                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
8554                    if (extractLibs) {
8555                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8556                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
8557                                useIsaSpecificSubdirs);
8558                    } else {
8559                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
8560                    }
8561                }
8562
8563                maybeThrowExceptionForMultiArchCopy(
8564                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
8565
8566                if (abi64 >= 0) {
8567                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
8568                }
8569
8570                if (abi32 >= 0) {
8571                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
8572                    if (abi64 >= 0) {
8573                        if (cpuAbiOverride == null && pkg.use32bitAbi) {
8574                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
8575                            pkg.applicationInfo.primaryCpuAbi = abi;
8576                        } else {
8577                            pkg.applicationInfo.secondaryCpuAbi = abi;
8578                        }
8579                    } else {
8580                        pkg.applicationInfo.primaryCpuAbi = abi;
8581                    }
8582                }
8583
8584            } else {
8585                String[] abiList = (cpuAbiOverride != null) ?
8586                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
8587
8588                // Enable gross and lame hacks for apps that are built with old
8589                // SDK tools. We must scan their APKs for renderscript bitcode and
8590                // not launch them if it's present. Don't bother checking on devices
8591                // that don't have 64 bit support.
8592                boolean needsRenderScriptOverride = false;
8593                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
8594                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
8595                    abiList = Build.SUPPORTED_32_BIT_ABIS;
8596                    needsRenderScriptOverride = true;
8597                }
8598
8599                final int copyRet;
8600                if (extractLibs) {
8601                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
8602                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
8603                } else {
8604                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
8605                }
8606
8607                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
8608                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
8609                            "Error unpackaging native libs for app, errorCode=" + copyRet);
8610                }
8611
8612                if (copyRet >= 0) {
8613                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
8614                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
8615                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
8616                } else if (needsRenderScriptOverride) {
8617                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
8618                }
8619            }
8620        } catch (IOException ioe) {
8621            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
8622        } finally {
8623            IoUtils.closeQuietly(handle);
8624        }
8625
8626        // Now that we've calculated the ABIs and determined if it's an internal app,
8627        // we will go ahead and populate the nativeLibraryPath.
8628        setNativeLibraryPaths(pkg);
8629    }
8630
8631    /**
8632     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
8633     * i.e, so that all packages can be run inside a single process if required.
8634     *
8635     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
8636     * this function will either try and make the ABI for all packages in {@code packagesForUser}
8637     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
8638     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
8639     * updating a package that belongs to a shared user.
8640     *
8641     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
8642     * adds unnecessary complexity.
8643     */
8644    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
8645            PackageParser.Package scannedPackage, boolean bootComplete) {
8646        String requiredInstructionSet = null;
8647        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
8648            requiredInstructionSet = VMRuntime.getInstructionSet(
8649                     scannedPackage.applicationInfo.primaryCpuAbi);
8650        }
8651
8652        PackageSetting requirer = null;
8653        for (PackageSetting ps : packagesForUser) {
8654            // If packagesForUser contains scannedPackage, we skip it. This will happen
8655            // when scannedPackage is an update of an existing package. Without this check,
8656            // we will never be able to change the ABI of any package belonging to a shared
8657            // user, even if it's compatible with other packages.
8658            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8659                if (ps.primaryCpuAbiString == null) {
8660                    continue;
8661                }
8662
8663                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
8664                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
8665                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
8666                    // this but there's not much we can do.
8667                    String errorMessage = "Instruction set mismatch, "
8668                            + ((requirer == null) ? "[caller]" : requirer)
8669                            + " requires " + requiredInstructionSet + " whereas " + ps
8670                            + " requires " + instructionSet;
8671                    Slog.w(TAG, errorMessage);
8672                }
8673
8674                if (requiredInstructionSet == null) {
8675                    requiredInstructionSet = instructionSet;
8676                    requirer = ps;
8677                }
8678            }
8679        }
8680
8681        if (requiredInstructionSet != null) {
8682            String adjustedAbi;
8683            if (requirer != null) {
8684                // requirer != null implies that either scannedPackage was null or that scannedPackage
8685                // did not require an ABI, in which case we have to adjust scannedPackage to match
8686                // the ABI of the set (which is the same as requirer's ABI)
8687                adjustedAbi = requirer.primaryCpuAbiString;
8688                if (scannedPackage != null) {
8689                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
8690                }
8691            } else {
8692                // requirer == null implies that we're updating all ABIs in the set to
8693                // match scannedPackage.
8694                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
8695            }
8696
8697            for (PackageSetting ps : packagesForUser) {
8698                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
8699                    if (ps.primaryCpuAbiString != null) {
8700                        continue;
8701                    }
8702
8703                    ps.primaryCpuAbiString = adjustedAbi;
8704                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
8705                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
8706                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
8707                        Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
8708                                + " (requirer="
8709                                + (requirer == null ? "null" : requirer.pkg.packageName)
8710                                + ", scannedPackage="
8711                                + (scannedPackage != null ? scannedPackage.packageName : "null")
8712                                + ")");
8713                        try {
8714                            mInstaller.rmdex(ps.codePathString,
8715                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
8716                        } catch (InstallerException ignored) {
8717                        }
8718                    }
8719                }
8720            }
8721        }
8722    }
8723
8724    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
8725        synchronized (mPackages) {
8726            mResolverReplaced = true;
8727            // Set up information for custom user intent resolution activity.
8728            mResolveActivity.applicationInfo = pkg.applicationInfo;
8729            mResolveActivity.name = mCustomResolverComponentName.getClassName();
8730            mResolveActivity.packageName = pkg.applicationInfo.packageName;
8731            mResolveActivity.processName = pkg.applicationInfo.packageName;
8732            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8733            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8734                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8735            mResolveActivity.theme = 0;
8736            mResolveActivity.exported = true;
8737            mResolveActivity.enabled = true;
8738            mResolveInfo.activityInfo = mResolveActivity;
8739            mResolveInfo.priority = 0;
8740            mResolveInfo.preferredOrder = 0;
8741            mResolveInfo.match = 0;
8742            mResolveComponentName = mCustomResolverComponentName;
8743            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
8744                    mResolveComponentName);
8745        }
8746    }
8747
8748    private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) {
8749        final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName());
8750
8751        // Set up information for ephemeral installer activity
8752        mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo;
8753        mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName();
8754        mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName;
8755        mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName;
8756        mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
8757        mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
8758                ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
8759        mEphemeralInstallerActivity.theme = 0;
8760        mEphemeralInstallerActivity.exported = true;
8761        mEphemeralInstallerActivity.enabled = true;
8762        mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity;
8763        mEphemeralInstallerInfo.priority = 0;
8764        mEphemeralInstallerInfo.preferredOrder = 0;
8765        mEphemeralInstallerInfo.match = 0;
8766
8767        if (DEBUG_EPHEMERAL) {
8768            Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent);
8769        }
8770    }
8771
8772    private static String calculateBundledApkRoot(final String codePathString) {
8773        final File codePath = new File(codePathString);
8774        final File codeRoot;
8775        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
8776            codeRoot = Environment.getRootDirectory();
8777        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
8778            codeRoot = Environment.getOemDirectory();
8779        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
8780            codeRoot = Environment.getVendorDirectory();
8781        } else {
8782            // Unrecognized code path; take its top real segment as the apk root:
8783            // e.g. /something/app/blah.apk => /something
8784            try {
8785                File f = codePath.getCanonicalFile();
8786                File parent = f.getParentFile();    // non-null because codePath is a file
8787                File tmp;
8788                while ((tmp = parent.getParentFile()) != null) {
8789                    f = parent;
8790                    parent = tmp;
8791                }
8792                codeRoot = f;
8793                Slog.w(TAG, "Unrecognized code path "
8794                        + codePath + " - using " + codeRoot);
8795            } catch (IOException e) {
8796                // Can't canonicalize the code path -- shenanigans?
8797                Slog.w(TAG, "Can't canonicalize code path " + codePath);
8798                return Environment.getRootDirectory().getPath();
8799            }
8800        }
8801        return codeRoot.getPath();
8802    }
8803
8804    /**
8805     * Derive and set the location of native libraries for the given package,
8806     * which varies depending on where and how the package was installed.
8807     */
8808    private void setNativeLibraryPaths(PackageParser.Package pkg) {
8809        final ApplicationInfo info = pkg.applicationInfo;
8810        final String codePath = pkg.codePath;
8811        final File codeFile = new File(codePath);
8812        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
8813        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
8814
8815        info.nativeLibraryRootDir = null;
8816        info.nativeLibraryRootRequiresIsa = false;
8817        info.nativeLibraryDir = null;
8818        info.secondaryNativeLibraryDir = null;
8819
8820        if (isApkFile(codeFile)) {
8821            // Monolithic install
8822            if (bundledApp) {
8823                // If "/system/lib64/apkname" exists, assume that is the per-package
8824                // native library directory to use; otherwise use "/system/lib/apkname".
8825                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
8826                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
8827                        getPrimaryInstructionSet(info));
8828
8829                // This is a bundled system app so choose the path based on the ABI.
8830                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
8831                // is just the default path.
8832                final String apkName = deriveCodePathName(codePath);
8833                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
8834                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
8835                        apkName).getAbsolutePath();
8836
8837                if (info.secondaryCpuAbi != null) {
8838                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
8839                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
8840                            secondaryLibDir, apkName).getAbsolutePath();
8841                }
8842            } else if (asecApp) {
8843                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
8844                        .getAbsolutePath();
8845            } else {
8846                final String apkName = deriveCodePathName(codePath);
8847                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
8848                        .getAbsolutePath();
8849            }
8850
8851            info.nativeLibraryRootRequiresIsa = false;
8852            info.nativeLibraryDir = info.nativeLibraryRootDir;
8853        } else {
8854            // Cluster install
8855            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
8856            info.nativeLibraryRootRequiresIsa = true;
8857
8858            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
8859                    getPrimaryInstructionSet(info)).getAbsolutePath();
8860
8861            if (info.secondaryCpuAbi != null) {
8862                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
8863                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
8864            }
8865        }
8866    }
8867
8868    /**
8869     * Calculate the abis and roots for a bundled app. These can uniquely
8870     * be determined from the contents of the system partition, i.e whether
8871     * it contains 64 or 32 bit shared libraries etc. We do not validate any
8872     * of this information, and instead assume that the system was built
8873     * sensibly.
8874     */
8875    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
8876                                           PackageSetting pkgSetting) {
8877        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
8878
8879        // If "/system/lib64/apkname" exists, assume that is the per-package
8880        // native library directory to use; otherwise use "/system/lib/apkname".
8881        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
8882        setBundledAppAbi(pkg, apkRoot, apkName);
8883        // pkgSetting might be null during rescan following uninstall of updates
8884        // to a bundled app, so accommodate that possibility.  The settings in
8885        // that case will be established later from the parsed package.
8886        //
8887        // If the settings aren't null, sync them up with what we've just derived.
8888        // note that apkRoot isn't stored in the package settings.
8889        if (pkgSetting != null) {
8890            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
8891            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
8892        }
8893    }
8894
8895    /**
8896     * Deduces the ABI of a bundled app and sets the relevant fields on the
8897     * parsed pkg object.
8898     *
8899     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
8900     *        under which system libraries are installed.
8901     * @param apkName the name of the installed package.
8902     */
8903    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
8904        final File codeFile = new File(pkg.codePath);
8905
8906        final boolean has64BitLibs;
8907        final boolean has32BitLibs;
8908        if (isApkFile(codeFile)) {
8909            // Monolithic install
8910            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
8911            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
8912        } else {
8913            // Cluster install
8914            final File rootDir = new File(codeFile, LIB_DIR_NAME);
8915            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
8916                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
8917                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
8918                has64BitLibs = (new File(rootDir, isa)).exists();
8919            } else {
8920                has64BitLibs = false;
8921            }
8922            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
8923                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
8924                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
8925                has32BitLibs = (new File(rootDir, isa)).exists();
8926            } else {
8927                has32BitLibs = false;
8928            }
8929        }
8930
8931        if (has64BitLibs && !has32BitLibs) {
8932            // The package has 64 bit libs, but not 32 bit libs. Its primary
8933            // ABI should be 64 bit. We can safely assume here that the bundled
8934            // native libraries correspond to the most preferred ABI in the list.
8935
8936            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8937            pkg.applicationInfo.secondaryCpuAbi = null;
8938        } else if (has32BitLibs && !has64BitLibs) {
8939            // The package has 32 bit libs but not 64 bit libs. Its primary
8940            // ABI should be 32 bit.
8941
8942            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8943            pkg.applicationInfo.secondaryCpuAbi = null;
8944        } else if (has32BitLibs && has64BitLibs) {
8945            // The application has both 64 and 32 bit bundled libraries. We check
8946            // here that the app declares multiArch support, and warn if it doesn't.
8947            //
8948            // We will be lenient here and record both ABIs. The primary will be the
8949            // ABI that's higher on the list, i.e, a device that's configured to prefer
8950            // 64 bit apps will see a 64 bit primary ABI,
8951
8952            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
8953                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
8954            }
8955
8956            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
8957                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8958                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8959            } else {
8960                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
8961                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
8962            }
8963        } else {
8964            pkg.applicationInfo.primaryCpuAbi = null;
8965            pkg.applicationInfo.secondaryCpuAbi = null;
8966        }
8967    }
8968
8969    private void killPackage(PackageParser.Package pkg, String reason) {
8970        // Kill the parent package
8971        killApplication(pkg.packageName, pkg.applicationInfo.uid, reason);
8972        // Kill the child packages
8973        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8974        for (int i = 0; i < childCount; i++) {
8975            PackageParser.Package childPkg = pkg.childPackages.get(i);
8976            killApplication(childPkg.packageName, childPkg.applicationInfo.uid, reason);
8977        }
8978    }
8979
8980    private void killApplication(String pkgName, int appId, String reason) {
8981        // Request the ActivityManager to kill the process(only for existing packages)
8982        // so that we do not end up in a confused state while the user is still using the older
8983        // version of the application while the new one gets installed.
8984        IActivityManager am = ActivityManagerNative.getDefault();
8985        if (am != null) {
8986            try {
8987                am.killApplicationWithAppId(pkgName, appId, reason);
8988            } catch (RemoteException e) {
8989            }
8990        }
8991    }
8992
8993    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
8994        // Remove the parent package setting
8995        PackageSetting ps = (PackageSetting) pkg.mExtras;
8996        if (ps != null) {
8997            removePackageLI(ps, chatty);
8998        }
8999        // Remove the child package setting
9000        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9001        for (int i = 0; i < childCount; i++) {
9002            PackageParser.Package childPkg = pkg.childPackages.get(i);
9003            ps = (PackageSetting) childPkg.mExtras;
9004            if (ps != null) {
9005                removePackageLI(ps, chatty);
9006            }
9007        }
9008    }
9009
9010    void removePackageLI(PackageSetting ps, boolean chatty) {
9011        if (DEBUG_INSTALL) {
9012            if (chatty)
9013                Log.d(TAG, "Removing package " + ps.name);
9014        }
9015
9016        // writer
9017        synchronized (mPackages) {
9018            mPackages.remove(ps.name);
9019            final PackageParser.Package pkg = ps.pkg;
9020            if (pkg != null) {
9021                cleanPackageDataStructuresLILPw(pkg, chatty);
9022            }
9023        }
9024    }
9025
9026    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
9027        if (DEBUG_INSTALL) {
9028            if (chatty)
9029                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
9030        }
9031
9032        // writer
9033        synchronized (mPackages) {
9034            // Remove the parent package
9035            mPackages.remove(pkg.applicationInfo.packageName);
9036            cleanPackageDataStructuresLILPw(pkg, chatty);
9037
9038            // Remove the child packages
9039            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9040            for (int i = 0; i < childCount; i++) {
9041                PackageParser.Package childPkg = pkg.childPackages.get(i);
9042                mPackages.remove(childPkg.applicationInfo.packageName);
9043                cleanPackageDataStructuresLILPw(childPkg, chatty);
9044            }
9045        }
9046    }
9047
9048    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
9049        int N = pkg.providers.size();
9050        StringBuilder r = null;
9051        int i;
9052        for (i=0; i<N; i++) {
9053            PackageParser.Provider p = pkg.providers.get(i);
9054            mProviders.removeProvider(p);
9055            if (p.info.authority == null) {
9056
9057                /* There was another ContentProvider with this authority when
9058                 * this app was installed so this authority is null,
9059                 * Ignore it as we don't have to unregister the provider.
9060                 */
9061                continue;
9062            }
9063            String names[] = p.info.authority.split(";");
9064            for (int j = 0; j < names.length; j++) {
9065                if (mProvidersByAuthority.get(names[j]) == p) {
9066                    mProvidersByAuthority.remove(names[j]);
9067                    if (DEBUG_REMOVE) {
9068                        if (chatty)
9069                            Log.d(TAG, "Unregistered content provider: " + names[j]
9070                                    + ", className = " + p.info.name + ", isSyncable = "
9071                                    + p.info.isSyncable);
9072                    }
9073                }
9074            }
9075            if (DEBUG_REMOVE && chatty) {
9076                if (r == null) {
9077                    r = new StringBuilder(256);
9078                } else {
9079                    r.append(' ');
9080                }
9081                r.append(p.info.name);
9082            }
9083        }
9084        if (r != null) {
9085            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
9086        }
9087
9088        N = pkg.services.size();
9089        r = null;
9090        for (i=0; i<N; i++) {
9091            PackageParser.Service s = pkg.services.get(i);
9092            mServices.removeService(s);
9093            if (chatty) {
9094                if (r == null) {
9095                    r = new StringBuilder(256);
9096                } else {
9097                    r.append(' ');
9098                }
9099                r.append(s.info.name);
9100            }
9101        }
9102        if (r != null) {
9103            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
9104        }
9105
9106        N = pkg.receivers.size();
9107        r = null;
9108        for (i=0; i<N; i++) {
9109            PackageParser.Activity a = pkg.receivers.get(i);
9110            mReceivers.removeActivity(a, "receiver");
9111            if (DEBUG_REMOVE && chatty) {
9112                if (r == null) {
9113                    r = new StringBuilder(256);
9114                } else {
9115                    r.append(' ');
9116                }
9117                r.append(a.info.name);
9118            }
9119        }
9120        if (r != null) {
9121            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
9122        }
9123
9124        N = pkg.activities.size();
9125        r = null;
9126        for (i=0; i<N; i++) {
9127            PackageParser.Activity a = pkg.activities.get(i);
9128            mActivities.removeActivity(a, "activity");
9129            if (DEBUG_REMOVE && chatty) {
9130                if (r == null) {
9131                    r = new StringBuilder(256);
9132                } else {
9133                    r.append(' ');
9134                }
9135                r.append(a.info.name);
9136            }
9137        }
9138        if (r != null) {
9139            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
9140        }
9141
9142        N = pkg.permissions.size();
9143        r = null;
9144        for (i=0; i<N; i++) {
9145            PackageParser.Permission p = pkg.permissions.get(i);
9146            BasePermission bp = mSettings.mPermissions.get(p.info.name);
9147            if (bp == null) {
9148                bp = mSettings.mPermissionTrees.get(p.info.name);
9149            }
9150            if (bp != null && bp.perm == p) {
9151                bp.perm = null;
9152                if (DEBUG_REMOVE && chatty) {
9153                    if (r == null) {
9154                        r = new StringBuilder(256);
9155                    } else {
9156                        r.append(' ');
9157                    }
9158                    r.append(p.info.name);
9159                }
9160            }
9161            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9162                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
9163                if (appOpPkgs != null) {
9164                    appOpPkgs.remove(pkg.packageName);
9165                }
9166            }
9167        }
9168        if (r != null) {
9169            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9170        }
9171
9172        N = pkg.requestedPermissions.size();
9173        r = null;
9174        for (i=0; i<N; i++) {
9175            String perm = pkg.requestedPermissions.get(i);
9176            BasePermission bp = mSettings.mPermissions.get(perm);
9177            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9178                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
9179                if (appOpPkgs != null) {
9180                    appOpPkgs.remove(pkg.packageName);
9181                    if (appOpPkgs.isEmpty()) {
9182                        mAppOpPermissionPackages.remove(perm);
9183                    }
9184                }
9185            }
9186        }
9187        if (r != null) {
9188            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
9189        }
9190
9191        N = pkg.instrumentation.size();
9192        r = null;
9193        for (i=0; i<N; i++) {
9194            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
9195            mInstrumentation.remove(a.getComponentName());
9196            if (DEBUG_REMOVE && chatty) {
9197                if (r == null) {
9198                    r = new StringBuilder(256);
9199                } else {
9200                    r.append(' ');
9201                }
9202                r.append(a.info.name);
9203            }
9204        }
9205        if (r != null) {
9206            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
9207        }
9208
9209        r = null;
9210        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
9211            // Only system apps can hold shared libraries.
9212            if (pkg.libraryNames != null) {
9213                for (i=0; i<pkg.libraryNames.size(); i++) {
9214                    String name = pkg.libraryNames.get(i);
9215                    SharedLibraryEntry cur = mSharedLibraries.get(name);
9216                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
9217                        mSharedLibraries.remove(name);
9218                        if (DEBUG_REMOVE && chatty) {
9219                            if (r == null) {
9220                                r = new StringBuilder(256);
9221                            } else {
9222                                r.append(' ');
9223                            }
9224                            r.append(name);
9225                        }
9226                    }
9227                }
9228            }
9229        }
9230        if (r != null) {
9231            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
9232        }
9233    }
9234
9235    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
9236        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
9237            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
9238                return true;
9239            }
9240        }
9241        return false;
9242    }
9243
9244    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
9245    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
9246    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
9247
9248    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
9249        // Update the parent permissions
9250        updatePermissionsLPw(pkg.packageName, pkg, flags);
9251        // Update the child permissions
9252        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9253        for (int i = 0; i < childCount; i++) {
9254            PackageParser.Package childPkg = pkg.childPackages.get(i);
9255            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
9256        }
9257    }
9258
9259    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
9260            int flags) {
9261        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
9262        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
9263    }
9264
9265    private void updatePermissionsLPw(String changingPkg,
9266            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
9267        // Make sure there are no dangling permission trees.
9268        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
9269        while (it.hasNext()) {
9270            final BasePermission bp = it.next();
9271            if (bp.packageSetting == null) {
9272                // We may not yet have parsed the package, so just see if
9273                // we still know about its settings.
9274                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9275            }
9276            if (bp.packageSetting == null) {
9277                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
9278                        + " from package " + bp.sourcePackage);
9279                it.remove();
9280            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9281                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9282                    Slog.i(TAG, "Removing old permission tree: " + bp.name
9283                            + " from package " + bp.sourcePackage);
9284                    flags |= UPDATE_PERMISSIONS_ALL;
9285                    it.remove();
9286                }
9287            }
9288        }
9289
9290        // Make sure all dynamic permissions have been assigned to a package,
9291        // and make sure there are no dangling permissions.
9292        it = mSettings.mPermissions.values().iterator();
9293        while (it.hasNext()) {
9294            final BasePermission bp = it.next();
9295            if (bp.type == BasePermission.TYPE_DYNAMIC) {
9296                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
9297                        + bp.name + " pkg=" + bp.sourcePackage
9298                        + " info=" + bp.pendingInfo);
9299                if (bp.packageSetting == null && bp.pendingInfo != null) {
9300                    final BasePermission tree = findPermissionTreeLP(bp.name);
9301                    if (tree != null && tree.perm != null) {
9302                        bp.packageSetting = tree.packageSetting;
9303                        bp.perm = new PackageParser.Permission(tree.perm.owner,
9304                                new PermissionInfo(bp.pendingInfo));
9305                        bp.perm.info.packageName = tree.perm.info.packageName;
9306                        bp.perm.info.name = bp.name;
9307                        bp.uid = tree.uid;
9308                    }
9309                }
9310            }
9311            if (bp.packageSetting == null) {
9312                // We may not yet have parsed the package, so just see if
9313                // we still know about its settings.
9314                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
9315            }
9316            if (bp.packageSetting == null) {
9317                Slog.w(TAG, "Removing dangling permission: " + bp.name
9318                        + " from package " + bp.sourcePackage);
9319                it.remove();
9320            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
9321                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
9322                    Slog.i(TAG, "Removing old permission: " + bp.name
9323                            + " from package " + bp.sourcePackage);
9324                    flags |= UPDATE_PERMISSIONS_ALL;
9325                    it.remove();
9326                }
9327            }
9328        }
9329
9330        // Now update the permissions for all packages, in particular
9331        // replace the granted permissions of the system packages.
9332        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
9333            for (PackageParser.Package pkg : mPackages.values()) {
9334                if (pkg != pkgInfo) {
9335                    // Only replace for packages on requested volume
9336                    final String volumeUuid = getVolumeUuidForPackage(pkg);
9337                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
9338                            && Objects.equals(replaceVolumeUuid, volumeUuid);
9339                    grantPermissionsLPw(pkg, replace, changingPkg);
9340                }
9341            }
9342        }
9343
9344        if (pkgInfo != null) {
9345            // Only replace for packages on requested volume
9346            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
9347            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
9348                    && Objects.equals(replaceVolumeUuid, volumeUuid);
9349            grantPermissionsLPw(pkgInfo, replace, changingPkg);
9350        }
9351    }
9352
9353    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
9354            String packageOfInterest) {
9355        // IMPORTANT: There are two types of permissions: install and runtime.
9356        // Install time permissions are granted when the app is installed to
9357        // all device users and users added in the future. Runtime permissions
9358        // are granted at runtime explicitly to specific users. Normal and signature
9359        // protected permissions are install time permissions. Dangerous permissions
9360        // are install permissions if the app's target SDK is Lollipop MR1 or older,
9361        // otherwise they are runtime permissions. This function does not manage
9362        // runtime permissions except for the case an app targeting Lollipop MR1
9363        // being upgraded to target a newer SDK, in which case dangerous permissions
9364        // are transformed from install time to runtime ones.
9365
9366        final PackageSetting ps = (PackageSetting) pkg.mExtras;
9367        if (ps == null) {
9368            return;
9369        }
9370
9371        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
9372
9373        PermissionsState permissionsState = ps.getPermissionsState();
9374        PermissionsState origPermissions = permissionsState;
9375
9376        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
9377
9378        boolean runtimePermissionsRevoked = false;
9379        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
9380
9381        boolean changedInstallPermission = false;
9382
9383        if (replace) {
9384            ps.installPermissionsFixed = false;
9385            if (!ps.isSharedUser()) {
9386                origPermissions = new PermissionsState(permissionsState);
9387                permissionsState.reset();
9388            } else {
9389                // We need to know only about runtime permission changes since the
9390                // calling code always writes the install permissions state but
9391                // the runtime ones are written only if changed. The only cases of
9392                // changed runtime permissions here are promotion of an install to
9393                // runtime and revocation of a runtime from a shared user.
9394                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
9395                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
9396                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
9397                    runtimePermissionsRevoked = true;
9398                }
9399            }
9400        }
9401
9402        permissionsState.setGlobalGids(mGlobalGids);
9403
9404        final int N = pkg.requestedPermissions.size();
9405        for (int i=0; i<N; i++) {
9406            final String name = pkg.requestedPermissions.get(i);
9407            final BasePermission bp = mSettings.mPermissions.get(name);
9408
9409            if (DEBUG_INSTALL) {
9410                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
9411            }
9412
9413            if (bp == null || bp.packageSetting == null) {
9414                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9415                    Slog.w(TAG, "Unknown permission " + name
9416                            + " in package " + pkg.packageName);
9417                }
9418                continue;
9419            }
9420
9421            final String perm = bp.name;
9422            boolean allowedSig = false;
9423            int grant = GRANT_DENIED;
9424
9425            // Keep track of app op permissions.
9426            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
9427                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
9428                if (pkgs == null) {
9429                    pkgs = new ArraySet<>();
9430                    mAppOpPermissionPackages.put(bp.name, pkgs);
9431                }
9432                pkgs.add(pkg.packageName);
9433            }
9434
9435            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
9436            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
9437                    >= Build.VERSION_CODES.M;
9438            switch (level) {
9439                case PermissionInfo.PROTECTION_NORMAL: {
9440                    // For all apps normal permissions are install time ones.
9441                    grant = GRANT_INSTALL;
9442                } break;
9443
9444                case PermissionInfo.PROTECTION_DANGEROUS: {
9445                    // If a permission review is required for legacy apps we represent
9446                    // their permissions as always granted runtime ones since we need
9447                    // to keep the review required permission flag per user while an
9448                    // install permission's state is shared across all users.
9449                    if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) {
9450                        // For legacy apps dangerous permissions are install time ones.
9451                        grant = GRANT_INSTALL;
9452                    } else if (origPermissions.hasInstallPermission(bp.name)) {
9453                        // For legacy apps that became modern, install becomes runtime.
9454                        grant = GRANT_UPGRADE;
9455                    } else if (mPromoteSystemApps
9456                            && isSystemApp(ps)
9457                            && mExistingSystemPackages.contains(ps.name)) {
9458                        // For legacy system apps, install becomes runtime.
9459                        // We cannot check hasInstallPermission() for system apps since those
9460                        // permissions were granted implicitly and not persisted pre-M.
9461                        grant = GRANT_UPGRADE;
9462                    } else {
9463                        // For modern apps keep runtime permissions unchanged.
9464                        grant = GRANT_RUNTIME;
9465                    }
9466                } break;
9467
9468                case PermissionInfo.PROTECTION_SIGNATURE: {
9469                    // For all apps signature permissions are install time ones.
9470                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
9471                    if (allowedSig) {
9472                        grant = GRANT_INSTALL;
9473                    }
9474                } break;
9475            }
9476
9477            if (DEBUG_INSTALL) {
9478                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
9479            }
9480
9481            if (grant != GRANT_DENIED) {
9482                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
9483                    // If this is an existing, non-system package, then
9484                    // we can't add any new permissions to it.
9485                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
9486                        // Except...  if this is a permission that was added
9487                        // to the platform (note: need to only do this when
9488                        // updating the platform).
9489                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
9490                            grant = GRANT_DENIED;
9491                        }
9492                    }
9493                }
9494
9495                switch (grant) {
9496                    case GRANT_INSTALL: {
9497                        // Revoke this as runtime permission to handle the case of
9498                        // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps
9499                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9500                            if (origPermissions.getRuntimePermissionState(
9501                                    bp.name, userId) != null) {
9502                                // Revoke the runtime permission and clear the flags.
9503                                origPermissions.revokeRuntimePermission(bp, userId);
9504                                origPermissions.updatePermissionFlags(bp, userId,
9505                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
9506                                // If we revoked a permission permission, we have to write.
9507                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9508                                        changedRuntimePermissionUserIds, userId);
9509                            }
9510                        }
9511                        // Grant an install permission.
9512                        if (permissionsState.grantInstallPermission(bp) !=
9513                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
9514                            changedInstallPermission = true;
9515                        }
9516                    } break;
9517
9518                    case GRANT_RUNTIME: {
9519                        // Grant previously granted runtime permissions.
9520                        for (int userId : UserManagerService.getInstance().getUserIds()) {
9521                            PermissionState permissionState = origPermissions
9522                                    .getRuntimePermissionState(bp.name, userId);
9523                            int flags = permissionState != null
9524                                    ? permissionState.getFlags() : 0;
9525                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
9526                                if (permissionsState.grantRuntimePermission(bp, userId) ==
9527                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9528                                    // If we cannot put the permission as it was, we have to write.
9529                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9530                                            changedRuntimePermissionUserIds, userId);
9531                                }
9532                                // If the app supports runtime permissions no need for a review.
9533                                if (Build.PERMISSIONS_REVIEW_REQUIRED
9534                                        && appSupportsRuntimePermissions
9535                                        && (flags & PackageManager
9536                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
9537                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
9538                                    // Since we changed the flags, we have to write.
9539                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9540                                            changedRuntimePermissionUserIds, userId);
9541                                }
9542                            } else if (Build.PERMISSIONS_REVIEW_REQUIRED
9543                                    && !appSupportsRuntimePermissions) {
9544                                // For legacy apps that need a permission review, every new
9545                                // runtime permission is granted but it is pending a review.
9546                                if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
9547                                    permissionsState.grantRuntimePermission(bp, userId);
9548                                    flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
9549                                    // We changed the permission and flags, hence have to write.
9550                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9551                                            changedRuntimePermissionUserIds, userId);
9552                                }
9553                            }
9554                            // Propagate the permission flags.
9555                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
9556                        }
9557                    } break;
9558
9559                    case GRANT_UPGRADE: {
9560                        // Grant runtime permissions for a previously held install permission.
9561                        PermissionState permissionState = origPermissions
9562                                .getInstallPermissionState(bp.name);
9563                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
9564
9565                        if (origPermissions.revokeInstallPermission(bp)
9566                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
9567                            // We will be transferring the permission flags, so clear them.
9568                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
9569                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
9570                            changedInstallPermission = true;
9571                        }
9572
9573                        // If the permission is not to be promoted to runtime we ignore it and
9574                        // also its other flags as they are not applicable to install permissions.
9575                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
9576                            for (int userId : currentUserIds) {
9577                                if (permissionsState.grantRuntimePermission(bp, userId) !=
9578                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9579                                    // Transfer the permission flags.
9580                                    permissionsState.updatePermissionFlags(bp, userId,
9581                                            flags, flags);
9582                                    // If we granted the permission, we have to write.
9583                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
9584                                            changedRuntimePermissionUserIds, userId);
9585                                }
9586                            }
9587                        }
9588                    } break;
9589
9590                    default: {
9591                        if (packageOfInterest == null
9592                                || packageOfInterest.equals(pkg.packageName)) {
9593                            Slog.w(TAG, "Not granting permission " + perm
9594                                    + " to package " + pkg.packageName
9595                                    + " because it was previously installed without");
9596                        }
9597                    } break;
9598                }
9599            } else {
9600                if (permissionsState.revokeInstallPermission(bp) !=
9601                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
9602                    // Also drop the permission flags.
9603                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
9604                            PackageManager.MASK_PERMISSION_FLAGS, 0);
9605                    changedInstallPermission = true;
9606                    Slog.i(TAG, "Un-granting permission " + perm
9607                            + " from package " + pkg.packageName
9608                            + " (protectionLevel=" + bp.protectionLevel
9609                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9610                            + ")");
9611                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
9612                    // Don't print warning for app op permissions, since it is fine for them
9613                    // not to be granted, there is a UI for the user to decide.
9614                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
9615                        Slog.w(TAG, "Not granting permission " + perm
9616                                + " to package " + pkg.packageName
9617                                + " (protectionLevel=" + bp.protectionLevel
9618                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
9619                                + ")");
9620                    }
9621                }
9622            }
9623        }
9624
9625        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
9626                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
9627            // This is the first that we have heard about this package, so the
9628            // permissions we have now selected are fixed until explicitly
9629            // changed.
9630            ps.installPermissionsFixed = true;
9631        }
9632
9633        // Persist the runtime permissions state for users with changes. If permissions
9634        // were revoked because no app in the shared user declares them we have to
9635        // write synchronously to avoid losing runtime permissions state.
9636        for (int userId : changedRuntimePermissionUserIds) {
9637            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
9638        }
9639
9640        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9641    }
9642
9643    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
9644        boolean allowed = false;
9645        final int NP = PackageParser.NEW_PERMISSIONS.length;
9646        for (int ip=0; ip<NP; ip++) {
9647            final PackageParser.NewPermissionInfo npi
9648                    = PackageParser.NEW_PERMISSIONS[ip];
9649            if (npi.name.equals(perm)
9650                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
9651                allowed = true;
9652                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
9653                        + pkg.packageName);
9654                break;
9655            }
9656        }
9657        return allowed;
9658    }
9659
9660    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
9661            BasePermission bp, PermissionsState origPermissions) {
9662        boolean allowed;
9663        allowed = (compareSignatures(
9664                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
9665                        == PackageManager.SIGNATURE_MATCH)
9666                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
9667                        == PackageManager.SIGNATURE_MATCH);
9668        if (!allowed && (bp.protectionLevel
9669                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) {
9670            if (isSystemApp(pkg)) {
9671                // For updated system applications, a system permission
9672                // is granted only if it had been defined by the original application.
9673                if (pkg.isUpdatedSystemApp()) {
9674                    final PackageSetting sysPs = mSettings
9675                            .getDisabledSystemPkgLPr(pkg.packageName);
9676                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
9677                        // If the original was granted this permission, we take
9678                        // that grant decision as read and propagate it to the
9679                        // update.
9680                        if (sysPs.isPrivileged()) {
9681                            allowed = true;
9682                        }
9683                    } else {
9684                        // The system apk may have been updated with an older
9685                        // version of the one on the data partition, but which
9686                        // granted a new system permission that it didn't have
9687                        // before.  In this case we do want to allow the app to
9688                        // now get the new permission if the ancestral apk is
9689                        // privileged to get it.
9690                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
9691                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
9692                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
9693                                    allowed = true;
9694                                    break;
9695                                }
9696                            }
9697                        }
9698                        // Also if a privileged parent package on the system image or any of
9699                        // its children requested a privileged permission, the updated child
9700                        // packages can also get the permission.
9701                        if (pkg.parentPackage != null) {
9702                            final PackageSetting disabledSysParentPs = mSettings
9703                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
9704                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
9705                                    && disabledSysParentPs.isPrivileged()) {
9706                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
9707                                    allowed = true;
9708                                } else if (disabledSysParentPs.pkg.childPackages != null) {
9709                                    final int count = disabledSysParentPs.pkg.childPackages.size();
9710                                    for (int i = 0; i < count; i++) {
9711                                        PackageParser.Package disabledSysChildPkg =
9712                                                disabledSysParentPs.pkg.childPackages.get(i);
9713                                        if (isPackageRequestingPermission(disabledSysChildPkg,
9714                                                perm)) {
9715                                            allowed = true;
9716                                            break;
9717                                        }
9718                                    }
9719                                }
9720                            }
9721                        }
9722                    }
9723                } else {
9724                    allowed = isPrivilegedApp(pkg);
9725                }
9726            }
9727        }
9728        if (!allowed) {
9729            if (!allowed && (bp.protectionLevel
9730                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
9731                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
9732                // If this was a previously normal/dangerous permission that got moved
9733                // to a system permission as part of the runtime permission redesign, then
9734                // we still want to blindly grant it to old apps.
9735                allowed = true;
9736            }
9737            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
9738                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
9739                // If this permission is to be granted to the system installer and
9740                // this app is an installer, then it gets the permission.
9741                allowed = true;
9742            }
9743            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
9744                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
9745                // If this permission is to be granted to the system verifier and
9746                // this app is a verifier, then it gets the permission.
9747                allowed = true;
9748            }
9749            if (!allowed && (bp.protectionLevel
9750                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
9751                    && isSystemApp(pkg)) {
9752                // Any pre-installed system app is allowed to get this permission.
9753                allowed = true;
9754            }
9755            if (!allowed && (bp.protectionLevel
9756                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
9757                // For development permissions, a development permission
9758                // is granted only if it was already granted.
9759                allowed = origPermissions.hasInstallPermission(perm);
9760            }
9761            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
9762                    && pkg.packageName.equals(mSetupWizardPackage)) {
9763                // If this permission is to be granted to the system setup wizard and
9764                // this app is a setup wizard, then it gets the permission.
9765                allowed = true;
9766            }
9767        }
9768        return allowed;
9769    }
9770
9771    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
9772        final int permCount = pkg.requestedPermissions.size();
9773        for (int j = 0; j < permCount; j++) {
9774            String requestedPermission = pkg.requestedPermissions.get(j);
9775            if (permission.equals(requestedPermission)) {
9776                return true;
9777            }
9778        }
9779        return false;
9780    }
9781
9782    final class ActivityIntentResolver
9783            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
9784        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
9785                boolean defaultOnly, int userId) {
9786            if (!sUserManager.exists(userId)) return null;
9787            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
9788            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
9789        }
9790
9791        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
9792                int userId) {
9793            if (!sUserManager.exists(userId)) return null;
9794            mFlags = flags;
9795            return super.queryIntent(intent, resolvedType,
9796                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
9797        }
9798
9799        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
9800                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
9801            if (!sUserManager.exists(userId)) return null;
9802            if (packageActivities == null) {
9803                return null;
9804            }
9805            mFlags = flags;
9806            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
9807            final int N = packageActivities.size();
9808            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
9809                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
9810
9811            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
9812            for (int i = 0; i < N; ++i) {
9813                intentFilters = packageActivities.get(i).intents;
9814                if (intentFilters != null && intentFilters.size() > 0) {
9815                    PackageParser.ActivityIntentInfo[] array =
9816                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
9817                    intentFilters.toArray(array);
9818                    listCut.add(array);
9819                }
9820            }
9821            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
9822        }
9823
9824        /**
9825         * Finds a privileged activity that matches the specified activity names.
9826         */
9827        private PackageParser.Activity findMatchingActivity(
9828                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
9829            for (PackageParser.Activity sysActivity : activityList) {
9830                if (sysActivity.info.name.equals(activityInfo.name)) {
9831                    return sysActivity;
9832                }
9833                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
9834                    return sysActivity;
9835                }
9836                if (sysActivity.info.targetActivity != null) {
9837                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
9838                        return sysActivity;
9839                    }
9840                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
9841                        return sysActivity;
9842                    }
9843                }
9844            }
9845            return null;
9846        }
9847
9848        public class IterGenerator<E> {
9849            public Iterator<E> generate(ActivityIntentInfo info) {
9850                return null;
9851            }
9852        }
9853
9854        public class ActionIterGenerator extends IterGenerator<String> {
9855            @Override
9856            public Iterator<String> generate(ActivityIntentInfo info) {
9857                return info.actionsIterator();
9858            }
9859        }
9860
9861        public class CategoriesIterGenerator extends IterGenerator<String> {
9862            @Override
9863            public Iterator<String> generate(ActivityIntentInfo info) {
9864                return info.categoriesIterator();
9865            }
9866        }
9867
9868        public class SchemesIterGenerator extends IterGenerator<String> {
9869            @Override
9870            public Iterator<String> generate(ActivityIntentInfo info) {
9871                return info.schemesIterator();
9872            }
9873        }
9874
9875        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
9876            @Override
9877            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
9878                return info.authoritiesIterator();
9879            }
9880        }
9881
9882        /**
9883         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
9884         * MODIFIED. Do not pass in a list that should not be changed.
9885         */
9886        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
9887                IterGenerator<T> generator, Iterator<T> searchIterator) {
9888            // loop through the set of actions; every one must be found in the intent filter
9889            while (searchIterator.hasNext()) {
9890                // we must have at least one filter in the list to consider a match
9891                if (intentList.size() == 0) {
9892                    break;
9893                }
9894
9895                final T searchAction = searchIterator.next();
9896
9897                // loop through the set of intent filters
9898                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
9899                while (intentIter.hasNext()) {
9900                    final ActivityIntentInfo intentInfo = intentIter.next();
9901                    boolean selectionFound = false;
9902
9903                    // loop through the intent filter's selection criteria; at least one
9904                    // of them must match the searched criteria
9905                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
9906                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
9907                        final T intentSelection = intentSelectionIter.next();
9908                        if (intentSelection != null && intentSelection.equals(searchAction)) {
9909                            selectionFound = true;
9910                            break;
9911                        }
9912                    }
9913
9914                    // the selection criteria wasn't found in this filter's set; this filter
9915                    // is not a potential match
9916                    if (!selectionFound) {
9917                        intentIter.remove();
9918                    }
9919                }
9920            }
9921        }
9922
9923        private boolean isProtectedAction(ActivityIntentInfo filter) {
9924            final Iterator<String> actionsIter = filter.actionsIterator();
9925            while (actionsIter != null && actionsIter.hasNext()) {
9926                final String filterAction = actionsIter.next();
9927                if (PROTECTED_ACTIONS.contains(filterAction)) {
9928                    return true;
9929                }
9930            }
9931            return false;
9932        }
9933
9934        /**
9935         * Adjusts the priority of the given intent filter according to policy.
9936         * <p>
9937         * <ul>
9938         * <li>The priority for non privileged applications is capped to '0'</li>
9939         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
9940         * <li>The priority for unbundled updates to privileged applications is capped to the
9941         *      priority defined on the system partition</li>
9942         * </ul>
9943         * <p>
9944         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
9945         * allowed to obtain any priority on any action.
9946         */
9947        private void adjustPriority(
9948                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
9949            // nothing to do; priority is fine as-is
9950            if (intent.getPriority() <= 0) {
9951                return;
9952            }
9953
9954            final ActivityInfo activityInfo = intent.activity.info;
9955            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
9956
9957            final boolean privilegedApp =
9958                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
9959            if (!privilegedApp) {
9960                // non-privileged applications can never define a priority >0
9961                Slog.w(TAG, "Non-privileged app; cap priority to 0;"
9962                        + " package: " + applicationInfo.packageName
9963                        + " activity: " + intent.activity.className
9964                        + " origPrio: " + intent.getPriority());
9965                intent.setPriority(0);
9966                return;
9967            }
9968
9969            if (systemActivities == null) {
9970                // the system package is not disabled; we're parsing the system partition
9971                if (isProtectedAction(intent)) {
9972                    if (mDeferProtectedFilters) {
9973                        // We can't deal with these just yet. No component should ever obtain a
9974                        // >0 priority for a protected actions, with ONE exception -- the setup
9975                        // wizard. The setup wizard, however, cannot be known until we're able to
9976                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
9977                        // until all intent filters have been processed. Chicken, meet egg.
9978                        // Let the filter temporarily have a high priority and rectify the
9979                        // priorities after all system packages have been scanned.
9980                        mProtectedFilters.add(intent);
9981                        if (DEBUG_FILTERS) {
9982                            Slog.i(TAG, "Protected action; save for later;"
9983                                    + " package: " + applicationInfo.packageName
9984                                    + " activity: " + intent.activity.className
9985                                    + " origPrio: " + intent.getPriority());
9986                        }
9987                        return;
9988                    } else {
9989                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
9990                            Slog.i(TAG, "No setup wizard;"
9991                                + " All protected intents capped to priority 0");
9992                        }
9993                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
9994                            if (DEBUG_FILTERS) {
9995                                Slog.i(TAG, "Found setup wizard;"
9996                                    + " allow priority " + intent.getPriority() + ";"
9997                                    + " package: " + intent.activity.info.packageName
9998                                    + " activity: " + intent.activity.className
9999                                    + " priority: " + intent.getPriority());
10000                            }
10001                            // setup wizard gets whatever it wants
10002                            return;
10003                        }
10004                        Slog.w(TAG, "Protected action; cap priority to 0;"
10005                                + " package: " + intent.activity.info.packageName
10006                                + " activity: " + intent.activity.className
10007                                + " origPrio: " + intent.getPriority());
10008                        intent.setPriority(0);
10009                        return;
10010                    }
10011                }
10012                // privileged apps on the system image get whatever priority they request
10013                return;
10014            }
10015
10016            // privileged app unbundled update ... try to find the same activity
10017            final PackageParser.Activity foundActivity =
10018                    findMatchingActivity(systemActivities, activityInfo);
10019            if (foundActivity == null) {
10020                // this is a new activity; it cannot obtain >0 priority
10021                if (DEBUG_FILTERS) {
10022                    Slog.i(TAG, "New activity; cap priority to 0;"
10023                            + " package: " + applicationInfo.packageName
10024                            + " activity: " + intent.activity.className
10025                            + " origPrio: " + intent.getPriority());
10026                }
10027                intent.setPriority(0);
10028                return;
10029            }
10030
10031            // found activity, now check for filter equivalence
10032
10033            // a shallow copy is enough; we modify the list, not its contents
10034            final List<ActivityIntentInfo> intentListCopy =
10035                    new ArrayList<>(foundActivity.intents);
10036            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
10037
10038            // find matching action subsets
10039            final Iterator<String> actionsIterator = intent.actionsIterator();
10040            if (actionsIterator != null) {
10041                getIntentListSubset(
10042                        intentListCopy, new ActionIterGenerator(), actionsIterator);
10043                if (intentListCopy.size() == 0) {
10044                    // no more intents to match; we're not equivalent
10045                    if (DEBUG_FILTERS) {
10046                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
10047                                + " package: " + applicationInfo.packageName
10048                                + " activity: " + intent.activity.className
10049                                + " origPrio: " + intent.getPriority());
10050                    }
10051                    intent.setPriority(0);
10052                    return;
10053                }
10054            }
10055
10056            // find matching category subsets
10057            final Iterator<String> categoriesIterator = intent.categoriesIterator();
10058            if (categoriesIterator != null) {
10059                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
10060                        categoriesIterator);
10061                if (intentListCopy.size() == 0) {
10062                    // no more intents to match; we're not equivalent
10063                    if (DEBUG_FILTERS) {
10064                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
10065                                + " package: " + applicationInfo.packageName
10066                                + " activity: " + intent.activity.className
10067                                + " origPrio: " + intent.getPriority());
10068                    }
10069                    intent.setPriority(0);
10070                    return;
10071                }
10072            }
10073
10074            // find matching schemes subsets
10075            final Iterator<String> schemesIterator = intent.schemesIterator();
10076            if (schemesIterator != null) {
10077                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
10078                        schemesIterator);
10079                if (intentListCopy.size() == 0) {
10080                    // no more intents to match; we're not equivalent
10081                    if (DEBUG_FILTERS) {
10082                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
10083                                + " package: " + applicationInfo.packageName
10084                                + " activity: " + intent.activity.className
10085                                + " origPrio: " + intent.getPriority());
10086                    }
10087                    intent.setPriority(0);
10088                    return;
10089                }
10090            }
10091
10092            // find matching authorities subsets
10093            final Iterator<IntentFilter.AuthorityEntry>
10094                    authoritiesIterator = intent.authoritiesIterator();
10095            if (authoritiesIterator != null) {
10096                getIntentListSubset(intentListCopy,
10097                        new AuthoritiesIterGenerator(),
10098                        authoritiesIterator);
10099                if (intentListCopy.size() == 0) {
10100                    // no more intents to match; we're not equivalent
10101                    if (DEBUG_FILTERS) {
10102                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
10103                                + " package: " + applicationInfo.packageName
10104                                + " activity: " + intent.activity.className
10105                                + " origPrio: " + intent.getPriority());
10106                    }
10107                    intent.setPriority(0);
10108                    return;
10109                }
10110            }
10111
10112            // we found matching filter(s); app gets the max priority of all intents
10113            int cappedPriority = 0;
10114            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
10115                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
10116            }
10117            if (intent.getPriority() > cappedPriority) {
10118                if (DEBUG_FILTERS) {
10119                    Slog.i(TAG, "Found matching filter(s);"
10120                            + " cap priority to " + cappedPriority + ";"
10121                            + " package: " + applicationInfo.packageName
10122                            + " activity: " + intent.activity.className
10123                            + " origPrio: " + intent.getPriority());
10124                }
10125                intent.setPriority(cappedPriority);
10126                return;
10127            }
10128            // all this for nothing; the requested priority was <= what was on the system
10129        }
10130
10131        public final void addActivity(PackageParser.Activity a, String type) {
10132            mActivities.put(a.getComponentName(), a);
10133            if (DEBUG_SHOW_INFO)
10134                Log.v(
10135                TAG, "  " + type + " " +
10136                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
10137            if (DEBUG_SHOW_INFO)
10138                Log.v(TAG, "    Class=" + a.info.name);
10139            final int NI = a.intents.size();
10140            for (int j=0; j<NI; j++) {
10141                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10142                if ("activity".equals(type)) {
10143                    final PackageSetting ps =
10144                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
10145                    final List<PackageParser.Activity> systemActivities =
10146                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
10147                    adjustPriority(systemActivities, intent);
10148                }
10149                if (DEBUG_SHOW_INFO) {
10150                    Log.v(TAG, "    IntentFilter:");
10151                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10152                }
10153                if (!intent.debugCheck()) {
10154                    Log.w(TAG, "==> For Activity " + a.info.name);
10155                }
10156                addFilter(intent);
10157            }
10158        }
10159
10160        public final void removeActivity(PackageParser.Activity a, String type) {
10161            mActivities.remove(a.getComponentName());
10162            if (DEBUG_SHOW_INFO) {
10163                Log.v(TAG, "  " + type + " "
10164                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
10165                                : a.info.name) + ":");
10166                Log.v(TAG, "    Class=" + a.info.name);
10167            }
10168            final int NI = a.intents.size();
10169            for (int j=0; j<NI; j++) {
10170                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
10171                if (DEBUG_SHOW_INFO) {
10172                    Log.v(TAG, "    IntentFilter:");
10173                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10174                }
10175                removeFilter(intent);
10176            }
10177        }
10178
10179        @Override
10180        protected boolean allowFilterResult(
10181                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
10182            ActivityInfo filterAi = filter.activity.info;
10183            for (int i=dest.size()-1; i>=0; i--) {
10184                ActivityInfo destAi = dest.get(i).activityInfo;
10185                if (destAi.name == filterAi.name
10186                        && destAi.packageName == filterAi.packageName) {
10187                    return false;
10188                }
10189            }
10190            return true;
10191        }
10192
10193        @Override
10194        protected ActivityIntentInfo[] newArray(int size) {
10195            return new ActivityIntentInfo[size];
10196        }
10197
10198        @Override
10199        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
10200            if (!sUserManager.exists(userId)) return true;
10201            PackageParser.Package p = filter.activity.owner;
10202            if (p != null) {
10203                PackageSetting ps = (PackageSetting)p.mExtras;
10204                if (ps != null) {
10205                    // System apps are never considered stopped for purposes of
10206                    // filtering, because there may be no way for the user to
10207                    // actually re-launch them.
10208                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
10209                            && ps.getStopped(userId);
10210                }
10211            }
10212            return false;
10213        }
10214
10215        @Override
10216        protected boolean isPackageForFilter(String packageName,
10217                PackageParser.ActivityIntentInfo info) {
10218            return packageName.equals(info.activity.owner.packageName);
10219        }
10220
10221        @Override
10222        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
10223                int match, int userId) {
10224            if (!sUserManager.exists(userId)) return null;
10225            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
10226                return null;
10227            }
10228            final PackageParser.Activity activity = info.activity;
10229            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
10230            if (ps == null) {
10231                return null;
10232            }
10233            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
10234                    ps.readUserState(userId), userId);
10235            if (ai == null) {
10236                return null;
10237            }
10238            final ResolveInfo res = new ResolveInfo();
10239            res.activityInfo = ai;
10240            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10241                res.filter = info;
10242            }
10243            if (info != null) {
10244                res.handleAllWebDataURI = info.handleAllWebDataURI();
10245            }
10246            res.priority = info.getPriority();
10247            res.preferredOrder = activity.owner.mPreferredOrder;
10248            //System.out.println("Result: " + res.activityInfo.className +
10249            //                   " = " + res.priority);
10250            res.match = match;
10251            res.isDefault = info.hasDefault;
10252            res.labelRes = info.labelRes;
10253            res.nonLocalizedLabel = info.nonLocalizedLabel;
10254            if (userNeedsBadging(userId)) {
10255                res.noResourceId = true;
10256            } else {
10257                res.icon = info.icon;
10258            }
10259            res.iconResourceId = info.icon;
10260            res.system = res.activityInfo.applicationInfo.isSystemApp();
10261            return res;
10262        }
10263
10264        @Override
10265        protected void sortResults(List<ResolveInfo> results) {
10266            Collections.sort(results, mResolvePrioritySorter);
10267        }
10268
10269        @Override
10270        protected void dumpFilter(PrintWriter out, String prefix,
10271                PackageParser.ActivityIntentInfo filter) {
10272            out.print(prefix); out.print(
10273                    Integer.toHexString(System.identityHashCode(filter.activity)));
10274                    out.print(' ');
10275                    filter.activity.printComponentShortName(out);
10276                    out.print(" filter ");
10277                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10278        }
10279
10280        @Override
10281        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
10282            return filter.activity;
10283        }
10284
10285        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10286            PackageParser.Activity activity = (PackageParser.Activity)label;
10287            out.print(prefix); out.print(
10288                    Integer.toHexString(System.identityHashCode(activity)));
10289                    out.print(' ');
10290                    activity.printComponentShortName(out);
10291            if (count > 1) {
10292                out.print(" ("); out.print(count); out.print(" filters)");
10293            }
10294            out.println();
10295        }
10296
10297        // Keys are String (activity class name), values are Activity.
10298        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
10299                = new ArrayMap<ComponentName, PackageParser.Activity>();
10300        private int mFlags;
10301    }
10302
10303    private final class ServiceIntentResolver
10304            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
10305        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10306                boolean defaultOnly, int userId) {
10307            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10308            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10309        }
10310
10311        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10312                int userId) {
10313            if (!sUserManager.exists(userId)) return null;
10314            mFlags = flags;
10315            return super.queryIntent(intent, resolvedType,
10316                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10317        }
10318
10319        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10320                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
10321            if (!sUserManager.exists(userId)) return null;
10322            if (packageServices == null) {
10323                return null;
10324            }
10325            mFlags = flags;
10326            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
10327            final int N = packageServices.size();
10328            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
10329                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
10330
10331            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
10332            for (int i = 0; i < N; ++i) {
10333                intentFilters = packageServices.get(i).intents;
10334                if (intentFilters != null && intentFilters.size() > 0) {
10335                    PackageParser.ServiceIntentInfo[] array =
10336                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
10337                    intentFilters.toArray(array);
10338                    listCut.add(array);
10339                }
10340            }
10341            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10342        }
10343
10344        public final void addService(PackageParser.Service s) {
10345            mServices.put(s.getComponentName(), s);
10346            if (DEBUG_SHOW_INFO) {
10347                Log.v(TAG, "  "
10348                        + (s.info.nonLocalizedLabel != null
10349                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10350                Log.v(TAG, "    Class=" + s.info.name);
10351            }
10352            final int NI = s.intents.size();
10353            int j;
10354            for (j=0; j<NI; j++) {
10355                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10356                if (DEBUG_SHOW_INFO) {
10357                    Log.v(TAG, "    IntentFilter:");
10358                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10359                }
10360                if (!intent.debugCheck()) {
10361                    Log.w(TAG, "==> For Service " + s.info.name);
10362                }
10363                addFilter(intent);
10364            }
10365        }
10366
10367        public final void removeService(PackageParser.Service s) {
10368            mServices.remove(s.getComponentName());
10369            if (DEBUG_SHOW_INFO) {
10370                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
10371                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
10372                Log.v(TAG, "    Class=" + s.info.name);
10373            }
10374            final int NI = s.intents.size();
10375            int j;
10376            for (j=0; j<NI; j++) {
10377                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
10378                if (DEBUG_SHOW_INFO) {
10379                    Log.v(TAG, "    IntentFilter:");
10380                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10381                }
10382                removeFilter(intent);
10383            }
10384        }
10385
10386        @Override
10387        protected boolean allowFilterResult(
10388                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
10389            ServiceInfo filterSi = filter.service.info;
10390            for (int i=dest.size()-1; i>=0; i--) {
10391                ServiceInfo destAi = dest.get(i).serviceInfo;
10392                if (destAi.name == filterSi.name
10393                        && destAi.packageName == filterSi.packageName) {
10394                    return false;
10395                }
10396            }
10397            return true;
10398        }
10399
10400        @Override
10401        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
10402            return new PackageParser.ServiceIntentInfo[size];
10403        }
10404
10405        @Override
10406        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
10407            if (!sUserManager.exists(userId)) return true;
10408            PackageParser.Package p = filter.service.owner;
10409            if (p != null) {
10410                PackageSetting ps = (PackageSetting)p.mExtras;
10411                if (ps != null) {
10412                    // System apps are never considered stopped for purposes of
10413                    // filtering, because there may be no way for the user to
10414                    // actually re-launch them.
10415                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10416                            && ps.getStopped(userId);
10417                }
10418            }
10419            return false;
10420        }
10421
10422        @Override
10423        protected boolean isPackageForFilter(String packageName,
10424                PackageParser.ServiceIntentInfo info) {
10425            return packageName.equals(info.service.owner.packageName);
10426        }
10427
10428        @Override
10429        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
10430                int match, int userId) {
10431            if (!sUserManager.exists(userId)) return null;
10432            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
10433            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
10434                return null;
10435            }
10436            final PackageParser.Service service = info.service;
10437            PackageSetting ps = (PackageSetting) service.owner.mExtras;
10438            if (ps == null) {
10439                return null;
10440            }
10441            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
10442                    ps.readUserState(userId), userId);
10443            if (si == null) {
10444                return null;
10445            }
10446            final ResolveInfo res = new ResolveInfo();
10447            res.serviceInfo = si;
10448            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
10449                res.filter = filter;
10450            }
10451            res.priority = info.getPriority();
10452            res.preferredOrder = service.owner.mPreferredOrder;
10453            res.match = match;
10454            res.isDefault = info.hasDefault;
10455            res.labelRes = info.labelRes;
10456            res.nonLocalizedLabel = info.nonLocalizedLabel;
10457            res.icon = info.icon;
10458            res.system = res.serviceInfo.applicationInfo.isSystemApp();
10459            return res;
10460        }
10461
10462        @Override
10463        protected void sortResults(List<ResolveInfo> results) {
10464            Collections.sort(results, mResolvePrioritySorter);
10465        }
10466
10467        @Override
10468        protected void dumpFilter(PrintWriter out, String prefix,
10469                PackageParser.ServiceIntentInfo filter) {
10470            out.print(prefix); out.print(
10471                    Integer.toHexString(System.identityHashCode(filter.service)));
10472                    out.print(' ');
10473                    filter.service.printComponentShortName(out);
10474                    out.print(" filter ");
10475                    out.println(Integer.toHexString(System.identityHashCode(filter)));
10476        }
10477
10478        @Override
10479        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
10480            return filter.service;
10481        }
10482
10483        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10484            PackageParser.Service service = (PackageParser.Service)label;
10485            out.print(prefix); out.print(
10486                    Integer.toHexString(System.identityHashCode(service)));
10487                    out.print(' ');
10488                    service.printComponentShortName(out);
10489            if (count > 1) {
10490                out.print(" ("); out.print(count); out.print(" filters)");
10491            }
10492            out.println();
10493        }
10494
10495//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
10496//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
10497//            final List<ResolveInfo> retList = Lists.newArrayList();
10498//            while (i.hasNext()) {
10499//                final ResolveInfo resolveInfo = (ResolveInfo) i;
10500//                if (isEnabledLP(resolveInfo.serviceInfo)) {
10501//                    retList.add(resolveInfo);
10502//                }
10503//            }
10504//            return retList;
10505//        }
10506
10507        // Keys are String (activity class name), values are Activity.
10508        private final ArrayMap<ComponentName, PackageParser.Service> mServices
10509                = new ArrayMap<ComponentName, PackageParser.Service>();
10510        private int mFlags;
10511    };
10512
10513    private final class ProviderIntentResolver
10514            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
10515        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
10516                boolean defaultOnly, int userId) {
10517            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
10518            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
10519        }
10520
10521        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
10522                int userId) {
10523            if (!sUserManager.exists(userId))
10524                return null;
10525            mFlags = flags;
10526            return super.queryIntent(intent, resolvedType,
10527                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
10528        }
10529
10530        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
10531                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
10532            if (!sUserManager.exists(userId))
10533                return null;
10534            if (packageProviders == null) {
10535                return null;
10536            }
10537            mFlags = flags;
10538            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
10539            final int N = packageProviders.size();
10540            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
10541                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
10542
10543            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
10544            for (int i = 0; i < N; ++i) {
10545                intentFilters = packageProviders.get(i).intents;
10546                if (intentFilters != null && intentFilters.size() > 0) {
10547                    PackageParser.ProviderIntentInfo[] array =
10548                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
10549                    intentFilters.toArray(array);
10550                    listCut.add(array);
10551                }
10552            }
10553            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
10554        }
10555
10556        public final void addProvider(PackageParser.Provider p) {
10557            if (mProviders.containsKey(p.getComponentName())) {
10558                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
10559                return;
10560            }
10561
10562            mProviders.put(p.getComponentName(), p);
10563            if (DEBUG_SHOW_INFO) {
10564                Log.v(TAG, "  "
10565                        + (p.info.nonLocalizedLabel != null
10566                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
10567                Log.v(TAG, "    Class=" + p.info.name);
10568            }
10569            final int NI = p.intents.size();
10570            int j;
10571            for (j = 0; j < NI; j++) {
10572                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10573                if (DEBUG_SHOW_INFO) {
10574                    Log.v(TAG, "    IntentFilter:");
10575                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10576                }
10577                if (!intent.debugCheck()) {
10578                    Log.w(TAG, "==> For Provider " + p.info.name);
10579                }
10580                addFilter(intent);
10581            }
10582        }
10583
10584        public final void removeProvider(PackageParser.Provider p) {
10585            mProviders.remove(p.getComponentName());
10586            if (DEBUG_SHOW_INFO) {
10587                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
10588                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
10589                Log.v(TAG, "    Class=" + p.info.name);
10590            }
10591            final int NI = p.intents.size();
10592            int j;
10593            for (j = 0; j < NI; j++) {
10594                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
10595                if (DEBUG_SHOW_INFO) {
10596                    Log.v(TAG, "    IntentFilter:");
10597                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
10598                }
10599                removeFilter(intent);
10600            }
10601        }
10602
10603        @Override
10604        protected boolean allowFilterResult(
10605                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
10606            ProviderInfo filterPi = filter.provider.info;
10607            for (int i = dest.size() - 1; i >= 0; i--) {
10608                ProviderInfo destPi = dest.get(i).providerInfo;
10609                if (destPi.name == filterPi.name
10610                        && destPi.packageName == filterPi.packageName) {
10611                    return false;
10612                }
10613            }
10614            return true;
10615        }
10616
10617        @Override
10618        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
10619            return new PackageParser.ProviderIntentInfo[size];
10620        }
10621
10622        @Override
10623        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
10624            if (!sUserManager.exists(userId))
10625                return true;
10626            PackageParser.Package p = filter.provider.owner;
10627            if (p != null) {
10628                PackageSetting ps = (PackageSetting) p.mExtras;
10629                if (ps != null) {
10630                    // System apps are never considered stopped for purposes of
10631                    // filtering, because there may be no way for the user to
10632                    // actually re-launch them.
10633                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
10634                            && ps.getStopped(userId);
10635                }
10636            }
10637            return false;
10638        }
10639
10640        @Override
10641        protected boolean isPackageForFilter(String packageName,
10642                PackageParser.ProviderIntentInfo info) {
10643            return packageName.equals(info.provider.owner.packageName);
10644        }
10645
10646        @Override
10647        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
10648                int match, int userId) {
10649            if (!sUserManager.exists(userId))
10650                return null;
10651            final PackageParser.ProviderIntentInfo info = filter;
10652            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
10653                return null;
10654            }
10655            final PackageParser.Provider provider = info.provider;
10656            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
10657            if (ps == null) {
10658                return null;
10659            }
10660            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
10661                    ps.readUserState(userId), userId);
10662            if (pi == null) {
10663                return null;
10664            }
10665            final ResolveInfo res = new ResolveInfo();
10666            res.providerInfo = pi;
10667            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
10668                res.filter = filter;
10669            }
10670            res.priority = info.getPriority();
10671            res.preferredOrder = provider.owner.mPreferredOrder;
10672            res.match = match;
10673            res.isDefault = info.hasDefault;
10674            res.labelRes = info.labelRes;
10675            res.nonLocalizedLabel = info.nonLocalizedLabel;
10676            res.icon = info.icon;
10677            res.system = res.providerInfo.applicationInfo.isSystemApp();
10678            return res;
10679        }
10680
10681        @Override
10682        protected void sortResults(List<ResolveInfo> results) {
10683            Collections.sort(results, mResolvePrioritySorter);
10684        }
10685
10686        @Override
10687        protected void dumpFilter(PrintWriter out, String prefix,
10688                PackageParser.ProviderIntentInfo filter) {
10689            out.print(prefix);
10690            out.print(
10691                    Integer.toHexString(System.identityHashCode(filter.provider)));
10692            out.print(' ');
10693            filter.provider.printComponentShortName(out);
10694            out.print(" filter ");
10695            out.println(Integer.toHexString(System.identityHashCode(filter)));
10696        }
10697
10698        @Override
10699        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
10700            return filter.provider;
10701        }
10702
10703        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
10704            PackageParser.Provider provider = (PackageParser.Provider)label;
10705            out.print(prefix); out.print(
10706                    Integer.toHexString(System.identityHashCode(provider)));
10707                    out.print(' ');
10708                    provider.printComponentShortName(out);
10709            if (count > 1) {
10710                out.print(" ("); out.print(count); out.print(" filters)");
10711            }
10712            out.println();
10713        }
10714
10715        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
10716                = new ArrayMap<ComponentName, PackageParser.Provider>();
10717        private int mFlags;
10718    }
10719
10720    private static final class EphemeralIntentResolver
10721            extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> {
10722        @Override
10723        protected EphemeralResolveIntentInfo[] newArray(int size) {
10724            return new EphemeralResolveIntentInfo[size];
10725        }
10726
10727        @Override
10728        protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) {
10729            return true;
10730        }
10731
10732        @Override
10733        protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match,
10734                int userId) {
10735            if (!sUserManager.exists(userId)) {
10736                return null;
10737            }
10738            return info.getEphemeralResolveInfo();
10739        }
10740    }
10741
10742    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
10743            new Comparator<ResolveInfo>() {
10744        public int compare(ResolveInfo r1, ResolveInfo r2) {
10745            int v1 = r1.priority;
10746            int v2 = r2.priority;
10747            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
10748            if (v1 != v2) {
10749                return (v1 > v2) ? -1 : 1;
10750            }
10751            v1 = r1.preferredOrder;
10752            v2 = r2.preferredOrder;
10753            if (v1 != v2) {
10754                return (v1 > v2) ? -1 : 1;
10755            }
10756            if (r1.isDefault != r2.isDefault) {
10757                return r1.isDefault ? -1 : 1;
10758            }
10759            v1 = r1.match;
10760            v2 = r2.match;
10761            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
10762            if (v1 != v2) {
10763                return (v1 > v2) ? -1 : 1;
10764            }
10765            if (r1.system != r2.system) {
10766                return r1.system ? -1 : 1;
10767            }
10768            if (r1.activityInfo != null) {
10769                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
10770            }
10771            if (r1.serviceInfo != null) {
10772                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
10773            }
10774            if (r1.providerInfo != null) {
10775                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
10776            }
10777            return 0;
10778        }
10779    };
10780
10781    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
10782            new Comparator<ProviderInfo>() {
10783        public int compare(ProviderInfo p1, ProviderInfo p2) {
10784            final int v1 = p1.initOrder;
10785            final int v2 = p2.initOrder;
10786            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
10787        }
10788    };
10789
10790    final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
10791            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
10792            final int[] userIds) {
10793        mHandler.post(new Runnable() {
10794            @Override
10795            public void run() {
10796                try {
10797                    final IActivityManager am = ActivityManagerNative.getDefault();
10798                    if (am == null) return;
10799                    final int[] resolvedUserIds;
10800                    if (userIds == null) {
10801                        resolvedUserIds = am.getRunningUserIds();
10802                    } else {
10803                        resolvedUserIds = userIds;
10804                    }
10805                    for (int id : resolvedUserIds) {
10806                        final Intent intent = new Intent(action,
10807                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
10808                        if (extras != null) {
10809                            intent.putExtras(extras);
10810                        }
10811                        if (targetPkg != null) {
10812                            intent.setPackage(targetPkg);
10813                        }
10814                        // Modify the UID when posting to other users
10815                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
10816                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
10817                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
10818                            intent.putExtra(Intent.EXTRA_UID, uid);
10819                        }
10820                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
10821                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
10822                        if (DEBUG_BROADCASTS) {
10823                            RuntimeException here = new RuntimeException("here");
10824                            here.fillInStackTrace();
10825                            Slog.d(TAG, "Sending to user " + id + ": "
10826                                    + intent.toShortString(false, true, false, false)
10827                                    + " " + intent.getExtras(), here);
10828                        }
10829                        am.broadcastIntent(null, intent, null, finishedReceiver,
10830                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
10831                                null, finishedReceiver != null, false, id);
10832                    }
10833                } catch (RemoteException ex) {
10834                }
10835            }
10836        });
10837    }
10838
10839    /**
10840     * Check if the external storage media is available. This is true if there
10841     * is a mounted external storage medium or if the external storage is
10842     * emulated.
10843     */
10844    private boolean isExternalMediaAvailable() {
10845        return mMediaMounted || Environment.isExternalStorageEmulated();
10846    }
10847
10848    @Override
10849    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
10850        // writer
10851        synchronized (mPackages) {
10852            if (!isExternalMediaAvailable()) {
10853                // If the external storage is no longer mounted at this point,
10854                // the caller may not have been able to delete all of this
10855                // packages files and can not delete any more.  Bail.
10856                return null;
10857            }
10858            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
10859            if (lastPackage != null) {
10860                pkgs.remove(lastPackage);
10861            }
10862            if (pkgs.size() > 0) {
10863                return pkgs.get(0);
10864            }
10865        }
10866        return null;
10867    }
10868
10869    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
10870        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
10871                userId, andCode ? 1 : 0, packageName);
10872        if (mSystemReady) {
10873            msg.sendToTarget();
10874        } else {
10875            if (mPostSystemReadyMessages == null) {
10876                mPostSystemReadyMessages = new ArrayList<>();
10877            }
10878            mPostSystemReadyMessages.add(msg);
10879        }
10880    }
10881
10882    void startCleaningPackages() {
10883        // reader
10884        if (!isExternalMediaAvailable()) {
10885            return;
10886        }
10887        synchronized (mPackages) {
10888            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
10889                return;
10890            }
10891        }
10892        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
10893        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
10894        IActivityManager am = ActivityManagerNative.getDefault();
10895        if (am != null) {
10896            try {
10897                am.startService(null, intent, null, mContext.getOpPackageName(),
10898                        UserHandle.USER_SYSTEM);
10899            } catch (RemoteException e) {
10900            }
10901        }
10902    }
10903
10904    @Override
10905    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
10906            int installFlags, String installerPackageName, int userId) {
10907        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
10908
10909        final int callingUid = Binder.getCallingUid();
10910        enforceCrossUserPermission(callingUid, userId,
10911                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
10912
10913        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
10914            try {
10915                if (observer != null) {
10916                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
10917                }
10918            } catch (RemoteException re) {
10919            }
10920            return;
10921        }
10922
10923        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
10924            installFlags |= PackageManager.INSTALL_FROM_ADB;
10925
10926        } else {
10927            // Caller holds INSTALL_PACKAGES permission, so we're less strict
10928            // about installerPackageName.
10929
10930            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
10931            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
10932        }
10933
10934        UserHandle user;
10935        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
10936            user = UserHandle.ALL;
10937        } else {
10938            user = new UserHandle(userId);
10939        }
10940
10941        // Only system components can circumvent runtime permissions when installing.
10942        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
10943                && mContext.checkCallingOrSelfPermission(Manifest.permission
10944                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
10945            throw new SecurityException("You need the "
10946                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
10947                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
10948        }
10949
10950        final File originFile = new File(originPath);
10951        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
10952
10953        final Message msg = mHandler.obtainMessage(INIT_COPY);
10954        final VerificationInfo verificationInfo = new VerificationInfo(
10955                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
10956        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
10957                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
10958                null /*packageAbiOverride*/, null /*grantedPermissions*/);
10959        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
10960        msg.obj = params;
10961
10962        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
10963                System.identityHashCode(msg.obj));
10964        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
10965                System.identityHashCode(msg.obj));
10966
10967        mHandler.sendMessage(msg);
10968    }
10969
10970    void installStage(String packageName, File stagedDir, String stagedCid,
10971            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
10972            String installerPackageName, int installerUid, UserHandle user) {
10973        if (DEBUG_EPHEMERAL) {
10974            if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
10975                Slog.d(TAG, "Ephemeral install of " + packageName);
10976            }
10977        }
10978        final VerificationInfo verificationInfo = new VerificationInfo(
10979                sessionParams.originatingUri, sessionParams.referrerUri,
10980                sessionParams.originatingUid, installerUid);
10981
10982        final OriginInfo origin;
10983        if (stagedDir != null) {
10984            origin = OriginInfo.fromStagedFile(stagedDir);
10985        } else {
10986            origin = OriginInfo.fromStagedContainer(stagedCid);
10987        }
10988
10989        final Message msg = mHandler.obtainMessage(INIT_COPY);
10990        final InstallParams params = new InstallParams(origin, null, observer,
10991                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
10992                verificationInfo, user, sessionParams.abiOverride,
10993                sessionParams.grantedRuntimePermissions);
10994        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
10995        msg.obj = params;
10996
10997        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
10998                System.identityHashCode(msg.obj));
10999        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
11000                System.identityHashCode(msg.obj));
11001
11002        mHandler.sendMessage(msg);
11003    }
11004
11005    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
11006            int userId) {
11007        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
11008        sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId);
11009    }
11010
11011    private void sendPackageAddedForUser(String packageName, boolean isSystem,
11012            int appId, int userId) {
11013        Bundle extras = new Bundle(1);
11014        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId));
11015
11016        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
11017                packageName, extras, 0, null, null, new int[] {userId});
11018        try {
11019            IActivityManager am = ActivityManagerNative.getDefault();
11020            if (isSystem && am.isUserRunning(userId, 0)) {
11021                // The just-installed/enabled app is bundled on the system, so presumed
11022                // to be able to run automatically without needing an explicit launch.
11023                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
11024                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
11025                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
11026                        .setPackage(packageName);
11027                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
11028                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
11029            }
11030        } catch (RemoteException e) {
11031            // shouldn't happen
11032            Slog.w(TAG, "Unable to bootstrap installed package", e);
11033        }
11034    }
11035
11036    @Override
11037    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
11038            int userId) {
11039        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11040        PackageSetting pkgSetting;
11041        final int uid = Binder.getCallingUid();
11042        enforceCrossUserPermission(uid, userId,
11043                true /* requireFullPermission */, true /* checkShell */,
11044                "setApplicationHiddenSetting for user " + userId);
11045
11046        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
11047            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
11048            return false;
11049        }
11050
11051        long callingId = Binder.clearCallingIdentity();
11052        try {
11053            boolean sendAdded = false;
11054            boolean sendRemoved = false;
11055            // writer
11056            synchronized (mPackages) {
11057                pkgSetting = mSettings.mPackages.get(packageName);
11058                if (pkgSetting == null) {
11059                    return false;
11060                }
11061                if (pkgSetting.getHidden(userId) != hidden) {
11062                    pkgSetting.setHidden(hidden, userId);
11063                    mSettings.writePackageRestrictionsLPr(userId);
11064                    if (hidden) {
11065                        sendRemoved = true;
11066                    } else {
11067                        sendAdded = true;
11068                    }
11069                }
11070            }
11071            if (sendAdded) {
11072                sendPackageAddedForUser(packageName, pkgSetting, userId);
11073                return true;
11074            }
11075            if (sendRemoved) {
11076                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
11077                        "hiding pkg");
11078                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
11079                return true;
11080            }
11081        } finally {
11082            Binder.restoreCallingIdentity(callingId);
11083        }
11084        return false;
11085    }
11086
11087    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
11088            int userId) {
11089        final PackageRemovedInfo info = new PackageRemovedInfo();
11090        info.removedPackage = packageName;
11091        info.removedUsers = new int[] {userId};
11092        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
11093        info.sendPackageRemovedBroadcasts(true /*killApp*/);
11094    }
11095
11096    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
11097        if (pkgList.length > 0) {
11098            Bundle extras = new Bundle(1);
11099            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
11100
11101            sendPackageBroadcast(
11102                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
11103                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
11104                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
11105                    new int[] {userId});
11106        }
11107    }
11108
11109    /**
11110     * Returns true if application is not found or there was an error. Otherwise it returns
11111     * the hidden state of the package for the given user.
11112     */
11113    @Override
11114    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
11115        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11116        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11117                true /* requireFullPermission */, false /* checkShell */,
11118                "getApplicationHidden for user " + userId);
11119        PackageSetting pkgSetting;
11120        long callingId = Binder.clearCallingIdentity();
11121        try {
11122            // writer
11123            synchronized (mPackages) {
11124                pkgSetting = mSettings.mPackages.get(packageName);
11125                if (pkgSetting == null) {
11126                    return true;
11127                }
11128                return pkgSetting.getHidden(userId);
11129            }
11130        } finally {
11131            Binder.restoreCallingIdentity(callingId);
11132        }
11133    }
11134
11135    /**
11136     * @hide
11137     */
11138    @Override
11139    public int installExistingPackageAsUser(String packageName, int userId) {
11140        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
11141                null);
11142        PackageSetting pkgSetting;
11143        final int uid = Binder.getCallingUid();
11144        enforceCrossUserPermission(uid, userId,
11145                true /* requireFullPermission */, true /* checkShell */,
11146                "installExistingPackage for user " + userId);
11147        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
11148            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
11149        }
11150
11151        long callingId = Binder.clearCallingIdentity();
11152        try {
11153            boolean installed = false;
11154
11155            // writer
11156            synchronized (mPackages) {
11157                pkgSetting = mSettings.mPackages.get(packageName);
11158                if (pkgSetting == null) {
11159                    return PackageManager.INSTALL_FAILED_INVALID_URI;
11160                }
11161                if (!pkgSetting.getInstalled(userId)) {
11162                    pkgSetting.setInstalled(true, userId);
11163                    pkgSetting.setHidden(false, userId);
11164                    mSettings.writePackageRestrictionsLPr(userId);
11165                    installed = true;
11166                }
11167            }
11168
11169            if (installed) {
11170                if (pkgSetting.pkg != null) {
11171                    prepareAppDataAfterInstall(pkgSetting.pkg);
11172                }
11173                sendPackageAddedForUser(packageName, pkgSetting, userId);
11174            }
11175        } finally {
11176            Binder.restoreCallingIdentity(callingId);
11177        }
11178
11179        return PackageManager.INSTALL_SUCCEEDED;
11180    }
11181
11182    boolean isUserRestricted(int userId, String restrictionKey) {
11183        Bundle restrictions = sUserManager.getUserRestrictions(userId);
11184        if (restrictions.getBoolean(restrictionKey, false)) {
11185            Log.w(TAG, "User is restricted: " + restrictionKey);
11186            return true;
11187        }
11188        return false;
11189    }
11190
11191    @Override
11192    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
11193            int userId) {
11194        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
11195        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11196                true /* requireFullPermission */, true /* checkShell */,
11197                "setPackagesSuspended for user " + userId);
11198
11199        if (ArrayUtils.isEmpty(packageNames)) {
11200            return packageNames;
11201        }
11202
11203        // List of package names for whom the suspended state has changed.
11204        List<String> changedPackages = new ArrayList<>(packageNames.length);
11205        // List of package names for whom the suspended state is not set as requested in this
11206        // method.
11207        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
11208        for (int i = 0; i < packageNames.length; i++) {
11209            String packageName = packageNames[i];
11210            long callingId = Binder.clearCallingIdentity();
11211            try {
11212                boolean changed = false;
11213                final int appId;
11214                synchronized (mPackages) {
11215                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11216                    if (pkgSetting == null) {
11217                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
11218                                + "\". Skipping suspending/un-suspending.");
11219                        unactionedPackages.add(packageName);
11220                        continue;
11221                    }
11222                    appId = pkgSetting.appId;
11223                    if (pkgSetting.getSuspended(userId) != suspended) {
11224                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
11225                            unactionedPackages.add(packageName);
11226                            continue;
11227                        }
11228                        pkgSetting.setSuspended(suspended, userId);
11229                        mSettings.writePackageRestrictionsLPr(userId);
11230                        changed = true;
11231                        changedPackages.add(packageName);
11232                    }
11233                }
11234
11235                if (changed && suspended) {
11236                    killApplication(packageName, UserHandle.getUid(userId, appId),
11237                            "suspending package");
11238                }
11239            } finally {
11240                Binder.restoreCallingIdentity(callingId);
11241            }
11242        }
11243
11244        if (!changedPackages.isEmpty()) {
11245            sendPackagesSuspendedForUser(changedPackages.toArray(
11246                    new String[changedPackages.size()]), userId, suspended);
11247        }
11248
11249        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
11250    }
11251
11252    @Override
11253    public boolean isPackageSuspendedForUser(String packageName, int userId) {
11254        enforceCrossUserPermission(Binder.getCallingUid(), userId,
11255                true /* requireFullPermission */, false /* checkShell */,
11256                "isPackageSuspendedForUser for user " + userId);
11257        synchronized (mPackages) {
11258            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
11259            if (pkgSetting == null) {
11260                throw new IllegalArgumentException("Unknown target package: " + packageName);
11261            }
11262            return pkgSetting.getSuspended(userId);
11263        }
11264    }
11265
11266    /**
11267     * TODO: cache and disallow blocking the active dialer.
11268     *
11269     * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions
11270     */
11271    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
11272        if (isPackageDeviceAdmin(packageName, userId)) {
11273            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11274                    + "\": has an active device admin");
11275            return false;
11276        }
11277
11278        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
11279        if (packageName.equals(activeLauncherPackageName)) {
11280            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11281                    + "\": contains the active launcher");
11282            return false;
11283        }
11284
11285        if (packageName.equals(mRequiredInstallerPackage)) {
11286            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11287                    + "\": required for package installation");
11288            return false;
11289        }
11290
11291        if (packageName.equals(mRequiredVerifierPackage)) {
11292            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11293                    + "\": required for package verification");
11294            return false;
11295        }
11296
11297        final PackageParser.Package pkg = mPackages.get(packageName);
11298        if (pkg != null && isPrivilegedApp(pkg)) {
11299            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
11300                    + "\": is a privileged app");
11301            return false;
11302        }
11303
11304        return true;
11305    }
11306
11307    private String getActiveLauncherPackageName(int userId) {
11308        Intent intent = new Intent(Intent.ACTION_MAIN);
11309        intent.addCategory(Intent.CATEGORY_HOME);
11310        ResolveInfo resolveInfo = resolveIntent(
11311                intent,
11312                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
11313                PackageManager.MATCH_DEFAULT_ONLY,
11314                userId);
11315
11316        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
11317    }
11318
11319    @Override
11320    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
11321        mContext.enforceCallingOrSelfPermission(
11322                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11323                "Only package verification agents can verify applications");
11324
11325        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11326        final PackageVerificationResponse response = new PackageVerificationResponse(
11327                verificationCode, Binder.getCallingUid());
11328        msg.arg1 = id;
11329        msg.obj = response;
11330        mHandler.sendMessage(msg);
11331    }
11332
11333    @Override
11334    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
11335            long millisecondsToDelay) {
11336        mContext.enforceCallingOrSelfPermission(
11337                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
11338                "Only package verification agents can extend verification timeouts");
11339
11340        final PackageVerificationState state = mPendingVerification.get(id);
11341        final PackageVerificationResponse response = new PackageVerificationResponse(
11342                verificationCodeAtTimeout, Binder.getCallingUid());
11343
11344        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
11345            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
11346        }
11347        if (millisecondsToDelay < 0) {
11348            millisecondsToDelay = 0;
11349        }
11350        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
11351                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
11352            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
11353        }
11354
11355        if ((state != null) && !state.timeoutExtended()) {
11356            state.extendTimeout();
11357
11358            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
11359            msg.arg1 = id;
11360            msg.obj = response;
11361            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
11362        }
11363    }
11364
11365    private void broadcastPackageVerified(int verificationId, Uri packageUri,
11366            int verificationCode, UserHandle user) {
11367        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
11368        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
11369        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
11370        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
11371        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
11372
11373        mContext.sendBroadcastAsUser(intent, user,
11374                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
11375    }
11376
11377    private ComponentName matchComponentForVerifier(String packageName,
11378            List<ResolveInfo> receivers) {
11379        ActivityInfo targetReceiver = null;
11380
11381        final int NR = receivers.size();
11382        for (int i = 0; i < NR; i++) {
11383            final ResolveInfo info = receivers.get(i);
11384            if (info.activityInfo == null) {
11385                continue;
11386            }
11387
11388            if (packageName.equals(info.activityInfo.packageName)) {
11389                targetReceiver = info.activityInfo;
11390                break;
11391            }
11392        }
11393
11394        if (targetReceiver == null) {
11395            return null;
11396        }
11397
11398        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
11399    }
11400
11401    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
11402            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
11403        if (pkgInfo.verifiers.length == 0) {
11404            return null;
11405        }
11406
11407        final int N = pkgInfo.verifiers.length;
11408        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
11409        for (int i = 0; i < N; i++) {
11410            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
11411
11412            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
11413                    receivers);
11414            if (comp == null) {
11415                continue;
11416            }
11417
11418            final int verifierUid = getUidForVerifier(verifierInfo);
11419            if (verifierUid == -1) {
11420                continue;
11421            }
11422
11423            if (DEBUG_VERIFY) {
11424                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
11425                        + " with the correct signature");
11426            }
11427            sufficientVerifiers.add(comp);
11428            verificationState.addSufficientVerifier(verifierUid);
11429        }
11430
11431        return sufficientVerifiers;
11432    }
11433
11434    private int getUidForVerifier(VerifierInfo verifierInfo) {
11435        synchronized (mPackages) {
11436            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
11437            if (pkg == null) {
11438                return -1;
11439            } else if (pkg.mSignatures.length != 1) {
11440                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11441                        + " has more than one signature; ignoring");
11442                return -1;
11443            }
11444
11445            /*
11446             * If the public key of the package's signature does not match
11447             * our expected public key, then this is a different package and
11448             * we should skip.
11449             */
11450
11451            final byte[] expectedPublicKey;
11452            try {
11453                final Signature verifierSig = pkg.mSignatures[0];
11454                final PublicKey publicKey = verifierSig.getPublicKey();
11455                expectedPublicKey = publicKey.getEncoded();
11456            } catch (CertificateException e) {
11457                return -1;
11458            }
11459
11460            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
11461
11462            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
11463                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
11464                        + " does not have the expected public key; ignoring");
11465                return -1;
11466            }
11467
11468            return pkg.applicationInfo.uid;
11469        }
11470    }
11471
11472    @Override
11473    public void finishPackageInstall(int token) {
11474        enforceSystemOrRoot("Only the system is allowed to finish installs");
11475
11476        if (DEBUG_INSTALL) {
11477            Slog.v(TAG, "BM finishing package install for " + token);
11478        }
11479        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11480
11481        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11482        mHandler.sendMessage(msg);
11483    }
11484
11485    /**
11486     * Get the verification agent timeout.
11487     *
11488     * @return verification timeout in milliseconds
11489     */
11490    private long getVerificationTimeout() {
11491        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
11492                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
11493                DEFAULT_VERIFICATION_TIMEOUT);
11494    }
11495
11496    /**
11497     * Get the default verification agent response code.
11498     *
11499     * @return default verification response code
11500     */
11501    private int getDefaultVerificationResponse() {
11502        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11503                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
11504                DEFAULT_VERIFICATION_RESPONSE);
11505    }
11506
11507    /**
11508     * Check whether or not package verification has been enabled.
11509     *
11510     * @return true if verification should be performed
11511     */
11512    private boolean isVerificationEnabled(int userId, int installFlags) {
11513        if (!DEFAULT_VERIFY_ENABLE) {
11514            return false;
11515        }
11516        // Ephemeral apps don't get the full verification treatment
11517        if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) {
11518            if (DEBUG_EPHEMERAL) {
11519                Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification");
11520            }
11521            return false;
11522        }
11523
11524        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
11525
11526        // Check if installing from ADB
11527        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
11528            // Do not run verification in a test harness environment
11529            if (ActivityManager.isRunningInTestHarness()) {
11530                return false;
11531            }
11532            if (ensureVerifyAppsEnabled) {
11533                return true;
11534            }
11535            // Check if the developer does not want package verification for ADB installs
11536            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11537                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
11538                return false;
11539            }
11540        }
11541
11542        if (ensureVerifyAppsEnabled) {
11543            return true;
11544        }
11545
11546        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
11547                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
11548    }
11549
11550    @Override
11551    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
11552            throws RemoteException {
11553        mContext.enforceCallingOrSelfPermission(
11554                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
11555                "Only intentfilter verification agents can verify applications");
11556
11557        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
11558        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
11559                Binder.getCallingUid(), verificationCode, failedDomains);
11560        msg.arg1 = id;
11561        msg.obj = response;
11562        mHandler.sendMessage(msg);
11563    }
11564
11565    @Override
11566    public int getIntentVerificationStatus(String packageName, int userId) {
11567        synchronized (mPackages) {
11568            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
11569        }
11570    }
11571
11572    @Override
11573    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
11574        mContext.enforceCallingOrSelfPermission(
11575                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11576
11577        boolean result = false;
11578        synchronized (mPackages) {
11579            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
11580        }
11581        if (result) {
11582            scheduleWritePackageRestrictionsLocked(userId);
11583        }
11584        return result;
11585    }
11586
11587    @Override
11588    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
11589            String packageName) {
11590        synchronized (mPackages) {
11591            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
11592        }
11593    }
11594
11595    @Override
11596    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
11597        if (TextUtils.isEmpty(packageName)) {
11598            return ParceledListSlice.emptyList();
11599        }
11600        synchronized (mPackages) {
11601            PackageParser.Package pkg = mPackages.get(packageName);
11602            if (pkg == null || pkg.activities == null) {
11603                return ParceledListSlice.emptyList();
11604            }
11605            final int count = pkg.activities.size();
11606            ArrayList<IntentFilter> result = new ArrayList<>();
11607            for (int n=0; n<count; n++) {
11608                PackageParser.Activity activity = pkg.activities.get(n);
11609                if (activity.intents != null && activity.intents.size() > 0) {
11610                    result.addAll(activity.intents);
11611                }
11612            }
11613            return new ParceledListSlice<>(result);
11614        }
11615    }
11616
11617    @Override
11618    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
11619        mContext.enforceCallingOrSelfPermission(
11620                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11621
11622        synchronized (mPackages) {
11623            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
11624            if (packageName != null) {
11625                result |= updateIntentVerificationStatus(packageName,
11626                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
11627                        userId);
11628                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
11629                        packageName, userId);
11630            }
11631            return result;
11632        }
11633    }
11634
11635    @Override
11636    public String getDefaultBrowserPackageName(int userId) {
11637        synchronized (mPackages) {
11638            return mSettings.getDefaultBrowserPackageNameLPw(userId);
11639        }
11640    }
11641
11642    /**
11643     * Get the "allow unknown sources" setting.
11644     *
11645     * @return the current "allow unknown sources" setting
11646     */
11647    private int getUnknownSourcesSettings() {
11648        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
11649                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
11650                -1);
11651    }
11652
11653    @Override
11654    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
11655        final int uid = Binder.getCallingUid();
11656        // writer
11657        synchronized (mPackages) {
11658            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
11659            if (targetPackageSetting == null) {
11660                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
11661            }
11662
11663            PackageSetting installerPackageSetting;
11664            if (installerPackageName != null) {
11665                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
11666                if (installerPackageSetting == null) {
11667                    throw new IllegalArgumentException("Unknown installer package: "
11668                            + installerPackageName);
11669                }
11670            } else {
11671                installerPackageSetting = null;
11672            }
11673
11674            Signature[] callerSignature;
11675            Object obj = mSettings.getUserIdLPr(uid);
11676            if (obj != null) {
11677                if (obj instanceof SharedUserSetting) {
11678                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
11679                } else if (obj instanceof PackageSetting) {
11680                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
11681                } else {
11682                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
11683                }
11684            } else {
11685                throw new SecurityException("Unknown calling UID: " + uid);
11686            }
11687
11688            // Verify: can't set installerPackageName to a package that is
11689            // not signed with the same cert as the caller.
11690            if (installerPackageSetting != null) {
11691                if (compareSignatures(callerSignature,
11692                        installerPackageSetting.signatures.mSignatures)
11693                        != PackageManager.SIGNATURE_MATCH) {
11694                    throw new SecurityException(
11695                            "Caller does not have same cert as new installer package "
11696                            + installerPackageName);
11697                }
11698            }
11699
11700            // Verify: if target already has an installer package, it must
11701            // be signed with the same cert as the caller.
11702            if (targetPackageSetting.installerPackageName != null) {
11703                PackageSetting setting = mSettings.mPackages.get(
11704                        targetPackageSetting.installerPackageName);
11705                // If the currently set package isn't valid, then it's always
11706                // okay to change it.
11707                if (setting != null) {
11708                    if (compareSignatures(callerSignature,
11709                            setting.signatures.mSignatures)
11710                            != PackageManager.SIGNATURE_MATCH) {
11711                        throw new SecurityException(
11712                                "Caller does not have same cert as old installer package "
11713                                + targetPackageSetting.installerPackageName);
11714                    }
11715                }
11716            }
11717
11718            // Okay!
11719            targetPackageSetting.installerPackageName = installerPackageName;
11720            scheduleWriteSettingsLocked();
11721        }
11722    }
11723
11724    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
11725        // Queue up an async operation since the package installation may take a little while.
11726        mHandler.post(new Runnable() {
11727            public void run() {
11728                mHandler.removeCallbacks(this);
11729                 // Result object to be returned
11730                PackageInstalledInfo res = new PackageInstalledInfo();
11731                res.setReturnCode(currentStatus);
11732                res.uid = -1;
11733                res.pkg = null;
11734                res.removedInfo = null;
11735                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11736                    args.doPreInstall(res.returnCode);
11737                    synchronized (mInstallLock) {
11738                        installPackageTracedLI(args, res);
11739                    }
11740                    args.doPostInstall(res.returnCode, res.uid);
11741                }
11742
11743                // A restore should be performed at this point if (a) the install
11744                // succeeded, (b) the operation is not an update, and (c) the new
11745                // package has not opted out of backup participation.
11746                final boolean update = res.removedInfo != null
11747                        && res.removedInfo.removedPackage != null;
11748                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
11749                boolean doRestore = !update
11750                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
11751
11752                // Set up the post-install work request bookkeeping.  This will be used
11753                // and cleaned up by the post-install event handling regardless of whether
11754                // there's a restore pass performed.  Token values are >= 1.
11755                int token;
11756                if (mNextInstallToken < 0) mNextInstallToken = 1;
11757                token = mNextInstallToken++;
11758
11759                PostInstallData data = new PostInstallData(args, res);
11760                mRunningInstalls.put(token, data);
11761                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
11762
11763                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
11764                    // Pass responsibility to the Backup Manager.  It will perform a
11765                    // restore if appropriate, then pass responsibility back to the
11766                    // Package Manager to run the post-install observer callbacks
11767                    // and broadcasts.
11768                    IBackupManager bm = IBackupManager.Stub.asInterface(
11769                            ServiceManager.getService(Context.BACKUP_SERVICE));
11770                    if (bm != null) {
11771                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
11772                                + " to BM for possible restore");
11773                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
11774                        try {
11775                            // TODO: http://b/22388012
11776                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
11777                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
11778                            } else {
11779                                doRestore = false;
11780                            }
11781                        } catch (RemoteException e) {
11782                            // can't happen; the backup manager is local
11783                        } catch (Exception e) {
11784                            Slog.e(TAG, "Exception trying to enqueue restore", e);
11785                            doRestore = false;
11786                        }
11787                    } else {
11788                        Slog.e(TAG, "Backup Manager not found!");
11789                        doRestore = false;
11790                    }
11791                }
11792
11793                if (!doRestore) {
11794                    // No restore possible, or the Backup Manager was mysteriously not
11795                    // available -- just fire the post-install work request directly.
11796                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
11797
11798                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
11799
11800                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
11801                    mHandler.sendMessage(msg);
11802                }
11803            }
11804        });
11805    }
11806
11807    private abstract class HandlerParams {
11808        private static final int MAX_RETRIES = 4;
11809
11810        /**
11811         * Number of times startCopy() has been attempted and had a non-fatal
11812         * error.
11813         */
11814        private int mRetries = 0;
11815
11816        /** User handle for the user requesting the information or installation. */
11817        private final UserHandle mUser;
11818        String traceMethod;
11819        int traceCookie;
11820
11821        HandlerParams(UserHandle user) {
11822            mUser = user;
11823        }
11824
11825        UserHandle getUser() {
11826            return mUser;
11827        }
11828
11829        HandlerParams setTraceMethod(String traceMethod) {
11830            this.traceMethod = traceMethod;
11831            return this;
11832        }
11833
11834        HandlerParams setTraceCookie(int traceCookie) {
11835            this.traceCookie = traceCookie;
11836            return this;
11837        }
11838
11839        final boolean startCopy() {
11840            boolean res;
11841            try {
11842                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
11843
11844                if (++mRetries > MAX_RETRIES) {
11845                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
11846                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
11847                    handleServiceError();
11848                    return false;
11849                } else {
11850                    handleStartCopy();
11851                    res = true;
11852                }
11853            } catch (RemoteException e) {
11854                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
11855                mHandler.sendEmptyMessage(MCS_RECONNECT);
11856                res = false;
11857            }
11858            handleReturnCode();
11859            return res;
11860        }
11861
11862        final void serviceError() {
11863            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
11864            handleServiceError();
11865            handleReturnCode();
11866        }
11867
11868        abstract void handleStartCopy() throws RemoteException;
11869        abstract void handleServiceError();
11870        abstract void handleReturnCode();
11871    }
11872
11873    class MeasureParams extends HandlerParams {
11874        private final PackageStats mStats;
11875        private boolean mSuccess;
11876
11877        private final IPackageStatsObserver mObserver;
11878
11879        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
11880            super(new UserHandle(stats.userHandle));
11881            mObserver = observer;
11882            mStats = stats;
11883        }
11884
11885        @Override
11886        public String toString() {
11887            return "MeasureParams{"
11888                + Integer.toHexString(System.identityHashCode(this))
11889                + " " + mStats.packageName + "}";
11890        }
11891
11892        @Override
11893        void handleStartCopy() throws RemoteException {
11894            synchronized (mInstallLock) {
11895                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
11896            }
11897
11898            if (mSuccess) {
11899                final boolean mounted;
11900                if (Environment.isExternalStorageEmulated()) {
11901                    mounted = true;
11902                } else {
11903                    final String status = Environment.getExternalStorageState();
11904                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
11905                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
11906                }
11907
11908                if (mounted) {
11909                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
11910
11911                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
11912                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
11913
11914                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
11915                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
11916
11917                    // Always subtract cache size, since it's a subdirectory
11918                    mStats.externalDataSize -= mStats.externalCacheSize;
11919
11920                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
11921                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
11922
11923                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
11924                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
11925                }
11926            }
11927        }
11928
11929        @Override
11930        void handleReturnCode() {
11931            if (mObserver != null) {
11932                try {
11933                    mObserver.onGetStatsCompleted(mStats, mSuccess);
11934                } catch (RemoteException e) {
11935                    Slog.i(TAG, "Observer no longer exists.");
11936                }
11937            }
11938        }
11939
11940        @Override
11941        void handleServiceError() {
11942            Slog.e(TAG, "Could not measure application " + mStats.packageName
11943                            + " external storage");
11944        }
11945    }
11946
11947    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
11948            throws RemoteException {
11949        long result = 0;
11950        for (File path : paths) {
11951            result += mcs.calculateDirectorySize(path.getAbsolutePath());
11952        }
11953        return result;
11954    }
11955
11956    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
11957        for (File path : paths) {
11958            try {
11959                mcs.clearDirectory(path.getAbsolutePath());
11960            } catch (RemoteException e) {
11961            }
11962        }
11963    }
11964
11965    static class OriginInfo {
11966        /**
11967         * Location where install is coming from, before it has been
11968         * copied/renamed into place. This could be a single monolithic APK
11969         * file, or a cluster directory. This location may be untrusted.
11970         */
11971        final File file;
11972        final String cid;
11973
11974        /**
11975         * Flag indicating that {@link #file} or {@link #cid} has already been
11976         * staged, meaning downstream users don't need to defensively copy the
11977         * contents.
11978         */
11979        final boolean staged;
11980
11981        /**
11982         * Flag indicating that {@link #file} or {@link #cid} is an already
11983         * installed app that is being moved.
11984         */
11985        final boolean existing;
11986
11987        final String resolvedPath;
11988        final File resolvedFile;
11989
11990        static OriginInfo fromNothing() {
11991            return new OriginInfo(null, null, false, false);
11992        }
11993
11994        static OriginInfo fromUntrustedFile(File file) {
11995            return new OriginInfo(file, null, false, false);
11996        }
11997
11998        static OriginInfo fromExistingFile(File file) {
11999            return new OriginInfo(file, null, false, true);
12000        }
12001
12002        static OriginInfo fromStagedFile(File file) {
12003            return new OriginInfo(file, null, true, false);
12004        }
12005
12006        static OriginInfo fromStagedContainer(String cid) {
12007            return new OriginInfo(null, cid, true, false);
12008        }
12009
12010        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
12011            this.file = file;
12012            this.cid = cid;
12013            this.staged = staged;
12014            this.existing = existing;
12015
12016            if (cid != null) {
12017                resolvedPath = PackageHelper.getSdDir(cid);
12018                resolvedFile = new File(resolvedPath);
12019            } else if (file != null) {
12020                resolvedPath = file.getAbsolutePath();
12021                resolvedFile = file;
12022            } else {
12023                resolvedPath = null;
12024                resolvedFile = null;
12025            }
12026        }
12027    }
12028
12029    static class MoveInfo {
12030        final int moveId;
12031        final String fromUuid;
12032        final String toUuid;
12033        final String packageName;
12034        final String dataAppName;
12035        final int appId;
12036        final String seinfo;
12037        final int targetSdkVersion;
12038
12039        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
12040                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
12041            this.moveId = moveId;
12042            this.fromUuid = fromUuid;
12043            this.toUuid = toUuid;
12044            this.packageName = packageName;
12045            this.dataAppName = dataAppName;
12046            this.appId = appId;
12047            this.seinfo = seinfo;
12048            this.targetSdkVersion = targetSdkVersion;
12049        }
12050    }
12051
12052    static class VerificationInfo {
12053        /** A constant used to indicate that a uid value is not present. */
12054        public static final int NO_UID = -1;
12055
12056        /** URI referencing where the package was downloaded from. */
12057        final Uri originatingUri;
12058
12059        /** HTTP referrer URI associated with the originatingURI. */
12060        final Uri referrer;
12061
12062        /** UID of the application that the install request originated from. */
12063        final int originatingUid;
12064
12065        /** UID of application requesting the install */
12066        final int installerUid;
12067
12068        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
12069            this.originatingUri = originatingUri;
12070            this.referrer = referrer;
12071            this.originatingUid = originatingUid;
12072            this.installerUid = installerUid;
12073        }
12074    }
12075
12076    class InstallParams extends HandlerParams {
12077        final OriginInfo origin;
12078        final MoveInfo move;
12079        final IPackageInstallObserver2 observer;
12080        int installFlags;
12081        final String installerPackageName;
12082        final String volumeUuid;
12083        private InstallArgs mArgs;
12084        private int mRet;
12085        final String packageAbiOverride;
12086        final String[] grantedRuntimePermissions;
12087        final VerificationInfo verificationInfo;
12088
12089        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12090                int installFlags, String installerPackageName, String volumeUuid,
12091                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
12092                String[] grantedPermissions) {
12093            super(user);
12094            this.origin = origin;
12095            this.move = move;
12096            this.observer = observer;
12097            this.installFlags = installFlags;
12098            this.installerPackageName = installerPackageName;
12099            this.volumeUuid = volumeUuid;
12100            this.verificationInfo = verificationInfo;
12101            this.packageAbiOverride = packageAbiOverride;
12102            this.grantedRuntimePermissions = grantedPermissions;
12103        }
12104
12105        @Override
12106        public String toString() {
12107            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
12108                    + " file=" + origin.file + " cid=" + origin.cid + "}";
12109        }
12110
12111        private int installLocationPolicy(PackageInfoLite pkgLite) {
12112            String packageName = pkgLite.packageName;
12113            int installLocation = pkgLite.installLocation;
12114            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12115            // reader
12116            synchronized (mPackages) {
12117                // Currently installed package which the new package is attempting to replace or
12118                // null if no such package is installed.
12119                PackageParser.Package installedPkg = mPackages.get(packageName);
12120                // Package which currently owns the data which the new package will own if installed.
12121                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
12122                // will be null whereas dataOwnerPkg will contain information about the package
12123                // which was uninstalled while keeping its data.
12124                PackageParser.Package dataOwnerPkg = installedPkg;
12125                if (dataOwnerPkg  == null) {
12126                    PackageSetting ps = mSettings.mPackages.get(packageName);
12127                    if (ps != null) {
12128                        dataOwnerPkg = ps.pkg;
12129                    }
12130                }
12131
12132                if (dataOwnerPkg != null) {
12133                    // If installed, the package will get access to data left on the device by its
12134                    // predecessor. As a security measure, this is permited only if this is not a
12135                    // version downgrade or if the predecessor package is marked as debuggable and
12136                    // a downgrade is explicitly requested.
12137                    //
12138                    // On debuggable platform builds, downgrades are permitted even for
12139                    // non-debuggable packages to make testing easier. Debuggable platform builds do
12140                    // not offer security guarantees and thus it's OK to disable some security
12141                    // mechanisms to make debugging/testing easier on those builds. However, even on
12142                    // debuggable builds downgrades of packages are permitted only if requested via
12143                    // installFlags. This is because we aim to keep the behavior of debuggable
12144                    // platform builds as close as possible to the behavior of non-debuggable
12145                    // platform builds.
12146                    final boolean downgradeRequested =
12147                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
12148                    final boolean packageDebuggable =
12149                                (dataOwnerPkg.applicationInfo.flags
12150                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
12151                    final boolean downgradePermitted =
12152                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
12153                    if (!downgradePermitted) {
12154                        try {
12155                            checkDowngrade(dataOwnerPkg, pkgLite);
12156                        } catch (PackageManagerException e) {
12157                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
12158                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
12159                        }
12160                    }
12161                }
12162
12163                if (installedPkg != null) {
12164                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
12165                        // Check for updated system application.
12166                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12167                            if (onSd) {
12168                                Slog.w(TAG, "Cannot install update to system app on sdcard");
12169                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
12170                            }
12171                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12172                        } else {
12173                            if (onSd) {
12174                                // Install flag overrides everything.
12175                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12176                            }
12177                            // If current upgrade specifies particular preference
12178                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
12179                                // Application explicitly specified internal.
12180                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12181                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
12182                                // App explictly prefers external. Let policy decide
12183                            } else {
12184                                // Prefer previous location
12185                                if (isExternal(installedPkg)) {
12186                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12187                                }
12188                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
12189                            }
12190                        }
12191                    } else {
12192                        // Invalid install. Return error code
12193                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
12194                    }
12195                }
12196            }
12197            // All the special cases have been taken care of.
12198            // Return result based on recommended install location.
12199            if (onSd) {
12200                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
12201            }
12202            return pkgLite.recommendedInstallLocation;
12203        }
12204
12205        /*
12206         * Invoke remote method to get package information and install
12207         * location values. Override install location based on default
12208         * policy if needed and then create install arguments based
12209         * on the install location.
12210         */
12211        public void handleStartCopy() throws RemoteException {
12212            int ret = PackageManager.INSTALL_SUCCEEDED;
12213
12214            // If we're already staged, we've firmly committed to an install location
12215            if (origin.staged) {
12216                if (origin.file != null) {
12217                    installFlags |= PackageManager.INSTALL_INTERNAL;
12218                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12219                } else if (origin.cid != null) {
12220                    installFlags |= PackageManager.INSTALL_EXTERNAL;
12221                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
12222                } else {
12223                    throw new IllegalStateException("Invalid stage location");
12224                }
12225            }
12226
12227            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12228            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
12229            final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12230            PackageInfoLite pkgLite = null;
12231
12232            if (onInt && onSd) {
12233                // Check if both bits are set.
12234                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
12235                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12236            } else if (onSd && ephemeral) {
12237                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
12238                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12239            } else {
12240                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
12241                        packageAbiOverride);
12242
12243                if (DEBUG_EPHEMERAL && ephemeral) {
12244                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
12245                }
12246
12247                /*
12248                 * If we have too little free space, try to free cache
12249                 * before giving up.
12250                 */
12251                if (!origin.staged && pkgLite.recommendedInstallLocation
12252                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12253                    // TODO: focus freeing disk space on the target device
12254                    final StorageManager storage = StorageManager.from(mContext);
12255                    final long lowThreshold = storage.getStorageLowBytes(
12256                            Environment.getDataDirectory());
12257
12258                    final long sizeBytes = mContainerService.calculateInstalledSize(
12259                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
12260
12261                    try {
12262                        mInstaller.freeCache(null, sizeBytes + lowThreshold);
12263                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
12264                                installFlags, packageAbiOverride);
12265                    } catch (InstallerException e) {
12266                        Slog.w(TAG, "Failed to free cache", e);
12267                    }
12268
12269                    /*
12270                     * The cache free must have deleted the file we
12271                     * downloaded to install.
12272                     *
12273                     * TODO: fix the "freeCache" call to not delete
12274                     *       the file we care about.
12275                     */
12276                    if (pkgLite.recommendedInstallLocation
12277                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12278                        pkgLite.recommendedInstallLocation
12279                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
12280                    }
12281                }
12282            }
12283
12284            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12285                int loc = pkgLite.recommendedInstallLocation;
12286                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
12287                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
12288                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
12289                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
12290                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
12291                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12292                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
12293                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
12294                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
12295                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
12296                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
12297                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
12298                } else {
12299                    // Override with defaults if needed.
12300                    loc = installLocationPolicy(pkgLite);
12301                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
12302                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
12303                    } else if (!onSd && !onInt) {
12304                        // Override install location with flags
12305                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
12306                            // Set the flag to install on external media.
12307                            installFlags |= PackageManager.INSTALL_EXTERNAL;
12308                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
12309                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
12310                            if (DEBUG_EPHEMERAL) {
12311                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
12312                            }
12313                            installFlags |= PackageManager.INSTALL_EPHEMERAL;
12314                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
12315                                    |PackageManager.INSTALL_INTERNAL);
12316                        } else {
12317                            // Make sure the flag for installing on external
12318                            // media is unset
12319                            installFlags |= PackageManager.INSTALL_INTERNAL;
12320                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
12321                        }
12322                    }
12323                }
12324            }
12325
12326            final InstallArgs args = createInstallArgs(this);
12327            mArgs = args;
12328
12329            if (ret == PackageManager.INSTALL_SUCCEEDED) {
12330                // TODO: http://b/22976637
12331                // Apps installed for "all" users use the device owner to verify the app
12332                UserHandle verifierUser = getUser();
12333                if (verifierUser == UserHandle.ALL) {
12334                    verifierUser = UserHandle.SYSTEM;
12335                }
12336
12337                /*
12338                 * Determine if we have any installed package verifiers. If we
12339                 * do, then we'll defer to them to verify the packages.
12340                 */
12341                final int requiredUid = mRequiredVerifierPackage == null ? -1
12342                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
12343                                verifierUser.getIdentifier());
12344                if (!origin.existing && requiredUid != -1
12345                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
12346                    final Intent verification = new Intent(
12347                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
12348                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
12349                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
12350                            PACKAGE_MIME_TYPE);
12351                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
12352
12353                    // Query all live verifiers based on current user state
12354                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
12355                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
12356
12357                    if (DEBUG_VERIFY) {
12358                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
12359                                + verification.toString() + " with " + pkgLite.verifiers.length
12360                                + " optional verifiers");
12361                    }
12362
12363                    final int verificationId = mPendingVerificationToken++;
12364
12365                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
12366
12367                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
12368                            installerPackageName);
12369
12370                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
12371                            installFlags);
12372
12373                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
12374                            pkgLite.packageName);
12375
12376                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
12377                            pkgLite.versionCode);
12378
12379                    if (verificationInfo != null) {
12380                        if (verificationInfo.originatingUri != null) {
12381                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
12382                                    verificationInfo.originatingUri);
12383                        }
12384                        if (verificationInfo.referrer != null) {
12385                            verification.putExtra(Intent.EXTRA_REFERRER,
12386                                    verificationInfo.referrer);
12387                        }
12388                        if (verificationInfo.originatingUid >= 0) {
12389                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
12390                                    verificationInfo.originatingUid);
12391                        }
12392                        if (verificationInfo.installerUid >= 0) {
12393                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
12394                                    verificationInfo.installerUid);
12395                        }
12396                    }
12397
12398                    final PackageVerificationState verificationState = new PackageVerificationState(
12399                            requiredUid, args);
12400
12401                    mPendingVerification.append(verificationId, verificationState);
12402
12403                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
12404                            receivers, verificationState);
12405
12406                    /*
12407                     * If any sufficient verifiers were listed in the package
12408                     * manifest, attempt to ask them.
12409                     */
12410                    if (sufficientVerifiers != null) {
12411                        final int N = sufficientVerifiers.size();
12412                        if (N == 0) {
12413                            Slog.i(TAG, "Additional verifiers required, but none installed.");
12414                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
12415                        } else {
12416                            for (int i = 0; i < N; i++) {
12417                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
12418
12419                                final Intent sufficientIntent = new Intent(verification);
12420                                sufficientIntent.setComponent(verifierComponent);
12421                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
12422                            }
12423                        }
12424                    }
12425
12426                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
12427                            mRequiredVerifierPackage, receivers);
12428                    if (ret == PackageManager.INSTALL_SUCCEEDED
12429                            && mRequiredVerifierPackage != null) {
12430                        Trace.asyncTraceBegin(
12431                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
12432                        /*
12433                         * Send the intent to the required verification agent,
12434                         * but only start the verification timeout after the
12435                         * target BroadcastReceivers have run.
12436                         */
12437                        verification.setComponent(requiredVerifierComponent);
12438                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
12439                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12440                                new BroadcastReceiver() {
12441                                    @Override
12442                                    public void onReceive(Context context, Intent intent) {
12443                                        final Message msg = mHandler
12444                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
12445                                        msg.arg1 = verificationId;
12446                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
12447                                    }
12448                                }, null, 0, null, null);
12449
12450                        /*
12451                         * We don't want the copy to proceed until verification
12452                         * succeeds, so null out this field.
12453                         */
12454                        mArgs = null;
12455                    }
12456                } else {
12457                    /*
12458                     * No package verification is enabled, so immediately start
12459                     * the remote call to initiate copy using temporary file.
12460                     */
12461                    ret = args.copyApk(mContainerService, true);
12462                }
12463            }
12464
12465            mRet = ret;
12466        }
12467
12468        @Override
12469        void handleReturnCode() {
12470            // If mArgs is null, then MCS couldn't be reached. When it
12471            // reconnects, it will try again to install. At that point, this
12472            // will succeed.
12473            if (mArgs != null) {
12474                processPendingInstall(mArgs, mRet);
12475            }
12476        }
12477
12478        @Override
12479        void handleServiceError() {
12480            mArgs = createInstallArgs(this);
12481            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12482        }
12483
12484        public boolean isForwardLocked() {
12485            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12486        }
12487    }
12488
12489    /**
12490     * Used during creation of InstallArgs
12491     *
12492     * @param installFlags package installation flags
12493     * @return true if should be installed on external storage
12494     */
12495    private static boolean installOnExternalAsec(int installFlags) {
12496        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
12497            return false;
12498        }
12499        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
12500            return true;
12501        }
12502        return false;
12503    }
12504
12505    /**
12506     * Used during creation of InstallArgs
12507     *
12508     * @param installFlags package installation flags
12509     * @return true if should be installed as forward locked
12510     */
12511    private static boolean installForwardLocked(int installFlags) {
12512        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12513    }
12514
12515    private InstallArgs createInstallArgs(InstallParams params) {
12516        if (params.move != null) {
12517            return new MoveInstallArgs(params);
12518        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
12519            return new AsecInstallArgs(params);
12520        } else {
12521            return new FileInstallArgs(params);
12522        }
12523    }
12524
12525    /**
12526     * Create args that describe an existing installed package. Typically used
12527     * when cleaning up old installs, or used as a move source.
12528     */
12529    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
12530            String resourcePath, String[] instructionSets) {
12531        final boolean isInAsec;
12532        if (installOnExternalAsec(installFlags)) {
12533            /* Apps on SD card are always in ASEC containers. */
12534            isInAsec = true;
12535        } else if (installForwardLocked(installFlags)
12536                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
12537            /*
12538             * Forward-locked apps are only in ASEC containers if they're the
12539             * new style
12540             */
12541            isInAsec = true;
12542        } else {
12543            isInAsec = false;
12544        }
12545
12546        if (isInAsec) {
12547            return new AsecInstallArgs(codePath, instructionSets,
12548                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
12549        } else {
12550            return new FileInstallArgs(codePath, resourcePath, instructionSets);
12551        }
12552    }
12553
12554    static abstract class InstallArgs {
12555        /** @see InstallParams#origin */
12556        final OriginInfo origin;
12557        /** @see InstallParams#move */
12558        final MoveInfo move;
12559
12560        final IPackageInstallObserver2 observer;
12561        // Always refers to PackageManager flags only
12562        final int installFlags;
12563        final String installerPackageName;
12564        final String volumeUuid;
12565        final UserHandle user;
12566        final String abiOverride;
12567        final String[] installGrantPermissions;
12568        /** If non-null, drop an async trace when the install completes */
12569        final String traceMethod;
12570        final int traceCookie;
12571
12572        // The list of instruction sets supported by this app. This is currently
12573        // only used during the rmdex() phase to clean up resources. We can get rid of this
12574        // if we move dex files under the common app path.
12575        /* nullable */ String[] instructionSets;
12576
12577        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
12578                int installFlags, String installerPackageName, String volumeUuid,
12579                UserHandle user, String[] instructionSets,
12580                String abiOverride, String[] installGrantPermissions,
12581                String traceMethod, int traceCookie) {
12582            this.origin = origin;
12583            this.move = move;
12584            this.installFlags = installFlags;
12585            this.observer = observer;
12586            this.installerPackageName = installerPackageName;
12587            this.volumeUuid = volumeUuid;
12588            this.user = user;
12589            this.instructionSets = instructionSets;
12590            this.abiOverride = abiOverride;
12591            this.installGrantPermissions = installGrantPermissions;
12592            this.traceMethod = traceMethod;
12593            this.traceCookie = traceCookie;
12594        }
12595
12596        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
12597        abstract int doPreInstall(int status);
12598
12599        /**
12600         * Rename package into final resting place. All paths on the given
12601         * scanned package should be updated to reflect the rename.
12602         */
12603        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
12604        abstract int doPostInstall(int status, int uid);
12605
12606        /** @see PackageSettingBase#codePathString */
12607        abstract String getCodePath();
12608        /** @see PackageSettingBase#resourcePathString */
12609        abstract String getResourcePath();
12610
12611        // Need installer lock especially for dex file removal.
12612        abstract void cleanUpResourcesLI();
12613        abstract boolean doPostDeleteLI(boolean delete);
12614
12615        /**
12616         * Called before the source arguments are copied. This is used mostly
12617         * for MoveParams when it needs to read the source file to put it in the
12618         * destination.
12619         */
12620        int doPreCopy() {
12621            return PackageManager.INSTALL_SUCCEEDED;
12622        }
12623
12624        /**
12625         * Called after the source arguments are copied. This is used mostly for
12626         * MoveParams when it needs to read the source file to put it in the
12627         * destination.
12628         */
12629        int doPostCopy(int uid) {
12630            return PackageManager.INSTALL_SUCCEEDED;
12631        }
12632
12633        protected boolean isFwdLocked() {
12634            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
12635        }
12636
12637        protected boolean isExternalAsec() {
12638            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
12639        }
12640
12641        protected boolean isEphemeral() {
12642            return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12643        }
12644
12645        UserHandle getUser() {
12646            return user;
12647        }
12648    }
12649
12650    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
12651        if (!allCodePaths.isEmpty()) {
12652            if (instructionSets == null) {
12653                throw new IllegalStateException("instructionSet == null");
12654            }
12655            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
12656            for (String codePath : allCodePaths) {
12657                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
12658                    try {
12659                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
12660                    } catch (InstallerException ignored) {
12661                    }
12662                }
12663            }
12664        }
12665    }
12666
12667    /**
12668     * Logic to handle installation of non-ASEC applications, including copying
12669     * and renaming logic.
12670     */
12671    class FileInstallArgs extends InstallArgs {
12672        private File codeFile;
12673        private File resourceFile;
12674
12675        // Example topology:
12676        // /data/app/com.example/base.apk
12677        // /data/app/com.example/split_foo.apk
12678        // /data/app/com.example/lib/arm/libfoo.so
12679        // /data/app/com.example/lib/arm64/libfoo.so
12680        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
12681
12682        /** New install */
12683        FileInstallArgs(InstallParams params) {
12684            super(params.origin, params.move, params.observer, params.installFlags,
12685                    params.installerPackageName, params.volumeUuid,
12686                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12687                    params.grantedRuntimePermissions,
12688                    params.traceMethod, params.traceCookie);
12689            if (isFwdLocked()) {
12690                throw new IllegalArgumentException("Forward locking only supported in ASEC");
12691            }
12692        }
12693
12694        /** Existing install */
12695        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
12696            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
12697                    null, null, null, 0);
12698            this.codeFile = (codePath != null) ? new File(codePath) : null;
12699            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
12700        }
12701
12702        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12703            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
12704            try {
12705                return doCopyApk(imcs, temp);
12706            } finally {
12707                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12708            }
12709        }
12710
12711        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12712            if (origin.staged) {
12713                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
12714                codeFile = origin.file;
12715                resourceFile = origin.file;
12716                return PackageManager.INSTALL_SUCCEEDED;
12717            }
12718
12719            try {
12720                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0;
12721                final File tempDir =
12722                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
12723                codeFile = tempDir;
12724                resourceFile = tempDir;
12725            } catch (IOException e) {
12726                Slog.w(TAG, "Failed to create copy file: " + e);
12727                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
12728            }
12729
12730            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
12731                @Override
12732                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
12733                    if (!FileUtils.isValidExtFilename(name)) {
12734                        throw new IllegalArgumentException("Invalid filename: " + name);
12735                    }
12736                    try {
12737                        final File file = new File(codeFile, name);
12738                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
12739                                O_RDWR | O_CREAT, 0644);
12740                        Os.chmod(file.getAbsolutePath(), 0644);
12741                        return new ParcelFileDescriptor(fd);
12742                    } catch (ErrnoException e) {
12743                        throw new RemoteException("Failed to open: " + e.getMessage());
12744                    }
12745                }
12746            };
12747
12748            int ret = PackageManager.INSTALL_SUCCEEDED;
12749            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
12750            if (ret != PackageManager.INSTALL_SUCCEEDED) {
12751                Slog.e(TAG, "Failed to copy package");
12752                return ret;
12753            }
12754
12755            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
12756            NativeLibraryHelper.Handle handle = null;
12757            try {
12758                handle = NativeLibraryHelper.Handle.create(codeFile);
12759                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
12760                        abiOverride);
12761            } catch (IOException e) {
12762                Slog.e(TAG, "Copying native libraries failed", e);
12763                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
12764            } finally {
12765                IoUtils.closeQuietly(handle);
12766            }
12767
12768            return ret;
12769        }
12770
12771        int doPreInstall(int status) {
12772            if (status != PackageManager.INSTALL_SUCCEEDED) {
12773                cleanUp();
12774            }
12775            return status;
12776        }
12777
12778        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
12779            if (status != PackageManager.INSTALL_SUCCEEDED) {
12780                cleanUp();
12781                return false;
12782            }
12783
12784            final File targetDir = codeFile.getParentFile();
12785            final File beforeCodeFile = codeFile;
12786            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
12787
12788            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
12789            try {
12790                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
12791            } catch (ErrnoException e) {
12792                Slog.w(TAG, "Failed to rename", e);
12793                return false;
12794            }
12795
12796            if (!SELinux.restoreconRecursive(afterCodeFile)) {
12797                Slog.w(TAG, "Failed to restorecon");
12798                return false;
12799            }
12800
12801            // Reflect the rename internally
12802            codeFile = afterCodeFile;
12803            resourceFile = afterCodeFile;
12804
12805            // Reflect the rename in scanned details
12806            pkg.setCodePath(afterCodeFile.getAbsolutePath());
12807            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
12808                    afterCodeFile, pkg.baseCodePath));
12809            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
12810                    afterCodeFile, pkg.splitCodePaths));
12811
12812            // Reflect the rename in app info
12813            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
12814            pkg.setApplicationInfoCodePath(pkg.codePath);
12815            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
12816            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
12817            pkg.setApplicationInfoResourcePath(pkg.codePath);
12818            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
12819            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
12820
12821            return true;
12822        }
12823
12824        int doPostInstall(int status, int uid) {
12825            if (status != PackageManager.INSTALL_SUCCEEDED) {
12826                cleanUp();
12827            }
12828            return status;
12829        }
12830
12831        @Override
12832        String getCodePath() {
12833            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
12834        }
12835
12836        @Override
12837        String getResourcePath() {
12838            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
12839        }
12840
12841        private boolean cleanUp() {
12842            if (codeFile == null || !codeFile.exists()) {
12843                return false;
12844            }
12845
12846            removeCodePathLI(codeFile);
12847
12848            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
12849                resourceFile.delete();
12850            }
12851
12852            return true;
12853        }
12854
12855        void cleanUpResourcesLI() {
12856            // Try enumerating all code paths before deleting
12857            List<String> allCodePaths = Collections.EMPTY_LIST;
12858            if (codeFile != null && codeFile.exists()) {
12859                try {
12860                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
12861                    allCodePaths = pkg.getAllCodePaths();
12862                } catch (PackageParserException e) {
12863                    // Ignored; we tried our best
12864                }
12865            }
12866
12867            cleanUp();
12868            removeDexFiles(allCodePaths, instructionSets);
12869        }
12870
12871        boolean doPostDeleteLI(boolean delete) {
12872            // XXX err, shouldn't we respect the delete flag?
12873            cleanUpResourcesLI();
12874            return true;
12875        }
12876    }
12877
12878    private boolean isAsecExternal(String cid) {
12879        final String asecPath = PackageHelper.getSdFilesystem(cid);
12880        return !asecPath.startsWith(mAsecInternalPath);
12881    }
12882
12883    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
12884            PackageManagerException {
12885        if (copyRet < 0) {
12886            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
12887                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
12888                throw new PackageManagerException(copyRet, message);
12889            }
12890        }
12891    }
12892
12893    /**
12894     * Extract the MountService "container ID" from the full code path of an
12895     * .apk.
12896     */
12897    static String cidFromCodePath(String fullCodePath) {
12898        int eidx = fullCodePath.lastIndexOf("/");
12899        String subStr1 = fullCodePath.substring(0, eidx);
12900        int sidx = subStr1.lastIndexOf("/");
12901        return subStr1.substring(sidx+1, eidx);
12902    }
12903
12904    /**
12905     * Logic to handle installation of ASEC applications, including copying and
12906     * renaming logic.
12907     */
12908    class AsecInstallArgs extends InstallArgs {
12909        static final String RES_FILE_NAME = "pkg.apk";
12910        static final String PUBLIC_RES_FILE_NAME = "res.zip";
12911
12912        String cid;
12913        String packagePath;
12914        String resourcePath;
12915
12916        /** New install */
12917        AsecInstallArgs(InstallParams params) {
12918            super(params.origin, params.move, params.observer, params.installFlags,
12919                    params.installerPackageName, params.volumeUuid,
12920                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
12921                    params.grantedRuntimePermissions,
12922                    params.traceMethod, params.traceCookie);
12923        }
12924
12925        /** Existing install */
12926        AsecInstallArgs(String fullCodePath, String[] instructionSets,
12927                        boolean isExternal, boolean isForwardLocked) {
12928            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
12929                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12930                    instructionSets, null, null, null, 0);
12931            // Hackily pretend we're still looking at a full code path
12932            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
12933                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
12934            }
12935
12936            // Extract cid from fullCodePath
12937            int eidx = fullCodePath.lastIndexOf("/");
12938            String subStr1 = fullCodePath.substring(0, eidx);
12939            int sidx = subStr1.lastIndexOf("/");
12940            cid = subStr1.substring(sidx+1, eidx);
12941            setMountPath(subStr1);
12942        }
12943
12944        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
12945            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
12946                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
12947                    instructionSets, null, null, null, 0);
12948            this.cid = cid;
12949            setMountPath(PackageHelper.getSdDir(cid));
12950        }
12951
12952        void createCopyFile() {
12953            cid = mInstallerService.allocateExternalStageCidLegacy();
12954        }
12955
12956        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
12957            if (origin.staged && origin.cid != null) {
12958                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
12959                cid = origin.cid;
12960                setMountPath(PackageHelper.getSdDir(cid));
12961                return PackageManager.INSTALL_SUCCEEDED;
12962            }
12963
12964            if (temp) {
12965                createCopyFile();
12966            } else {
12967                /*
12968                 * Pre-emptively destroy the container since it's destroyed if
12969                 * copying fails due to it existing anyway.
12970                 */
12971                PackageHelper.destroySdDir(cid);
12972            }
12973
12974            final String newMountPath = imcs.copyPackageToContainer(
12975                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
12976                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
12977
12978            if (newMountPath != null) {
12979                setMountPath(newMountPath);
12980                return PackageManager.INSTALL_SUCCEEDED;
12981            } else {
12982                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12983            }
12984        }
12985
12986        @Override
12987        String getCodePath() {
12988            return packagePath;
12989        }
12990
12991        @Override
12992        String getResourcePath() {
12993            return resourcePath;
12994        }
12995
12996        int doPreInstall(int status) {
12997            if (status != PackageManager.INSTALL_SUCCEEDED) {
12998                // Destroy container
12999                PackageHelper.destroySdDir(cid);
13000            } else {
13001                boolean mounted = PackageHelper.isContainerMounted(cid);
13002                if (!mounted) {
13003                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
13004                            Process.SYSTEM_UID);
13005                    if (newMountPath != null) {
13006                        setMountPath(newMountPath);
13007                    } else {
13008                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13009                    }
13010                }
13011            }
13012            return status;
13013        }
13014
13015        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13016            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
13017            String newMountPath = null;
13018            if (PackageHelper.isContainerMounted(cid)) {
13019                // Unmount the container
13020                if (!PackageHelper.unMountSdDir(cid)) {
13021                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
13022                    return false;
13023                }
13024            }
13025            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13026                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
13027                        " which might be stale. Will try to clean up.");
13028                // Clean up the stale container and proceed to recreate.
13029                if (!PackageHelper.destroySdDir(newCacheId)) {
13030                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
13031                    return false;
13032                }
13033                // Successfully cleaned up stale container. Try to rename again.
13034                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
13035                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
13036                            + " inspite of cleaning it up.");
13037                    return false;
13038                }
13039            }
13040            if (!PackageHelper.isContainerMounted(newCacheId)) {
13041                Slog.w(TAG, "Mounting container " + newCacheId);
13042                newMountPath = PackageHelper.mountSdDir(newCacheId,
13043                        getEncryptKey(), Process.SYSTEM_UID);
13044            } else {
13045                newMountPath = PackageHelper.getSdDir(newCacheId);
13046            }
13047            if (newMountPath == null) {
13048                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
13049                return false;
13050            }
13051            Log.i(TAG, "Succesfully renamed " + cid +
13052                    " to " + newCacheId +
13053                    " at new path: " + newMountPath);
13054            cid = newCacheId;
13055
13056            final File beforeCodeFile = new File(packagePath);
13057            setMountPath(newMountPath);
13058            final File afterCodeFile = new File(packagePath);
13059
13060            // Reflect the rename in scanned details
13061            pkg.setCodePath(afterCodeFile.getAbsolutePath());
13062            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
13063                    afterCodeFile, pkg.baseCodePath));
13064            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
13065                    afterCodeFile, pkg.splitCodePaths));
13066
13067            // Reflect the rename in app info
13068            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13069            pkg.setApplicationInfoCodePath(pkg.codePath);
13070            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13071            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13072            pkg.setApplicationInfoResourcePath(pkg.codePath);
13073            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13074            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13075
13076            return true;
13077        }
13078
13079        private void setMountPath(String mountPath) {
13080            final File mountFile = new File(mountPath);
13081
13082            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
13083            if (monolithicFile.exists()) {
13084                packagePath = monolithicFile.getAbsolutePath();
13085                if (isFwdLocked()) {
13086                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
13087                } else {
13088                    resourcePath = packagePath;
13089                }
13090            } else {
13091                packagePath = mountFile.getAbsolutePath();
13092                resourcePath = packagePath;
13093            }
13094        }
13095
13096        int doPostInstall(int status, int uid) {
13097            if (status != PackageManager.INSTALL_SUCCEEDED) {
13098                cleanUp();
13099            } else {
13100                final int groupOwner;
13101                final String protectedFile;
13102                if (isFwdLocked()) {
13103                    groupOwner = UserHandle.getSharedAppGid(uid);
13104                    protectedFile = RES_FILE_NAME;
13105                } else {
13106                    groupOwner = -1;
13107                    protectedFile = null;
13108                }
13109
13110                if (uid < Process.FIRST_APPLICATION_UID
13111                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
13112                    Slog.e(TAG, "Failed to finalize " + cid);
13113                    PackageHelper.destroySdDir(cid);
13114                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13115                }
13116
13117                boolean mounted = PackageHelper.isContainerMounted(cid);
13118                if (!mounted) {
13119                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
13120                }
13121            }
13122            return status;
13123        }
13124
13125        private void cleanUp() {
13126            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
13127
13128            // Destroy secure container
13129            PackageHelper.destroySdDir(cid);
13130        }
13131
13132        private List<String> getAllCodePaths() {
13133            final File codeFile = new File(getCodePath());
13134            if (codeFile != null && codeFile.exists()) {
13135                try {
13136                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
13137                    return pkg.getAllCodePaths();
13138                } catch (PackageParserException e) {
13139                    // Ignored; we tried our best
13140                }
13141            }
13142            return Collections.EMPTY_LIST;
13143        }
13144
13145        void cleanUpResourcesLI() {
13146            // Enumerate all code paths before deleting
13147            cleanUpResourcesLI(getAllCodePaths());
13148        }
13149
13150        private void cleanUpResourcesLI(List<String> allCodePaths) {
13151            cleanUp();
13152            removeDexFiles(allCodePaths, instructionSets);
13153        }
13154
13155        String getPackageName() {
13156            return getAsecPackageName(cid);
13157        }
13158
13159        boolean doPostDeleteLI(boolean delete) {
13160            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
13161            final List<String> allCodePaths = getAllCodePaths();
13162            boolean mounted = PackageHelper.isContainerMounted(cid);
13163            if (mounted) {
13164                // Unmount first
13165                if (PackageHelper.unMountSdDir(cid)) {
13166                    mounted = false;
13167                }
13168            }
13169            if (!mounted && delete) {
13170                cleanUpResourcesLI(allCodePaths);
13171            }
13172            return !mounted;
13173        }
13174
13175        @Override
13176        int doPreCopy() {
13177            if (isFwdLocked()) {
13178                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
13179                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
13180                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13181                }
13182            }
13183
13184            return PackageManager.INSTALL_SUCCEEDED;
13185        }
13186
13187        @Override
13188        int doPostCopy(int uid) {
13189            if (isFwdLocked()) {
13190                if (uid < Process.FIRST_APPLICATION_UID
13191                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
13192                                RES_FILE_NAME)) {
13193                    Slog.e(TAG, "Failed to finalize " + cid);
13194                    PackageHelper.destroySdDir(cid);
13195                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13196                }
13197            }
13198
13199            return PackageManager.INSTALL_SUCCEEDED;
13200        }
13201    }
13202
13203    /**
13204     * Logic to handle movement of existing installed applications.
13205     */
13206    class MoveInstallArgs extends InstallArgs {
13207        private File codeFile;
13208        private File resourceFile;
13209
13210        /** New install */
13211        MoveInstallArgs(InstallParams params) {
13212            super(params.origin, params.move, params.observer, params.installFlags,
13213                    params.installerPackageName, params.volumeUuid,
13214                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
13215                    params.grantedRuntimePermissions,
13216                    params.traceMethod, params.traceCookie);
13217        }
13218
13219        int copyApk(IMediaContainerService imcs, boolean temp) {
13220            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
13221                    + move.fromUuid + " to " + move.toUuid);
13222            synchronized (mInstaller) {
13223                try {
13224                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
13225                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
13226                } catch (InstallerException e) {
13227                    Slog.w(TAG, "Failed to move app", e);
13228                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
13229                }
13230            }
13231
13232            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
13233            resourceFile = codeFile;
13234            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
13235
13236            return PackageManager.INSTALL_SUCCEEDED;
13237        }
13238
13239        int doPreInstall(int status) {
13240            if (status != PackageManager.INSTALL_SUCCEEDED) {
13241                cleanUp(move.toUuid);
13242            }
13243            return status;
13244        }
13245
13246        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
13247            if (status != PackageManager.INSTALL_SUCCEEDED) {
13248                cleanUp(move.toUuid);
13249                return false;
13250            }
13251
13252            // Reflect the move in app info
13253            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
13254            pkg.setApplicationInfoCodePath(pkg.codePath);
13255            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
13256            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
13257            pkg.setApplicationInfoResourcePath(pkg.codePath);
13258            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
13259            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
13260
13261            return true;
13262        }
13263
13264        int doPostInstall(int status, int uid) {
13265            if (status == PackageManager.INSTALL_SUCCEEDED) {
13266                cleanUp(move.fromUuid);
13267            } else {
13268                cleanUp(move.toUuid);
13269            }
13270            return status;
13271        }
13272
13273        @Override
13274        String getCodePath() {
13275            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
13276        }
13277
13278        @Override
13279        String getResourcePath() {
13280            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
13281        }
13282
13283        private boolean cleanUp(String volumeUuid) {
13284            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
13285                    move.dataAppName);
13286            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
13287            synchronized (mInstallLock) {
13288                // Clean up both app data and code
13289                removeDataDirsLI(volumeUuid, move.packageName);
13290                removeCodePathLI(codeFile);
13291            }
13292            return true;
13293        }
13294
13295        void cleanUpResourcesLI() {
13296            throw new UnsupportedOperationException();
13297        }
13298
13299        boolean doPostDeleteLI(boolean delete) {
13300            throw new UnsupportedOperationException();
13301        }
13302    }
13303
13304    static String getAsecPackageName(String packageCid) {
13305        int idx = packageCid.lastIndexOf("-");
13306        if (idx == -1) {
13307            return packageCid;
13308        }
13309        return packageCid.substring(0, idx);
13310    }
13311
13312    // Utility method used to create code paths based on package name and available index.
13313    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
13314        String idxStr = "";
13315        int idx = 1;
13316        // Fall back to default value of idx=1 if prefix is not
13317        // part of oldCodePath
13318        if (oldCodePath != null) {
13319            String subStr = oldCodePath;
13320            // Drop the suffix right away
13321            if (suffix != null && subStr.endsWith(suffix)) {
13322                subStr = subStr.substring(0, subStr.length() - suffix.length());
13323            }
13324            // If oldCodePath already contains prefix find out the
13325            // ending index to either increment or decrement.
13326            int sidx = subStr.lastIndexOf(prefix);
13327            if (sidx != -1) {
13328                subStr = subStr.substring(sidx + prefix.length());
13329                if (subStr != null) {
13330                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
13331                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
13332                    }
13333                    try {
13334                        idx = Integer.parseInt(subStr);
13335                        if (idx <= 1) {
13336                            idx++;
13337                        } else {
13338                            idx--;
13339                        }
13340                    } catch(NumberFormatException e) {
13341                    }
13342                }
13343            }
13344        }
13345        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
13346        return prefix + idxStr;
13347    }
13348
13349    private File getNextCodePath(File targetDir, String packageName) {
13350        int suffix = 1;
13351        File result;
13352        do {
13353            result = new File(targetDir, packageName + "-" + suffix);
13354            suffix++;
13355        } while (result.exists());
13356        return result;
13357    }
13358
13359    // Utility method that returns the relative package path with respect
13360    // to the installation directory. Like say for /data/data/com.test-1.apk
13361    // string com.test-1 is returned.
13362    static String deriveCodePathName(String codePath) {
13363        if (codePath == null) {
13364            return null;
13365        }
13366        final File codeFile = new File(codePath);
13367        final String name = codeFile.getName();
13368        if (codeFile.isDirectory()) {
13369            return name;
13370        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
13371            final int lastDot = name.lastIndexOf('.');
13372            return name.substring(0, lastDot);
13373        } else {
13374            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
13375            return null;
13376        }
13377    }
13378
13379    static class PackageInstalledInfo {
13380        String name;
13381        int uid;
13382        // The set of users that originally had this package installed.
13383        int[] origUsers;
13384        // The set of users that now have this package installed.
13385        int[] newUsers;
13386        PackageParser.Package pkg;
13387        int returnCode;
13388        String returnMsg;
13389        PackageRemovedInfo removedInfo;
13390        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
13391
13392        public void setError(int code, String msg) {
13393            setReturnCode(code);
13394            setReturnMessage(msg);
13395            Slog.w(TAG, msg);
13396        }
13397
13398        public void setError(String msg, PackageParserException e) {
13399            setReturnCode(e.error);
13400            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13401            Slog.w(TAG, msg, e);
13402        }
13403
13404        public void setError(String msg, PackageManagerException e) {
13405            returnCode = e.error;
13406            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
13407            Slog.w(TAG, msg, e);
13408        }
13409
13410        public void setReturnCode(int returnCode) {
13411            this.returnCode = returnCode;
13412            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13413            for (int i = 0; i < childCount; i++) {
13414                addedChildPackages.valueAt(i).returnCode = returnCode;
13415            }
13416        }
13417
13418        private void setReturnMessage(String returnMsg) {
13419            this.returnMsg = returnMsg;
13420            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
13421            for (int i = 0; i < childCount; i++) {
13422                addedChildPackages.valueAt(i).returnMsg = returnMsg;
13423            }
13424        }
13425
13426        // In some error cases we want to convey more info back to the observer
13427        String origPackage;
13428        String origPermission;
13429    }
13430
13431    /*
13432     * Install a non-existing package.
13433     */
13434    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
13435            UserHandle user, String installerPackageName, String volumeUuid,
13436            PackageInstalledInfo res) {
13437        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
13438
13439        // Remember this for later, in case we need to rollback this install
13440        String pkgName = pkg.packageName;
13441
13442        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
13443
13444        synchronized(mPackages) {
13445            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
13446                // A package with the same name is already installed, though
13447                // it has been renamed to an older name.  The package we
13448                // are trying to install should be installed as an update to
13449                // the existing one, but that has not been requested, so bail.
13450                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13451                        + " without first uninstalling package running as "
13452                        + mSettings.mRenamedPackages.get(pkgName));
13453                return;
13454            }
13455            if (mPackages.containsKey(pkgName)) {
13456                // Don't allow installation over an existing package with the same name.
13457                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
13458                        + " without first uninstalling.");
13459                return;
13460            }
13461        }
13462
13463        try {
13464            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
13465                    System.currentTimeMillis(), user);
13466
13467            updateSettingsLI(newPackage, installerPackageName, null, res, user);
13468
13469            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13470                prepareAppDataAfterInstall(newPackage);
13471
13472            } else {
13473                // Remove package from internal structures, but keep around any
13474                // data that might have already existed
13475                deletePackageLI(pkgName, UserHandle.ALL, false, null,
13476                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
13477            }
13478        } catch (PackageManagerException e) {
13479            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13480        }
13481
13482        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
13483    }
13484
13485    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
13486        // Can't rotate keys during boot or if sharedUser.
13487        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
13488                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
13489            return false;
13490        }
13491        // app is using upgradeKeySets; make sure all are valid
13492        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13493        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
13494        for (int i = 0; i < upgradeKeySets.length; i++) {
13495            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
13496                Slog.wtf(TAG, "Package "
13497                         + (oldPs.name != null ? oldPs.name : "<null>")
13498                         + " contains upgrade-key-set reference to unknown key-set: "
13499                         + upgradeKeySets[i]
13500                         + " reverting to signatures check.");
13501                return false;
13502            }
13503        }
13504        return true;
13505    }
13506
13507    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
13508        // Upgrade keysets are being used.  Determine if new package has a superset of the
13509        // required keys.
13510        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
13511        KeySetManagerService ksms = mSettings.mKeySetManagerService;
13512        for (int i = 0; i < upgradeKeySets.length; i++) {
13513            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
13514            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
13515                return true;
13516            }
13517        }
13518        return false;
13519    }
13520
13521    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
13522            UserHandle user, String installerPackageName, PackageInstalledInfo res) {
13523        final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0;
13524
13525        final PackageParser.Package oldPackage;
13526        final String pkgName = pkg.packageName;
13527        final int[] allUsers;
13528        final boolean weFroze;
13529
13530        // First find the old package info and check signatures
13531        synchronized(mPackages) {
13532            oldPackage = mPackages.get(pkgName);
13533            final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp();
13534            if (isEphemeral && !oldIsEphemeral) {
13535                // can't downgrade from full to ephemeral
13536                Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName);
13537                res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
13538                return;
13539            }
13540            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
13541            final PackageSetting ps = mSettings.mPackages.get(pkgName);
13542            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
13543                if (!checkUpgradeKeySetLP(ps, pkg)) {
13544                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13545                            "New package not signed by keys specified by upgrade-keysets: "
13546                                    + pkgName);
13547                    return;
13548                }
13549            } else {
13550                // default to original signature matching
13551                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
13552                        != PackageManager.SIGNATURE_MATCH) {
13553                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
13554                            "New package has a different signature: " + pkgName);
13555                    return;
13556                }
13557            }
13558
13559            // In case of rollback, remember per-user/profile install state
13560            allUsers = sUserManager.getUserIds();
13561
13562            // Mark the app as frozen to prevent launching during the upgrade
13563            // process, and then kill all running instances
13564            if (!ps.frozen) {
13565                ps.frozen = true;
13566                weFroze = true;
13567            } else {
13568                weFroze = false;
13569            }
13570        }
13571
13572        try {
13573            replacePackageDirtyLI(pkg, oldPackage, parseFlags, scanFlags, user, allUsers,
13574                    installerPackageName, res);
13575        } finally {
13576            // Regardless of success or failure of upgrade steps above, always
13577            // unfreeze the package if we froze it
13578            if (weFroze) {
13579                unfreezePackage(pkgName);
13580            }
13581        }
13582    }
13583
13584    private void replacePackageDirtyLI(PackageParser.Package pkg, PackageParser.Package oldPackage,
13585            int parseFlags, int scanFlags, UserHandle user, int[] allUsers,
13586            String installerPackageName, PackageInstalledInfo res) {
13587        // Update what is removed
13588        res.removedInfo = new PackageRemovedInfo();
13589        res.removedInfo.uid = oldPackage.applicationInfo.uid;
13590        res.removedInfo.removedPackage = oldPackage.packageName;
13591        res.removedInfo.isUpdate = true;
13592        final int childCount = (oldPackage.childPackages != null)
13593                ? oldPackage.childPackages.size() : 0;
13594        for (int i = 0; i < childCount; i++) {
13595            boolean childPackageUpdated = false;
13596            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
13597            if (res.addedChildPackages != null) {
13598                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
13599                if (childRes != null) {
13600                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
13601                    childRes.removedInfo.removedPackage = childPkg.packageName;
13602                    childRes.removedInfo.isUpdate = true;
13603                    childPackageUpdated = true;
13604                }
13605            }
13606            if (!childPackageUpdated) {
13607                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo();
13608                childRemovedRes.removedPackage = childPkg.packageName;
13609                childRemovedRes.isUpdate = false;
13610                childRemovedRes.dataRemoved = true;
13611                synchronized (mPackages) {
13612                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
13613                    if (childPs != null) {
13614                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
13615                    }
13616                }
13617                if (res.removedInfo.removedChildPackages == null) {
13618                    res.removedInfo.removedChildPackages = new ArrayMap<>();
13619                }
13620                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
13621            }
13622        }
13623
13624        boolean sysPkg = (isSystemApp(oldPackage));
13625        if (sysPkg) {
13626            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13627                    user, allUsers, installerPackageName, res);
13628        } else {
13629            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
13630                    user, allUsers, installerPackageName, res);
13631        }
13632    }
13633
13634    public List<String> getPreviousCodePaths(String packageName) {
13635        final PackageSetting ps = mSettings.mPackages.get(packageName);
13636        final List<String> result = new ArrayList<String>();
13637        if (ps != null && ps.oldCodePaths != null) {
13638            result.addAll(ps.oldCodePaths);
13639        }
13640        return result;
13641    }
13642
13643    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
13644            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13645            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13646        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
13647                + deletedPackage);
13648
13649        String pkgName = deletedPackage.packageName;
13650        boolean deletedPkg = true;
13651        boolean addedPkg = false;
13652        boolean updatedSettings = false;
13653        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
13654        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
13655                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
13656
13657        final long origUpdateTime = (pkg.mExtras != null)
13658                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
13659
13660        // First delete the existing package while retaining the data directory
13661        if (!deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13662                res.removedInfo, true, pkg)) {
13663            // If the existing package wasn't successfully deleted
13664            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
13665            deletedPkg = false;
13666        } else {
13667            // Successfully deleted the old package; proceed with replace.
13668
13669            // If deleted package lived in a container, give users a chance to
13670            // relinquish resources before killing.
13671            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
13672                if (DEBUG_INSTALL) {
13673                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
13674                }
13675                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
13676                final ArrayList<String> pkgList = new ArrayList<String>(1);
13677                pkgList.add(deletedPackage.applicationInfo.packageName);
13678                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
13679            }
13680
13681            deleteCodeCacheDirsLI(pkg);
13682            deleteProfilesLI(pkg, /*destroy*/ false);
13683
13684            try {
13685                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
13686                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
13687                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13688
13689                // Update the in-memory copy of the previous code paths.
13690                PackageSetting ps = mSettings.mPackages.get(pkgName);
13691                if (!killApp) {
13692                    if (ps.oldCodePaths == null) {
13693                        ps.oldCodePaths = new ArraySet<>();
13694                    }
13695                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
13696                    if (deletedPackage.splitCodePaths != null) {
13697                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
13698                    }
13699                } else {
13700                    ps.oldCodePaths = null;
13701                }
13702                if (ps.childPackageNames != null) {
13703                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
13704                        final String childPkgName = ps.childPackageNames.get(i);
13705                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
13706                        childPs.oldCodePaths = ps.oldCodePaths;
13707                    }
13708                }
13709                prepareAppDataAfterInstall(newPackage);
13710                addedPkg = true;
13711            } catch (PackageManagerException e) {
13712                res.setError("Package couldn't be installed in " + pkg.codePath, e);
13713            }
13714        }
13715
13716        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13717            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
13718
13719            // Revert all internal state mutations and added folders for the failed install
13720            if (addedPkg) {
13721                deletePackageLI(pkgName, null, true, allUsers, deleteFlags,
13722                        res.removedInfo, true, null);
13723            }
13724
13725            // Restore the old package
13726            if (deletedPkg) {
13727                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
13728                File restoreFile = new File(deletedPackage.codePath);
13729                // Parse old package
13730                boolean oldExternal = isExternal(deletedPackage);
13731                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
13732                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
13733                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
13734                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
13735                try {
13736                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
13737                            null);
13738                } catch (PackageManagerException e) {
13739                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
13740                            + e.getMessage());
13741                    return;
13742                }
13743
13744                synchronized (mPackages) {
13745                    // Ensure the installer package name up to date
13746                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13747
13748                    // Update permissions for restored package
13749                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13750
13751                    mSettings.writeLPr();
13752                }
13753
13754                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
13755            }
13756        } else {
13757            synchronized (mPackages) {
13758                PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName);
13759                if (ps != null) {
13760                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
13761                    if (res.removedInfo.removedChildPackages != null) {
13762                        final int childCount = res.removedInfo.removedChildPackages.size();
13763                        // Iterate in reverse as we may modify the collection
13764                        for (int i = childCount - 1; i >= 0; i--) {
13765                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
13766                            if (res.addedChildPackages.containsKey(childPackageName)) {
13767                                res.removedInfo.removedChildPackages.removeAt(i);
13768                            } else {
13769                                PackageRemovedInfo childInfo = res.removedInfo
13770                                        .removedChildPackages.valueAt(i);
13771                                childInfo.removedForAllUsers = mPackages.get(
13772                                        childInfo.removedPackage) == null;
13773                            }
13774                        }
13775                    }
13776                }
13777            }
13778        }
13779    }
13780
13781    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
13782            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
13783            int[] allUsers, String installerPackageName, PackageInstalledInfo res) {
13784        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
13785                + ", old=" + deletedPackage);
13786
13787        final boolean disabledSystem;
13788
13789        // Set the system/privileged flags as needed
13790        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
13791        if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
13792                != 0) {
13793            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
13794        }
13795
13796        // Kill package processes including services, providers, etc.
13797        killPackage(deletedPackage, "replace sys pkg");
13798
13799        // Remove existing system package
13800        removePackageLI(deletedPackage, true);
13801
13802        disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
13803        if (!disabledSystem) {
13804            // We didn't need to disable the .apk as a current system package,
13805            // which means we are replacing another update that is already
13806            // installed.  We need to make sure to delete the older one's .apk.
13807            res.removedInfo.args = createInstallArgsForExisting(0,
13808                    deletedPackage.applicationInfo.getCodePath(),
13809                    deletedPackage.applicationInfo.getResourcePath(),
13810                    getAppDexInstructionSets(deletedPackage.applicationInfo));
13811        } else {
13812            res.removedInfo.args = null;
13813        }
13814
13815        // Successfully disabled the old package. Now proceed with re-installation
13816        deleteCodeCacheDirsLI(pkg);
13817        deleteProfilesLI(pkg, /*destroy*/ false);
13818
13819        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
13820        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
13821                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
13822
13823        PackageParser.Package newPackage = null;
13824        try {
13825            // Add the package to the internal data structures
13826            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
13827
13828            // Set the update and install times
13829            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
13830            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
13831                    System.currentTimeMillis());
13832
13833            // Check for shared user id changes
13834            String invalidPackageName = getParentOrChildPackageChangedSharedUser(
13835                    deletedPackage, newPackage);
13836            if (invalidPackageName != null) {
13837                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
13838                        "Forbidding shared user change from " + deletedPkgSetting.sharedUser
13839                                + " to " + invalidPackageName);
13840            }
13841
13842            // Update the package dynamic state if succeeded
13843            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
13844                // Now that the install succeeded make sure we remove data
13845                // directories for any child package the update removed.
13846                final int deletedChildCount = (deletedPackage.childPackages != null)
13847                        ? deletedPackage.childPackages.size() : 0;
13848                final int newChildCount = (newPackage.childPackages != null)
13849                        ? newPackage.childPackages.size() : 0;
13850                for (int i = 0; i < deletedChildCount; i++) {
13851                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
13852                    boolean childPackageDeleted = true;
13853                    for (int j = 0; j < newChildCount; j++) {
13854                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
13855                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
13856                            childPackageDeleted = false;
13857                            break;
13858                        }
13859                    }
13860                    if (childPackageDeleted) {
13861                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
13862                                deletedChildPkg.packageName);
13863                        if (ps != null && res.removedInfo.removedChildPackages != null) {
13864                            PackageRemovedInfo removedChildRes = res.removedInfo
13865                                    .removedChildPackages.get(deletedChildPkg.packageName);
13866                            removePackageDataLI(ps, allUsers, removedChildRes, 0, false);
13867                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
13868                        }
13869                    }
13870                }
13871
13872                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user);
13873                prepareAppDataAfterInstall(newPackage);
13874            }
13875        } catch (PackageManagerException e) {
13876            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
13877            res.setError("Package couldn't be installed in " + pkg.codePath, e);
13878        }
13879
13880        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
13881            // Re installation failed. Restore old information
13882            // Remove new pkg information
13883            if (newPackage != null) {
13884                removeInstalledPackageLI(newPackage, true);
13885            }
13886            // Add back the old system package
13887            try {
13888                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
13889            } catch (PackageManagerException e) {
13890                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
13891            }
13892
13893            synchronized (mPackages) {
13894                if (disabledSystem) {
13895                    enableSystemPackageLPw(deletedPackage);
13896                }
13897
13898                // Ensure the installer package name up to date
13899                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
13900
13901                // Update permissions for restored package
13902                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
13903
13904                mSettings.writeLPr();
13905            }
13906
13907            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
13908                    + " after failed upgrade");
13909        }
13910    }
13911
13912    /**
13913     * Checks whether the parent or any of the child packages have a change shared
13914     * user. For a package to be a valid update the shred users of the parent and
13915     * the children should match. We may later support changing child shared users.
13916     * @param oldPkg The updated package.
13917     * @param newPkg The update package.
13918     * @return The shared user that change between the versions.
13919     */
13920    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
13921            PackageParser.Package newPkg) {
13922        // Check parent shared user
13923        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
13924            return newPkg.packageName;
13925        }
13926        // Check child shared users
13927        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13928        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
13929        for (int i = 0; i < newChildCount; i++) {
13930            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
13931            // If this child was present, did it have the same shared user?
13932            for (int j = 0; j < oldChildCount; j++) {
13933                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
13934                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
13935                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
13936                    return newChildPkg.packageName;
13937                }
13938            }
13939        }
13940        return null;
13941    }
13942
13943    private void removeNativeBinariesLI(PackageSetting ps) {
13944        // Remove the lib path for the parent package
13945        if (ps != null) {
13946            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
13947            // Remove the lib path for the child packages
13948            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
13949            for (int i = 0; i < childCount; i++) {
13950                PackageSetting childPs = null;
13951                synchronized (mPackages) {
13952                    childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
13953                }
13954                if (childPs != null) {
13955                    NativeLibraryHelper.removeNativeBinariesLI(childPs
13956                            .legacyNativeLibraryPathString);
13957                }
13958            }
13959        }
13960    }
13961
13962    private void enableSystemPackageLPw(PackageParser.Package pkg) {
13963        // Enable the parent package
13964        mSettings.enableSystemPackageLPw(pkg.packageName);
13965        // Enable the child packages
13966        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13967        for (int i = 0; i < childCount; i++) {
13968            PackageParser.Package childPkg = pkg.childPackages.get(i);
13969            mSettings.enableSystemPackageLPw(childPkg.packageName);
13970        }
13971    }
13972
13973    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
13974            PackageParser.Package newPkg) {
13975        // Disable the parent package (parent always replaced)
13976        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
13977        // Disable the child packages
13978        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
13979        for (int i = 0; i < childCount; i++) {
13980            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
13981            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
13982            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
13983        }
13984        return disabled;
13985    }
13986
13987    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
13988            String installerPackageName) {
13989        // Enable the parent package
13990        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
13991        // Enable the child packages
13992        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
13993        for (int i = 0; i < childCount; i++) {
13994            PackageParser.Package childPkg = pkg.childPackages.get(i);
13995            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
13996        }
13997    }
13998
13999    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
14000        // Collect all used permissions in the UID
14001        ArraySet<String> usedPermissions = new ArraySet<>();
14002        final int packageCount = su.packages.size();
14003        for (int i = 0; i < packageCount; i++) {
14004            PackageSetting ps = su.packages.valueAt(i);
14005            if (ps.pkg == null) {
14006                continue;
14007            }
14008            final int requestedPermCount = ps.pkg.requestedPermissions.size();
14009            for (int j = 0; j < requestedPermCount; j++) {
14010                String permission = ps.pkg.requestedPermissions.get(j);
14011                BasePermission bp = mSettings.mPermissions.get(permission);
14012                if (bp != null) {
14013                    usedPermissions.add(permission);
14014                }
14015            }
14016        }
14017
14018        PermissionsState permissionsState = su.getPermissionsState();
14019        // Prune install permissions
14020        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
14021        final int installPermCount = installPermStates.size();
14022        for (int i = installPermCount - 1; i >= 0;  i--) {
14023            PermissionState permissionState = installPermStates.get(i);
14024            if (!usedPermissions.contains(permissionState.getName())) {
14025                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14026                if (bp != null) {
14027                    permissionsState.revokeInstallPermission(bp);
14028                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
14029                            PackageManager.MASK_PERMISSION_FLAGS, 0);
14030                }
14031            }
14032        }
14033
14034        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
14035
14036        // Prune runtime permissions
14037        for (int userId : allUserIds) {
14038            List<PermissionState> runtimePermStates = permissionsState
14039                    .getRuntimePermissionStates(userId);
14040            final int runtimePermCount = runtimePermStates.size();
14041            for (int i = runtimePermCount - 1; i >= 0; i--) {
14042                PermissionState permissionState = runtimePermStates.get(i);
14043                if (!usedPermissions.contains(permissionState.getName())) {
14044                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
14045                    if (bp != null) {
14046                        permissionsState.revokeRuntimePermission(bp, userId);
14047                        permissionsState.updatePermissionFlags(bp, userId,
14048                                PackageManager.MASK_PERMISSION_FLAGS, 0);
14049                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
14050                                runtimePermissionChangedUserIds, userId);
14051                    }
14052                }
14053            }
14054        }
14055
14056        return runtimePermissionChangedUserIds;
14057    }
14058
14059    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
14060            int[] allUsers, PackageInstalledInfo res, UserHandle user) {
14061        // Update the parent package setting
14062        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
14063                res, user);
14064        // Update the child packages setting
14065        final int childCount = (newPackage.childPackages != null)
14066                ? newPackage.childPackages.size() : 0;
14067        for (int i = 0; i < childCount; i++) {
14068            PackageParser.Package childPackage = newPackage.childPackages.get(i);
14069            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
14070            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
14071                    childRes.origUsers, childRes, user);
14072        }
14073    }
14074
14075    private void updateSettingsInternalLI(PackageParser.Package newPackage,
14076            String installerPackageName, int[] allUsers, int[] installedForUsers,
14077            PackageInstalledInfo res, UserHandle user) {
14078        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
14079
14080        String pkgName = newPackage.packageName;
14081        synchronized (mPackages) {
14082            //write settings. the installStatus will be incomplete at this stage.
14083            //note that the new package setting would have already been
14084            //added to mPackages. It hasn't been persisted yet.
14085            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
14086            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14087            mSettings.writeLPr();
14088            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14089        }
14090
14091        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
14092        synchronized (mPackages) {
14093            updatePermissionsLPw(newPackage.packageName, newPackage,
14094                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
14095                            ? UPDATE_PERMISSIONS_ALL : 0));
14096            // For system-bundled packages, we assume that installing an upgraded version
14097            // of the package implies that the user actually wants to run that new code,
14098            // so we enable the package.
14099            PackageSetting ps = mSettings.mPackages.get(pkgName);
14100            final int userId = user.getIdentifier();
14101            if (ps != null) {
14102                if (isSystemApp(newPackage)) {
14103                    if (DEBUG_INSTALL) {
14104                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
14105                    }
14106                    // Enable system package for requested users
14107                    if (res.origUsers != null) {
14108                        for (int origUserId : res.origUsers) {
14109                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
14110                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
14111                                        origUserId, installerPackageName);
14112                            }
14113                        }
14114                    }
14115                    // Also convey the prior install/uninstall state
14116                    if (allUsers != null && installedForUsers != null) {
14117                        for (int currentUserId : allUsers) {
14118                            final boolean installed = ArrayUtils.contains(
14119                                    installedForUsers, currentUserId);
14120                            if (DEBUG_INSTALL) {
14121                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
14122                            }
14123                            ps.setInstalled(installed, currentUserId);
14124                        }
14125                        // these install state changes will be persisted in the
14126                        // upcoming call to mSettings.writeLPr().
14127                    }
14128                }
14129                // It's implied that when a user requests installation, they want the app to be
14130                // installed and enabled.
14131                if (userId != UserHandle.USER_ALL) {
14132                    ps.setInstalled(true, userId);
14133                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
14134                }
14135            }
14136            res.name = pkgName;
14137            res.uid = newPackage.applicationInfo.uid;
14138            res.pkg = newPackage;
14139            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
14140            mSettings.setInstallerPackageName(pkgName, installerPackageName);
14141            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14142            //to update install status
14143            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
14144            mSettings.writeLPr();
14145            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14146        }
14147
14148        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14149    }
14150
14151    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
14152        try {
14153            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
14154            installPackageLI(args, res);
14155        } finally {
14156            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14157        }
14158    }
14159
14160    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
14161        final int installFlags = args.installFlags;
14162        final String installerPackageName = args.installerPackageName;
14163        final String volumeUuid = args.volumeUuid;
14164        final File tmpPackageFile = new File(args.getCodePath());
14165        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
14166        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
14167                || (args.volumeUuid != null));
14168        final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0);
14169        boolean replace = false;
14170        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
14171        if (args.move != null) {
14172            // moving a complete application; perform an initial scan on the new install location
14173            scanFlags |= SCAN_INITIAL;
14174        }
14175        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
14176            scanFlags |= SCAN_DONT_KILL_APP;
14177        }
14178
14179        // Result object to be returned
14180        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14181
14182        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
14183
14184        // Sanity check
14185        if (ephemeral && (forwardLocked || onExternal)) {
14186            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
14187                    + " external=" + onExternal);
14188            res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID);
14189            return;
14190        }
14191
14192        // Retrieve PackageSettings and parse package
14193        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
14194                | PackageParser.PARSE_ENFORCE_CODE
14195                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
14196                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
14197                | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0);
14198        PackageParser pp = new PackageParser();
14199        pp.setSeparateProcesses(mSeparateProcesses);
14200        pp.setDisplayMetrics(mMetrics);
14201
14202        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
14203        final PackageParser.Package pkg;
14204        try {
14205            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
14206        } catch (PackageParserException e) {
14207            res.setError("Failed parse during installPackageLI", e);
14208            return;
14209        } finally {
14210            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14211        }
14212
14213        // If we are installing a clustered package add results for the children
14214        if (pkg.childPackages != null) {
14215            synchronized (mPackages) {
14216                final int childCount = pkg.childPackages.size();
14217                for (int i = 0; i < childCount; i++) {
14218                    PackageParser.Package childPkg = pkg.childPackages.get(i);
14219                    PackageInstalledInfo childRes = new PackageInstalledInfo();
14220                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
14221                    childRes.pkg = childPkg;
14222                    childRes.name = childPkg.packageName;
14223                    PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14224                    if (childPs != null) {
14225                        childRes.origUsers = childPs.queryInstalledUsers(
14226                                sUserManager.getUserIds(), true);
14227                    }
14228                    if ((mPackages.containsKey(childPkg.packageName))) {
14229                        childRes.removedInfo = new PackageRemovedInfo();
14230                        childRes.removedInfo.removedPackage = childPkg.packageName;
14231                    }
14232                    if (res.addedChildPackages == null) {
14233                        res.addedChildPackages = new ArrayMap<>();
14234                    }
14235                    res.addedChildPackages.put(childPkg.packageName, childRes);
14236                }
14237            }
14238        }
14239
14240        // If package doesn't declare API override, mark that we have an install
14241        // time CPU ABI override.
14242        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
14243            pkg.cpuAbiOverride = args.abiOverride;
14244        }
14245
14246        String pkgName = res.name = pkg.packageName;
14247        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
14248            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
14249                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
14250                return;
14251            }
14252        }
14253
14254        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
14255        try {
14256            PackageParser.collectCertificates(pkg, parseFlags);
14257        } catch (PackageParserException e) {
14258            res.setError("Failed collect during installPackageLI", e);
14259            return;
14260        } finally {
14261            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14262        }
14263
14264        // Get rid of all references to package scan path via parser.
14265        pp = null;
14266        String oldCodePath = null;
14267        boolean systemApp = false;
14268        synchronized (mPackages) {
14269            // Check if installing already existing package
14270            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
14271                String oldName = mSettings.mRenamedPackages.get(pkgName);
14272                if (pkg.mOriginalPackages != null
14273                        && pkg.mOriginalPackages.contains(oldName)
14274                        && mPackages.containsKey(oldName)) {
14275                    // This package is derived from an original package,
14276                    // and this device has been updating from that original
14277                    // name.  We must continue using the original name, so
14278                    // rename the new package here.
14279                    pkg.setPackageName(oldName);
14280                    pkgName = pkg.packageName;
14281                    replace = true;
14282                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
14283                            + oldName + " pkgName=" + pkgName);
14284                } else if (mPackages.containsKey(pkgName)) {
14285                    // This package, under its official name, already exists
14286                    // on the device; we should replace it.
14287                    replace = true;
14288                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
14289                }
14290
14291                // Child packages are installed through the parent package
14292                if (pkg.parentPackage != null) {
14293                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14294                            "Package " + pkg.packageName + " is child of package "
14295                                    + pkg.parentPackage.parentPackage + ". Child packages "
14296                                    + "can be updated only through the parent package.");
14297                    return;
14298                }
14299
14300                if (replace) {
14301                    // Prevent apps opting out from runtime permissions
14302                    PackageParser.Package oldPackage = mPackages.get(pkgName);
14303                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
14304                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
14305                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
14306                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
14307                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
14308                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
14309                                        + " doesn't support runtime permissions but the old"
14310                                        + " target SDK " + oldTargetSdk + " does.");
14311                        return;
14312                    }
14313
14314                    // Prevent installing of child packages
14315                    if (oldPackage.parentPackage != null) {
14316                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
14317                                "Package " + pkg.packageName + " is child of package "
14318                                        + oldPackage.parentPackage + ". Child packages "
14319                                        + "can be updated only through the parent package.");
14320                        return;
14321                    }
14322                }
14323            }
14324
14325            PackageSetting ps = mSettings.mPackages.get(pkgName);
14326            if (ps != null) {
14327                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
14328
14329                // Quick sanity check that we're signed correctly if updating;
14330                // we'll check this again later when scanning, but we want to
14331                // bail early here before tripping over redefined permissions.
14332                if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
14333                    if (!checkUpgradeKeySetLP(ps, pkg)) {
14334                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
14335                                + pkg.packageName + " upgrade keys do not match the "
14336                                + "previously installed version");
14337                        return;
14338                    }
14339                } else {
14340                    try {
14341                        verifySignaturesLP(ps, pkg);
14342                    } catch (PackageManagerException e) {
14343                        res.setError(e.error, e.getMessage());
14344                        return;
14345                    }
14346                }
14347
14348                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
14349                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
14350                    systemApp = (ps.pkg.applicationInfo.flags &
14351                            ApplicationInfo.FLAG_SYSTEM) != 0;
14352                }
14353                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14354            }
14355
14356            // Check whether the newly-scanned package wants to define an already-defined perm
14357            int N = pkg.permissions.size();
14358            for (int i = N-1; i >= 0; i--) {
14359                PackageParser.Permission perm = pkg.permissions.get(i);
14360                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
14361                if (bp != null) {
14362                    // If the defining package is signed with our cert, it's okay.  This
14363                    // also includes the "updating the same package" case, of course.
14364                    // "updating same package" could also involve key-rotation.
14365                    final boolean sigsOk;
14366                    if (bp.sourcePackage.equals(pkg.packageName)
14367                            && (bp.packageSetting instanceof PackageSetting)
14368                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
14369                                    scanFlags))) {
14370                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
14371                    } else {
14372                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
14373                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
14374                    }
14375                    if (!sigsOk) {
14376                        // If the owning package is the system itself, we log but allow
14377                        // install to proceed; we fail the install on all other permission
14378                        // redefinitions.
14379                        if (!bp.sourcePackage.equals("android")) {
14380                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
14381                                    + pkg.packageName + " attempting to redeclare permission "
14382                                    + perm.info.name + " already owned by " + bp.sourcePackage);
14383                            res.origPermission = perm.info.name;
14384                            res.origPackage = bp.sourcePackage;
14385                            return;
14386                        } else {
14387                            Slog.w(TAG, "Package " + pkg.packageName
14388                                    + " attempting to redeclare system permission "
14389                                    + perm.info.name + "; ignoring new declaration");
14390                            pkg.permissions.remove(i);
14391                        }
14392                    }
14393                }
14394            }
14395        }
14396
14397        if (systemApp) {
14398            if (onExternal) {
14399                // Abort update; system app can't be replaced with app on sdcard
14400                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
14401                        "Cannot install updates to system apps on sdcard");
14402                return;
14403            } else if (ephemeral) {
14404                // Abort update; system app can't be replaced with an ephemeral app
14405                res.setError(INSTALL_FAILED_EPHEMERAL_INVALID,
14406                        "Cannot update a system app with an ephemeral app");
14407                return;
14408            }
14409        }
14410
14411        if (args.move != null) {
14412            // We did an in-place move, so dex is ready to roll
14413            scanFlags |= SCAN_NO_DEX;
14414            scanFlags |= SCAN_MOVE;
14415
14416            synchronized (mPackages) {
14417                final PackageSetting ps = mSettings.mPackages.get(pkgName);
14418                if (ps == null) {
14419                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
14420                            "Missing settings for moved package " + pkgName);
14421                }
14422
14423                // We moved the entire application as-is, so bring over the
14424                // previously derived ABI information.
14425                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
14426                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
14427            }
14428
14429        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
14430            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
14431            scanFlags |= SCAN_NO_DEX;
14432
14433            try {
14434                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
14435                    args.abiOverride : pkg.cpuAbiOverride);
14436                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
14437                        true /* extract libs */);
14438            } catch (PackageManagerException pme) {
14439                Slog.e(TAG, "Error deriving application ABI", pme);
14440                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
14441                return;
14442            }
14443
14444
14445            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
14446            // Do not run PackageDexOptimizer through the local performDexOpt
14447            // method because `pkg` is not in `mPackages` yet.
14448            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */,
14449                    false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL));
14450            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
14451            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
14452                String msg = "Extracking package failed for " + pkgName;
14453                res.setError(INSTALL_FAILED_DEXOPT, msg);
14454                return;
14455            }
14456        }
14457
14458        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
14459            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
14460            return;
14461        }
14462
14463        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
14464
14465        if (replace) {
14466            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
14467                    installerPackageName, res);
14468        } else {
14469            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
14470                    args.user, installerPackageName, volumeUuid, res);
14471        }
14472        synchronized (mPackages) {
14473            final PackageSetting ps = mSettings.mPackages.get(pkgName);
14474            if (ps != null) {
14475                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
14476            }
14477
14478            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14479            for (int i = 0; i < childCount; i++) {
14480                PackageParser.Package childPkg = pkg.childPackages.get(i);
14481                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
14482                PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName);
14483                if (childPs != null) {
14484                    childRes.newUsers = childPs.queryInstalledUsers(
14485                            sUserManager.getUserIds(), true);
14486                }
14487            }
14488        }
14489    }
14490
14491    private void startIntentFilterVerifications(int userId, boolean replacing,
14492            PackageParser.Package pkg) {
14493        if (mIntentFilterVerifierComponent == null) {
14494            Slog.w(TAG, "No IntentFilter verification will not be done as "
14495                    + "there is no IntentFilterVerifier available!");
14496            return;
14497        }
14498
14499        final int verifierUid = getPackageUid(
14500                mIntentFilterVerifierComponent.getPackageName(),
14501                MATCH_DEBUG_TRIAGED_MISSING,
14502                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
14503
14504        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14505        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
14506        mHandler.sendMessage(msg);
14507
14508        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
14509        for (int i = 0; i < childCount; i++) {
14510            PackageParser.Package childPkg = pkg.childPackages.get(i);
14511            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
14512            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
14513            mHandler.sendMessage(msg);
14514        }
14515    }
14516
14517    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
14518            PackageParser.Package pkg) {
14519        int size = pkg.activities.size();
14520        if (size == 0) {
14521            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14522                    "No activity, so no need to verify any IntentFilter!");
14523            return;
14524        }
14525
14526        final boolean hasDomainURLs = hasDomainURLs(pkg);
14527        if (!hasDomainURLs) {
14528            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14529                    "No domain URLs, so no need to verify any IntentFilter!");
14530            return;
14531        }
14532
14533        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
14534                + " if any IntentFilter from the " + size
14535                + " Activities needs verification ...");
14536
14537        int count = 0;
14538        final String packageName = pkg.packageName;
14539
14540        synchronized (mPackages) {
14541            // If this is a new install and we see that we've already run verification for this
14542            // package, we have nothing to do: it means the state was restored from backup.
14543            if (!replacing) {
14544                IntentFilterVerificationInfo ivi =
14545                        mSettings.getIntentFilterVerificationLPr(packageName);
14546                if (ivi != null) {
14547                    if (DEBUG_DOMAIN_VERIFICATION) {
14548                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
14549                                + ivi.getStatusString());
14550                    }
14551                    return;
14552                }
14553            }
14554
14555            // If any filters need to be verified, then all need to be.
14556            boolean needToVerify = false;
14557            for (PackageParser.Activity a : pkg.activities) {
14558                for (ActivityIntentInfo filter : a.intents) {
14559                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
14560                        if (DEBUG_DOMAIN_VERIFICATION) {
14561                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
14562                        }
14563                        needToVerify = true;
14564                        break;
14565                    }
14566                }
14567            }
14568
14569            if (needToVerify) {
14570                final int verificationId = mIntentFilterVerificationToken++;
14571                for (PackageParser.Activity a : pkg.activities) {
14572                    for (ActivityIntentInfo filter : a.intents) {
14573                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
14574                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
14575                                    "Verification needed for IntentFilter:" + filter.toString());
14576                            mIntentFilterVerifier.addOneIntentFilterVerification(
14577                                    verifierUid, userId, verificationId, filter, packageName);
14578                            count++;
14579                        }
14580                    }
14581                }
14582            }
14583        }
14584
14585        if (count > 0) {
14586            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
14587                    + " IntentFilter verification" + (count > 1 ? "s" : "")
14588                    +  " for userId:" + userId);
14589            mIntentFilterVerifier.startVerifications(userId);
14590        } else {
14591            if (DEBUG_DOMAIN_VERIFICATION) {
14592                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
14593            }
14594        }
14595    }
14596
14597    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
14598        final ComponentName cn  = filter.activity.getComponentName();
14599        final String packageName = cn.getPackageName();
14600
14601        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
14602                packageName);
14603        if (ivi == null) {
14604            return true;
14605        }
14606        int status = ivi.getStatus();
14607        switch (status) {
14608            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
14609            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
14610                return true;
14611
14612            default:
14613                // Nothing to do
14614                return false;
14615        }
14616    }
14617
14618    private static boolean isMultiArch(ApplicationInfo info) {
14619        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
14620    }
14621
14622    private static boolean isExternal(PackageParser.Package pkg) {
14623        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14624    }
14625
14626    private static boolean isExternal(PackageSetting ps) {
14627        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
14628    }
14629
14630    private static boolean isEphemeral(PackageParser.Package pkg) {
14631        return pkg.applicationInfo.isEphemeralApp();
14632    }
14633
14634    private static boolean isEphemeral(PackageSetting ps) {
14635        return ps.pkg != null && isEphemeral(ps.pkg);
14636    }
14637
14638    private static boolean isSystemApp(PackageParser.Package pkg) {
14639        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
14640    }
14641
14642    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
14643        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
14644    }
14645
14646    private static boolean hasDomainURLs(PackageParser.Package pkg) {
14647        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
14648    }
14649
14650    private static boolean isSystemApp(PackageSetting ps) {
14651        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
14652    }
14653
14654    private static boolean isUpdatedSystemApp(PackageSetting ps) {
14655        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
14656    }
14657
14658    private int packageFlagsToInstallFlags(PackageSetting ps) {
14659        int installFlags = 0;
14660        if (isEphemeral(ps)) {
14661            installFlags |= PackageManager.INSTALL_EPHEMERAL;
14662        }
14663        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
14664            // This existing package was an external ASEC install when we have
14665            // the external flag without a UUID
14666            installFlags |= PackageManager.INSTALL_EXTERNAL;
14667        }
14668        if (ps.isForwardLocked()) {
14669            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
14670        }
14671        return installFlags;
14672    }
14673
14674    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
14675        if (isExternal(pkg)) {
14676            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14677                return StorageManager.UUID_PRIMARY_PHYSICAL;
14678            } else {
14679                return pkg.volumeUuid;
14680            }
14681        } else {
14682            return StorageManager.UUID_PRIVATE_INTERNAL;
14683        }
14684    }
14685
14686    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
14687        if (isExternal(pkg)) {
14688            if (TextUtils.isEmpty(pkg.volumeUuid)) {
14689                return mSettings.getExternalVersion();
14690            } else {
14691                return mSettings.findOrCreateVersion(pkg.volumeUuid);
14692            }
14693        } else {
14694            return mSettings.getInternalVersion();
14695        }
14696    }
14697
14698    private void deleteTempPackageFiles() {
14699        final FilenameFilter filter = new FilenameFilter() {
14700            public boolean accept(File dir, String name) {
14701                return name.startsWith("vmdl") && name.endsWith(".tmp");
14702            }
14703        };
14704        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
14705            file.delete();
14706        }
14707    }
14708
14709    @Override
14710    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
14711            int flags) {
14712        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
14713                flags);
14714    }
14715
14716    @Override
14717    public void deletePackage(final String packageName,
14718            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
14719        mContext.enforceCallingOrSelfPermission(
14720                android.Manifest.permission.DELETE_PACKAGES, null);
14721        Preconditions.checkNotNull(packageName);
14722        Preconditions.checkNotNull(observer);
14723        final int uid = Binder.getCallingUid();
14724        final boolean deleteAllUsers = (flags & PackageManager.DELETE_ALL_USERS) != 0;
14725        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
14726        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
14727            mContext.enforceCallingOrSelfPermission(
14728                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14729                    "deletePackage for user " + userId);
14730        }
14731
14732        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
14733            try {
14734                observer.onPackageDeleted(packageName,
14735                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
14736            } catch (RemoteException re) {
14737            }
14738            return;
14739        }
14740
14741        if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) {
14742            try {
14743                observer.onPackageDeleted(packageName,
14744                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
14745            } catch (RemoteException re) {
14746            }
14747            return;
14748        }
14749
14750        if (DEBUG_REMOVE) {
14751            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId
14752                    + " deleteAllUsers: " + deleteAllUsers );
14753        }
14754        // Queue up an async operation since the package deletion may take a little while.
14755        mHandler.post(new Runnable() {
14756            public void run() {
14757                mHandler.removeCallbacks(this);
14758                int returnCode;
14759                if (!deleteAllUsers) {
14760                    returnCode = deletePackageX(packageName, userId, flags);
14761                } else {
14762                    int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users);
14763                    // If nobody is blocking uninstall, proceed with delete for all users
14764                    if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
14765                        returnCode = deletePackageX(packageName, userId, flags);
14766                    } else {
14767                        // Otherwise uninstall individually for users with blockUninstalls=false
14768                        final int userFlags = flags & ~PackageManager.DELETE_ALL_USERS;
14769                        for (int userId : users) {
14770                            if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
14771                                returnCode = deletePackageX(packageName, userId, userFlags);
14772                                if (returnCode != PackageManager.DELETE_SUCCEEDED) {
14773                                    Slog.w(TAG, "Package delete failed for user " + userId
14774                                            + ", returnCode " + returnCode);
14775                                }
14776                            }
14777                        }
14778                        // The app has only been marked uninstalled for certain users.
14779                        // We still need to report that delete was blocked
14780                        returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
14781                    }
14782                }
14783                try {
14784                    observer.onPackageDeleted(packageName, returnCode, null);
14785                } catch (RemoteException e) {
14786                    Log.i(TAG, "Observer no longer exists.");
14787                } //end catch
14788            } //end run
14789        });
14790    }
14791
14792    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
14793        int[] result = EMPTY_INT_ARRAY;
14794        for (int userId : userIds) {
14795            if (getBlockUninstallForUser(packageName, userId)) {
14796                result = ArrayUtils.appendInt(result, userId);
14797            }
14798        }
14799        return result;
14800    }
14801
14802    @Override
14803    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
14804        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
14805    }
14806
14807    private boolean isPackageDeviceAdmin(String packageName, int userId) {
14808        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14809                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14810        try {
14811            if (dpm != null) {
14812                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
14813                        /* callingUserOnly =*/ false);
14814                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
14815                        : deviceOwnerComponentName.getPackageName();
14816                // Does the package contains the device owner?
14817                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
14818                // this check is probably not needed, since DO should be registered as a device
14819                // admin on some user too. (Original bug for this: b/17657954)
14820                if (packageName.equals(deviceOwnerPackageName)) {
14821                    return true;
14822                }
14823                // Does it contain a device admin for any user?
14824                int[] users;
14825                if (userId == UserHandle.USER_ALL) {
14826                    users = sUserManager.getUserIds();
14827                } else {
14828                    users = new int[]{userId};
14829                }
14830                for (int i = 0; i < users.length; ++i) {
14831                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
14832                        return true;
14833                    }
14834                }
14835            }
14836        } catch (RemoteException e) {
14837        }
14838        return false;
14839    }
14840
14841    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
14842        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
14843    }
14844
14845    /**
14846     *  This method is an internal method that could be get invoked either
14847     *  to delete an installed package or to clean up a failed installation.
14848     *  After deleting an installed package, a broadcast is sent to notify any
14849     *  listeners that the package has been installed. For cleaning up a failed
14850     *  installation, the broadcast is not necessary since the package's
14851     *  installation wouldn't have sent the initial broadcast either
14852     *  The key steps in deleting a package are
14853     *  deleting the package information in internal structures like mPackages,
14854     *  deleting the packages base directories through installd
14855     *  updating mSettings to reflect current status
14856     *  persisting settings for later use
14857     *  sending a broadcast if necessary
14858     */
14859    private int deletePackageX(String packageName, int userId, int flags) {
14860        final PackageRemovedInfo info = new PackageRemovedInfo();
14861        final boolean res;
14862
14863        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
14864                ? UserHandle.ALL : new UserHandle(userId);
14865
14866        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
14867            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
14868            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
14869        }
14870
14871        PackageSetting uninstalledPs = null;
14872
14873        // for the uninstall-updates case and restricted profiles, remember the per-
14874        // user handle installed state
14875        int[] allUsers;
14876        synchronized (mPackages) {
14877            uninstalledPs = mSettings.mPackages.get(packageName);
14878            if (uninstalledPs == null) {
14879                Slog.w(TAG, "Not removing non-existent package " + packageName);
14880                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14881            }
14882            allUsers = sUserManager.getUserIds();
14883            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
14884        }
14885
14886        synchronized (mInstallLock) {
14887            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
14888            res = deletePackageLI(packageName, removeForUser, true, allUsers,
14889                    flags | REMOVE_CHATTY, info, true, null);
14890            synchronized (mPackages) {
14891                if (res) {
14892                    mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg);
14893                }
14894            }
14895        }
14896
14897        if (res) {
14898            final boolean killApp = (flags & PackageManager.INSTALL_DONT_KILL_APP) == 0;
14899            info.sendPackageRemovedBroadcasts(killApp);
14900            info.sendSystemPackageUpdatedBroadcasts();
14901            info.sendSystemPackageAppearedBroadcasts();
14902        }
14903        // Force a gc here.
14904        Runtime.getRuntime().gc();
14905        // Delete the resources here after sending the broadcast to let
14906        // other processes clean up before deleting resources.
14907        if (info.args != null) {
14908            synchronized (mInstallLock) {
14909                info.args.doPostDeleteLI(true);
14910            }
14911        }
14912
14913        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
14914    }
14915
14916    class PackageRemovedInfo {
14917        String removedPackage;
14918        int uid = -1;
14919        int removedAppId = -1;
14920        int[] origUsers;
14921        int[] removedUsers = null;
14922        boolean isRemovedPackageSystemUpdate = false;
14923        boolean isUpdate;
14924        boolean dataRemoved;
14925        boolean removedForAllUsers;
14926        // Clean up resources deleted packages.
14927        InstallArgs args = null;
14928        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
14929        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
14930
14931        void sendPackageRemovedBroadcasts(boolean killApp) {
14932            sendPackageRemovedBroadcastInternal(killApp);
14933            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
14934            for (int i = 0; i < childCount; i++) {
14935                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14936                childInfo.sendPackageRemovedBroadcastInternal(killApp);
14937            }
14938        }
14939
14940        void sendSystemPackageUpdatedBroadcasts() {
14941            if (isRemovedPackageSystemUpdate) {
14942                sendSystemPackageUpdatedBroadcastsInternal();
14943                final int childCount = (removedChildPackages != null)
14944                        ? removedChildPackages.size() : 0;
14945                for (int i = 0; i < childCount; i++) {
14946                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
14947                    if (childInfo.isRemovedPackageSystemUpdate) {
14948                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
14949                    }
14950                }
14951            }
14952        }
14953
14954        void sendSystemPackageAppearedBroadcasts() {
14955            final int packageCount = (appearedChildPackages != null)
14956                    ? appearedChildPackages.size() : 0;
14957            for (int i = 0; i < packageCount; i++) {
14958                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
14959                for (int userId : installedInfo.newUsers) {
14960                    sendPackageAddedForUser(installedInfo.name, true,
14961                            UserHandle.getAppId(installedInfo.uid), userId);
14962                }
14963            }
14964        }
14965
14966        private void sendSystemPackageUpdatedBroadcastsInternal() {
14967            Bundle extras = new Bundle(2);
14968            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
14969            extras.putBoolean(Intent.EXTRA_REPLACING, true);
14970            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage,
14971                    extras, 0, null, null, null);
14972            sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage,
14973                    extras, 0, null, null, null);
14974            sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
14975                    null, 0, removedPackage, null, null);
14976        }
14977
14978        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
14979            Bundle extras = new Bundle(2);
14980            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
14981            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
14982            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
14983            if (isUpdate || isRemovedPackageSystemUpdate) {
14984                extras.putBoolean(Intent.EXTRA_REPLACING, true);
14985            }
14986            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
14987            if (removedPackage != null) {
14988                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
14989                        extras, 0, null, null, removedUsers);
14990                if (dataRemoved && !isRemovedPackageSystemUpdate) {
14991                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
14992                            removedPackage, extras, 0, null, null, removedUsers);
14993                }
14994            }
14995            if (removedAppId >= 0) {
14996                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null,
14997                        removedUsers);
14998            }
14999        }
15000    }
15001
15002    /*
15003     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
15004     * flag is not set, the data directory is removed as well.
15005     * make sure this flag is set for partially installed apps. If not its meaningless to
15006     * delete a partially installed application.
15007     */
15008    private void removePackageDataLI(PackageSetting ps, int[] allUserHandles,
15009            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
15010        String packageName = ps.name;
15011        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
15012        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
15013        // Retrieve object to delete permissions for shared user later on
15014        final PackageSetting deletedPs;
15015        // reader
15016        synchronized (mPackages) {
15017            deletedPs = mSettings.mPackages.get(packageName);
15018            if (outInfo != null) {
15019                outInfo.removedPackage = packageName;
15020                outInfo.removedUsers = deletedPs != null
15021                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
15022                        : null;
15023            }
15024        }
15025        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15026            removeDataDirsLI(ps.volumeUuid, packageName);
15027            if (outInfo != null) {
15028                outInfo.dataRemoved = true;
15029            }
15030            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
15031        }
15032        // writer
15033        synchronized (mPackages) {
15034            if (deletedPs != null) {
15035                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
15036                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
15037                    clearDefaultBrowserIfNeeded(packageName);
15038                    if (outInfo != null) {
15039                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
15040                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
15041                    }
15042                    updatePermissionsLPw(deletedPs.name, null, 0);
15043                    if (deletedPs.sharedUser != null) {
15044                        // Remove permissions associated with package. Since runtime
15045                        // permissions are per user we have to kill the removed package
15046                        // or packages running under the shared user of the removed
15047                        // package if revoking the permissions requested only by the removed
15048                        // package is successful and this causes a change in gids.
15049                        for (int userId : UserManagerService.getInstance().getUserIds()) {
15050                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
15051                                    userId);
15052                            if (userIdToKill == UserHandle.USER_ALL
15053                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
15054                                // If gids changed for this user, kill all affected packages.
15055                                mHandler.post(new Runnable() {
15056                                    @Override
15057                                    public void run() {
15058                                        // This has to happen with no lock held.
15059                                        killApplication(deletedPs.name, deletedPs.appId,
15060                                                KILL_APP_REASON_GIDS_CHANGED);
15061                                    }
15062                                });
15063                                break;
15064                            }
15065                        }
15066                    }
15067                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
15068                }
15069                // make sure to preserve per-user disabled state if this removal was just
15070                // a downgrade of a system app to the factory package
15071                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
15072                    if (DEBUG_REMOVE) {
15073                        Slog.d(TAG, "Propagating install state across downgrade");
15074                    }
15075                    for (int userId : allUserHandles) {
15076                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15077                        if (DEBUG_REMOVE) {
15078                            Slog.d(TAG, "    user " + userId + " => " + installed);
15079                        }
15080                        ps.setInstalled(installed, userId);
15081                    }
15082                }
15083            }
15084            // can downgrade to reader
15085            if (writeSettings) {
15086                // Save settings now
15087                mSettings.writeLPr();
15088            }
15089        }
15090        if (outInfo != null) {
15091            // A user ID was deleted here. Go through all users and remove it
15092            // from KeyStore.
15093            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
15094        }
15095    }
15096
15097    static boolean locationIsPrivileged(File path) {
15098        try {
15099            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
15100                    .getCanonicalPath();
15101            return path.getCanonicalPath().startsWith(privilegedAppDir);
15102        } catch (IOException e) {
15103            Slog.e(TAG, "Unable to access code path " + path);
15104        }
15105        return false;
15106    }
15107
15108    /*
15109     * Tries to delete system package.
15110     */
15111    private boolean deleteSystemPackageLI(PackageParser.Package deletedPkg,
15112            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
15113            boolean writeSettings) {
15114        if (deletedPs.parentPackageName != null) {
15115            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
15116            return false;
15117        }
15118
15119        final boolean applyUserRestrictions
15120                = (allUserHandles != null) && (outInfo.origUsers != null);
15121        final PackageSetting disabledPs;
15122        // Confirm if the system package has been updated
15123        // An updated system app can be deleted. This will also have to restore
15124        // the system pkg from system partition
15125        // reader
15126        synchronized (mPackages) {
15127            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
15128        }
15129
15130        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
15131                + " disabledPs=" + disabledPs);
15132
15133        if (disabledPs == null) {
15134            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
15135            return false;
15136        } else if (DEBUG_REMOVE) {
15137            Slog.d(TAG, "Deleting system pkg from data partition");
15138        }
15139
15140        if (DEBUG_REMOVE) {
15141            if (applyUserRestrictions) {
15142                Slog.d(TAG, "Remembering install states:");
15143                for (int userId : allUserHandles) {
15144                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
15145                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
15146                }
15147            }
15148        }
15149
15150        // Delete the updated package
15151        outInfo.isRemovedPackageSystemUpdate = true;
15152        if (outInfo.removedChildPackages != null) {
15153            final int childCount = (deletedPs.childPackageNames != null)
15154                    ? deletedPs.childPackageNames.size() : 0;
15155            for (int i = 0; i < childCount; i++) {
15156                String childPackageName = deletedPs.childPackageNames.get(i);
15157                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
15158                        .contains(childPackageName)) {
15159                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15160                            childPackageName);
15161                    if (childInfo != null) {
15162                        childInfo.isRemovedPackageSystemUpdate = true;
15163                    }
15164                }
15165            }
15166        }
15167
15168        if (disabledPs.versionCode < deletedPs.versionCode) {
15169            // Delete data for downgrades
15170            flags &= ~PackageManager.DELETE_KEEP_DATA;
15171        } else {
15172            // Preserve data by setting flag
15173            flags |= PackageManager.DELETE_KEEP_DATA;
15174        }
15175
15176        boolean ret = deleteInstalledPackageLI(deletedPs, true, flags, allUserHandles,
15177                outInfo, writeSettings, disabledPs.pkg);
15178        if (!ret) {
15179            return false;
15180        }
15181
15182        // writer
15183        synchronized (mPackages) {
15184            // Reinstate the old system package
15185            enableSystemPackageLPw(disabledPs.pkg);
15186            // Remove any native libraries from the upgraded package.
15187            removeNativeBinariesLI(deletedPs);
15188        }
15189
15190        // Install the system package
15191        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
15192        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
15193        if (locationIsPrivileged(disabledPs.codePath)) {
15194            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
15195        }
15196
15197        final PackageParser.Package newPkg;
15198        try {
15199            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
15200        } catch (PackageManagerException e) {
15201            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
15202                    + e.getMessage());
15203            return false;
15204        }
15205
15206        prepareAppDataAfterInstall(newPkg);
15207
15208        // writer
15209        synchronized (mPackages) {
15210            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
15211
15212            // Propagate the permissions state as we do not want to drop on the floor
15213            // runtime permissions. The update permissions method below will take
15214            // care of removing obsolete permissions and grant install permissions.
15215            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
15216            updatePermissionsLPw(newPkg.packageName, newPkg,
15217                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
15218
15219            if (applyUserRestrictions) {
15220                if (DEBUG_REMOVE) {
15221                    Slog.d(TAG, "Propagating install state across reinstall");
15222                }
15223                for (int userId : allUserHandles) {
15224                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
15225                    if (DEBUG_REMOVE) {
15226                        Slog.d(TAG, "    user " + userId + " => " + installed);
15227                    }
15228                    ps.setInstalled(installed, userId);
15229
15230                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
15231                }
15232                // Regardless of writeSettings we need to ensure that this restriction
15233                // state propagation is persisted
15234                mSettings.writeAllUsersPackageRestrictionsLPr();
15235            }
15236            // can downgrade to reader here
15237            if (writeSettings) {
15238                mSettings.writeLPr();
15239            }
15240        }
15241        return true;
15242    }
15243
15244    private boolean deleteInstalledPackageLI(PackageSetting ps,
15245            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
15246            PackageRemovedInfo outInfo, boolean writeSettings,
15247            PackageParser.Package replacingPackage) {
15248        synchronized (mPackages) {
15249            if (outInfo != null) {
15250                outInfo.uid = ps.appId;
15251            }
15252
15253            if (outInfo != null && outInfo.removedChildPackages != null) {
15254                final int childCount = (ps.childPackageNames != null)
15255                        ? ps.childPackageNames.size() : 0;
15256                for (int i = 0; i < childCount; i++) {
15257                    String childPackageName = ps.childPackageNames.get(i);
15258                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
15259                    if (childPs == null) {
15260                        return false;
15261                    }
15262                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
15263                            childPackageName);
15264                    if (childInfo != null) {
15265                        childInfo.uid = childPs.appId;
15266                    }
15267                }
15268            }
15269        }
15270
15271        // Delete package data from internal structures and also remove data if flag is set
15272        removePackageDataLI(ps, allUserHandles, outInfo, flags, writeSettings);
15273
15274        // Delete the child packages data
15275        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
15276        for (int i = 0; i < childCount; i++) {
15277            PackageSetting childPs;
15278            synchronized (mPackages) {
15279                childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i));
15280            }
15281            if (childPs != null) {
15282                PackageRemovedInfo childOutInfo = (outInfo != null
15283                        && outInfo.removedChildPackages != null)
15284                        ? outInfo.removedChildPackages.get(childPs.name) : null;
15285                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
15286                        && (replacingPackage != null
15287                        && !replacingPackage.hasChildPackage(childPs.name))
15288                        ? flags & ~DELETE_KEEP_DATA : flags;
15289                removePackageDataLI(childPs, allUserHandles, childOutInfo,
15290                        deleteFlags, writeSettings);
15291            }
15292        }
15293
15294        // Delete application code and resources only for parent packages
15295        if (ps.parentPackageName == null) {
15296            if (deleteCodeAndResources && (outInfo != null)) {
15297                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
15298                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
15299                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
15300            }
15301        }
15302
15303        return true;
15304    }
15305
15306    @Override
15307    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
15308            int userId) {
15309        mContext.enforceCallingOrSelfPermission(
15310                android.Manifest.permission.DELETE_PACKAGES, null);
15311        synchronized (mPackages) {
15312            PackageSetting ps = mSettings.mPackages.get(packageName);
15313            if (ps == null) {
15314                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
15315                return false;
15316            }
15317            if (!ps.getInstalled(userId)) {
15318                // Can't block uninstall for an app that is not installed or enabled.
15319                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
15320                return false;
15321            }
15322            ps.setBlockUninstall(blockUninstall, userId);
15323            mSettings.writePackageRestrictionsLPr(userId);
15324        }
15325        return true;
15326    }
15327
15328    @Override
15329    public boolean getBlockUninstallForUser(String packageName, int userId) {
15330        synchronized (mPackages) {
15331            PackageSetting ps = mSettings.mPackages.get(packageName);
15332            if (ps == null) {
15333                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
15334                return false;
15335            }
15336            return ps.getBlockUninstall(userId);
15337        }
15338    }
15339
15340    @Override
15341    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
15342        int callingUid = Binder.getCallingUid();
15343        if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
15344            throw new SecurityException(
15345                    "setRequiredForSystemUser can only be run by the system or root");
15346        }
15347        synchronized (mPackages) {
15348            PackageSetting ps = mSettings.mPackages.get(packageName);
15349            if (ps == null) {
15350                Log.w(TAG, "Package doesn't exist: " + packageName);
15351                return false;
15352            }
15353            if (systemUserApp) {
15354                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15355            } else {
15356                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
15357            }
15358            mSettings.writeLPr();
15359        }
15360        return true;
15361    }
15362
15363    /*
15364     * This method handles package deletion in general
15365     */
15366    private boolean deletePackageLI(String packageName, UserHandle user,
15367            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
15368            PackageRemovedInfo outInfo, boolean writeSettings,
15369            PackageParser.Package replacingPackage) {
15370        if (packageName == null) {
15371            Slog.w(TAG, "Attempt to delete null packageName.");
15372            return false;
15373        }
15374
15375        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
15376
15377        PackageSetting ps;
15378
15379        synchronized (mPackages) {
15380            ps = mSettings.mPackages.get(packageName);
15381            if (ps == null) {
15382                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15383                return false;
15384            }
15385
15386            if (ps.parentPackageName != null && (!isSystemApp(ps)
15387                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
15388                if (DEBUG_REMOVE) {
15389                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
15390                            + ((user == null) ? UserHandle.USER_ALL : user));
15391                }
15392                final int removedUserId = (user != null) ? user.getIdentifier()
15393                        : UserHandle.USER_ALL;
15394                if (!clearPackageStateForUser(ps, removedUserId, outInfo)) {
15395                    return false;
15396                }
15397                markPackageUninstalledForUserLPw(ps, user);
15398                scheduleWritePackageRestrictionsLocked(user);
15399                return true;
15400            }
15401        }
15402
15403        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
15404                && user.getIdentifier() != UserHandle.USER_ALL)) {
15405            // The caller is asking that the package only be deleted for a single
15406            // user.  To do this, we just mark its uninstalled state and delete
15407            // its data. If this is a system app, we only allow this to happen if
15408            // they have set the special DELETE_SYSTEM_APP which requests different
15409            // semantics than normal for uninstalling system apps.
15410            markPackageUninstalledForUserLPw(ps, user);
15411
15412            if (!isSystemApp(ps)) {
15413                // Do not uninstall the APK if an app should be cached
15414                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
15415                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
15416                    // Other user still have this package installed, so all
15417                    // we need to do is clear this user's data and save that
15418                    // it is uninstalled.
15419                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
15420                    if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
15421                        return false;
15422                    }
15423                    scheduleWritePackageRestrictionsLocked(user);
15424                    return true;
15425                } else {
15426                    // We need to set it back to 'installed' so the uninstall
15427                    // broadcasts will be sent correctly.
15428                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
15429                    ps.setInstalled(true, user.getIdentifier());
15430                }
15431            } else {
15432                // This is a system app, so we assume that the
15433                // other users still have this package installed, so all
15434                // we need to do is clear this user's data and save that
15435                // it is uninstalled.
15436                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
15437                if (!clearPackageStateForUser(ps, user.getIdentifier(), outInfo)) {
15438                    return false;
15439                }
15440                scheduleWritePackageRestrictionsLocked(user);
15441                return true;
15442            }
15443        }
15444
15445        // If we are deleting a composite package for all users, keep track
15446        // of result for each child.
15447        if (ps.childPackageNames != null && outInfo != null) {
15448            synchronized (mPackages) {
15449                final int childCount = ps.childPackageNames.size();
15450                outInfo.removedChildPackages = new ArrayMap<>(childCount);
15451                for (int i = 0; i < childCount; i++) {
15452                    String childPackageName = ps.childPackageNames.get(i);
15453                    PackageRemovedInfo childInfo = new PackageRemovedInfo();
15454                    childInfo.removedPackage = childPackageName;
15455                    outInfo.removedChildPackages.put(childPackageName, childInfo);
15456                    PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15457                    if (childPs != null) {
15458                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
15459                    }
15460                }
15461            }
15462        }
15463
15464        boolean ret = false;
15465        if (isSystemApp(ps)) {
15466            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
15467            // When an updated system application is deleted we delete the existing resources
15468            // as well and fall back to existing code in system partition
15469            ret = deleteSystemPackageLI(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
15470        } else {
15471            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
15472            // Kill application pre-emptively especially for apps on sd.
15473            final boolean killApp = (flags & PackageManager.DELETE_DONT_KILL_APP) == 0;
15474            if (killApp) {
15475                killApplication(packageName, ps.appId, "uninstall pkg");
15476            }
15477            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, allUserHandles,
15478                    outInfo, writeSettings, replacingPackage);
15479        }
15480
15481        // Take a note whether we deleted the package for all users
15482        if (outInfo != null) {
15483            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
15484            if (outInfo.removedChildPackages != null) {
15485                synchronized (mPackages) {
15486                    final int childCount = outInfo.removedChildPackages.size();
15487                    for (int i = 0; i < childCount; i++) {
15488                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
15489                        if (childInfo != null) {
15490                            childInfo.removedForAllUsers = mPackages.get(
15491                                    childInfo.removedPackage) == null;
15492                        }
15493                    }
15494                }
15495            }
15496            // If we uninstalled an update to a system app there may be some
15497            // child packages that appeared as they are declared in the system
15498            // app but were not declared in the update.
15499            if (isSystemApp(ps)) {
15500                synchronized (mPackages) {
15501                    PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name);
15502                    final int childCount = (updatedPs.childPackageNames != null)
15503                            ? updatedPs.childPackageNames.size() : 0;
15504                    for (int i = 0; i < childCount; i++) {
15505                        String childPackageName = updatedPs.childPackageNames.get(i);
15506                        if (outInfo.removedChildPackages == null
15507                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
15508                            PackageSetting childPs = mSettings.peekPackageLPr(childPackageName);
15509                            if (childPs == null) {
15510                                continue;
15511                            }
15512                            PackageInstalledInfo installRes = new PackageInstalledInfo();
15513                            installRes.name = childPackageName;
15514                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
15515                            installRes.pkg = mPackages.get(childPackageName);
15516                            installRes.uid = childPs.pkg.applicationInfo.uid;
15517                            if (outInfo.appearedChildPackages == null) {
15518                                outInfo.appearedChildPackages = new ArrayMap<>();
15519                            }
15520                            outInfo.appearedChildPackages.put(childPackageName, installRes);
15521                        }
15522                    }
15523                }
15524            }
15525        }
15526
15527        return ret;
15528    }
15529
15530    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
15531        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
15532                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
15533        for (int nextUserId : userIds) {
15534            if (DEBUG_REMOVE) {
15535                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
15536            }
15537            ps.setUserState(nextUserId, COMPONENT_ENABLED_STATE_DEFAULT,
15538                    false /*installed*/, true /*stopped*/, true /*notLaunched*/,
15539                    false /*hidden*/, false /*suspended*/, null, null, null,
15540                    false /*blockUninstall*/,
15541                    ps.readUserState(nextUserId).domainVerificationStatus, 0);
15542        }
15543    }
15544
15545    private boolean clearPackageStateForUser(PackageSetting ps, int userId,
15546            PackageRemovedInfo outInfo) {
15547        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
15548                : new int[] {userId};
15549        for (int nextUserId : userIds) {
15550            if (DEBUG_REMOVE) {
15551                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
15552                        + nextUserId);
15553            }
15554            final int flags =  StorageManager.FLAG_STORAGE_CE|  StorageManager.FLAG_STORAGE_DE;
15555            try {
15556                mInstaller.destroyAppData(ps.volumeUuid, ps.name, nextUserId, flags);
15557            } catch (InstallerException e) {
15558                Slog.w(TAG, "Couldn't remove cache files for package " + ps.name, e);
15559                return false;
15560            }
15561            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
15562            schedulePackageCleaning(ps.name, nextUserId, false);
15563            synchronized (mPackages) {
15564                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
15565                    scheduleWritePackageRestrictionsLocked(nextUserId);
15566                }
15567                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
15568            }
15569        }
15570
15571        if (outInfo != null) {
15572            outInfo.removedPackage = ps.name;
15573            outInfo.removedAppId = ps.appId;
15574            outInfo.removedUsers = userIds;
15575        }
15576
15577        return true;
15578    }
15579
15580    private final class ClearStorageConnection implements ServiceConnection {
15581        IMediaContainerService mContainerService;
15582
15583        @Override
15584        public void onServiceConnected(ComponentName name, IBinder service) {
15585            synchronized (this) {
15586                mContainerService = IMediaContainerService.Stub.asInterface(service);
15587                notifyAll();
15588            }
15589        }
15590
15591        @Override
15592        public void onServiceDisconnected(ComponentName name) {
15593        }
15594    }
15595
15596    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
15597        final boolean mounted;
15598        if (Environment.isExternalStorageEmulated()) {
15599            mounted = true;
15600        } else {
15601            final String status = Environment.getExternalStorageState();
15602
15603            mounted = status.equals(Environment.MEDIA_MOUNTED)
15604                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
15605        }
15606
15607        if (!mounted) {
15608            return;
15609        }
15610
15611        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
15612        int[] users;
15613        if (userId == UserHandle.USER_ALL) {
15614            users = sUserManager.getUserIds();
15615        } else {
15616            users = new int[] { userId };
15617        }
15618        final ClearStorageConnection conn = new ClearStorageConnection();
15619        if (mContext.bindServiceAsUser(
15620                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
15621            try {
15622                for (int curUser : users) {
15623                    long timeout = SystemClock.uptimeMillis() + 5000;
15624                    synchronized (conn) {
15625                        long now = SystemClock.uptimeMillis();
15626                        while (conn.mContainerService == null && now < timeout) {
15627                            try {
15628                                conn.wait(timeout - now);
15629                            } catch (InterruptedException e) {
15630                            }
15631                        }
15632                    }
15633                    if (conn.mContainerService == null) {
15634                        return;
15635                    }
15636
15637                    final UserEnvironment userEnv = new UserEnvironment(curUser);
15638                    clearDirectory(conn.mContainerService,
15639                            userEnv.buildExternalStorageAppCacheDirs(packageName));
15640                    if (allData) {
15641                        clearDirectory(conn.mContainerService,
15642                                userEnv.buildExternalStorageAppDataDirs(packageName));
15643                        clearDirectory(conn.mContainerService,
15644                                userEnv.buildExternalStorageAppMediaDirs(packageName));
15645                    }
15646                }
15647            } finally {
15648                mContext.unbindService(conn);
15649            }
15650        }
15651    }
15652
15653    @Override
15654    public void clearApplicationProfileData(String packageName) {
15655        enforceSystemOrRoot("Only the system can clear all profile data");
15656        try {
15657            mInstaller.clearAppProfiles(packageName);
15658        } catch (InstallerException ex) {
15659            Log.e(TAG, "Could not clear profile data of package " + packageName);
15660        }
15661    }
15662
15663    @Override
15664    public void clearApplicationUserData(final String packageName,
15665            final IPackageDataObserver observer, final int userId) {
15666        mContext.enforceCallingOrSelfPermission(
15667                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
15668
15669        enforceCrossUserPermission(Binder.getCallingUid(), userId,
15670                true /* requireFullPermission */, false /* checkShell */, "clear application data");
15671
15672        final DevicePolicyManagerInternal dpmi = LocalServices
15673                .getService(DevicePolicyManagerInternal.class);
15674        if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) {
15675            throw new SecurityException("Cannot clear data for a device owner or a profile owner");
15676        }
15677        // Queue up an async operation since the package deletion may take a little while.
15678        mHandler.post(new Runnable() {
15679            public void run() {
15680                mHandler.removeCallbacks(this);
15681                final boolean succeeded;
15682                synchronized (mInstallLock) {
15683                    succeeded = clearApplicationUserDataLI(packageName, userId);
15684                }
15685                clearExternalStorageDataSync(packageName, userId, true);
15686                if (succeeded) {
15687                    // invoke DeviceStorageMonitor's update method to clear any notifications
15688                    DeviceStorageMonitorInternal dsm = LocalServices
15689                            .getService(DeviceStorageMonitorInternal.class);
15690                    if (dsm != null) {
15691                        dsm.checkMemory();
15692                    }
15693                }
15694                if(observer != null) {
15695                    try {
15696                        observer.onRemoveCompleted(packageName, succeeded);
15697                    } catch (RemoteException e) {
15698                        Log.i(TAG, "Observer no longer exists.");
15699                    }
15700                } //end if observer
15701            } //end run
15702        });
15703    }
15704
15705    private boolean clearApplicationUserDataLI(String packageName, int userId) {
15706        if (packageName == null) {
15707            Slog.w(TAG, "Attempt to delete null packageName.");
15708            return false;
15709        }
15710
15711        // Try finding details about the requested package
15712        PackageParser.Package pkg;
15713        synchronized (mPackages) {
15714            pkg = mPackages.get(packageName);
15715            if (pkg == null) {
15716                final PackageSetting ps = mSettings.mPackages.get(packageName);
15717                if (ps != null) {
15718                    pkg = ps.pkg;
15719                }
15720            }
15721
15722            if (pkg == null) {
15723                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
15724                return false;
15725            }
15726
15727            PackageSetting ps = (PackageSetting) pkg.mExtras;
15728            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15729        }
15730
15731        // Always delete data directories for package, even if we found no other
15732        // record of app. This helps users recover from UID mismatches without
15733        // resorting to a full data wipe.
15734        // TODO: triage flags as part of 26466827
15735        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15736        try {
15737            mInstaller.clearAppData(pkg.volumeUuid, packageName, userId, flags);
15738        } catch (InstallerException e) {
15739            Slog.w(TAG, "Couldn't remove cache files for package " + packageName, e);
15740            return false;
15741        }
15742
15743        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
15744        removeKeystoreDataIfNeeded(userId, appId);
15745
15746        // Create a native library symlink only if we have native libraries
15747        // and if the native libraries are 32 bit libraries. We do not provide
15748        // this symlink for 64 bit libraries.
15749        if (pkg.applicationInfo.primaryCpuAbi != null &&
15750                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
15751            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
15752            try {
15753                mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
15754                        nativeLibPath, userId);
15755            } catch (InstallerException e) {
15756                Slog.w(TAG, "Failed linking native library dir", e);
15757                return false;
15758            }
15759        }
15760
15761        return true;
15762    }
15763
15764    /**
15765     * Reverts user permission state changes (permissions and flags) in
15766     * all packages for a given user.
15767     *
15768     * @param userId The device user for which to do a reset.
15769     */
15770    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
15771        final int packageCount = mPackages.size();
15772        for (int i = 0; i < packageCount; i++) {
15773            PackageParser.Package pkg = mPackages.valueAt(i);
15774            PackageSetting ps = (PackageSetting) pkg.mExtras;
15775            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
15776        }
15777    }
15778
15779    /**
15780     * Reverts user permission state changes (permissions and flags).
15781     *
15782     * @param ps The package for which to reset.
15783     * @param userId The device user for which to do a reset.
15784     */
15785    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
15786            final PackageSetting ps, final int userId) {
15787        if (ps.pkg == null) {
15788            return;
15789        }
15790
15791        // These are flags that can change base on user actions.
15792        final int userSettableMask = FLAG_PERMISSION_USER_SET
15793                | FLAG_PERMISSION_USER_FIXED
15794                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
15795                | FLAG_PERMISSION_REVIEW_REQUIRED;
15796
15797        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
15798                | FLAG_PERMISSION_POLICY_FIXED;
15799
15800        boolean writeInstallPermissions = false;
15801        boolean writeRuntimePermissions = false;
15802
15803        final int permissionCount = ps.pkg.requestedPermissions.size();
15804        for (int i = 0; i < permissionCount; i++) {
15805            String permission = ps.pkg.requestedPermissions.get(i);
15806
15807            BasePermission bp = mSettings.mPermissions.get(permission);
15808            if (bp == null) {
15809                continue;
15810            }
15811
15812            // If shared user we just reset the state to which only this app contributed.
15813            if (ps.sharedUser != null) {
15814                boolean used = false;
15815                final int packageCount = ps.sharedUser.packages.size();
15816                for (int j = 0; j < packageCount; j++) {
15817                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
15818                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
15819                            && pkg.pkg.requestedPermissions.contains(permission)) {
15820                        used = true;
15821                        break;
15822                    }
15823                }
15824                if (used) {
15825                    continue;
15826                }
15827            }
15828
15829            PermissionsState permissionsState = ps.getPermissionsState();
15830
15831            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
15832
15833            // Always clear the user settable flags.
15834            final boolean hasInstallState = permissionsState.getInstallPermissionState(
15835                    bp.name) != null;
15836            // If permission review is enabled and this is a legacy app, mark the
15837            // permission as requiring a review as this is the initial state.
15838            int flags = 0;
15839            if (Build.PERMISSIONS_REVIEW_REQUIRED
15840                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
15841                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
15842            }
15843            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
15844                if (hasInstallState) {
15845                    writeInstallPermissions = true;
15846                } else {
15847                    writeRuntimePermissions = true;
15848                }
15849            }
15850
15851            // Below is only runtime permission handling.
15852            if (!bp.isRuntime()) {
15853                continue;
15854            }
15855
15856            // Never clobber system or policy.
15857            if ((oldFlags & policyOrSystemFlags) != 0) {
15858                continue;
15859            }
15860
15861            // If this permission was granted by default, make sure it is.
15862            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
15863                if (permissionsState.grantRuntimePermission(bp, userId)
15864                        != PERMISSION_OPERATION_FAILURE) {
15865                    writeRuntimePermissions = true;
15866                }
15867            // If permission review is enabled the permissions for a legacy apps
15868            // are represented as constantly granted runtime ones, so don't revoke.
15869            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
15870                // Otherwise, reset the permission.
15871                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
15872                switch (revokeResult) {
15873                    case PERMISSION_OPERATION_SUCCESS:
15874                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
15875                        writeRuntimePermissions = true;
15876                        final int appId = ps.appId;
15877                        mHandler.post(new Runnable() {
15878                            @Override
15879                            public void run() {
15880                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
15881                            }
15882                        });
15883                    } break;
15884                }
15885            }
15886        }
15887
15888        // Synchronously write as we are taking permissions away.
15889        if (writeRuntimePermissions) {
15890            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
15891        }
15892
15893        // Synchronously write as we are taking permissions away.
15894        if (writeInstallPermissions) {
15895            mSettings.writeLPr();
15896        }
15897    }
15898
15899    /**
15900     * Remove entries from the keystore daemon. Will only remove it if the
15901     * {@code appId} is valid.
15902     */
15903    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
15904        if (appId < 0) {
15905            return;
15906        }
15907
15908        final KeyStore keyStore = KeyStore.getInstance();
15909        if (keyStore != null) {
15910            if (userId == UserHandle.USER_ALL) {
15911                for (final int individual : sUserManager.getUserIds()) {
15912                    keyStore.clearUid(UserHandle.getUid(individual, appId));
15913                }
15914            } else {
15915                keyStore.clearUid(UserHandle.getUid(userId, appId));
15916            }
15917        } else {
15918            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
15919        }
15920    }
15921
15922    @Override
15923    public void deleteApplicationCacheFiles(final String packageName,
15924            final IPackageDataObserver observer) {
15925        mContext.enforceCallingOrSelfPermission(
15926                android.Manifest.permission.DELETE_CACHE_FILES, null);
15927        // Queue up an async operation since the package deletion may take a little while.
15928        final int userId = UserHandle.getCallingUserId();
15929        mHandler.post(new Runnable() {
15930            public void run() {
15931                mHandler.removeCallbacks(this);
15932                final boolean succeded;
15933                synchronized (mInstallLock) {
15934                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
15935                }
15936                clearExternalStorageDataSync(packageName, userId, false);
15937                if (observer != null) {
15938                    try {
15939                        observer.onRemoveCompleted(packageName, succeded);
15940                    } catch (RemoteException e) {
15941                        Log.i(TAG, "Observer no longer exists.");
15942                    }
15943                } //end if observer
15944            } //end run
15945        });
15946    }
15947
15948    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
15949        if (packageName == null) {
15950            Slog.w(TAG, "Attempt to delete null packageName.");
15951            return false;
15952        }
15953        PackageParser.Package p;
15954        synchronized (mPackages) {
15955            p = mPackages.get(packageName);
15956        }
15957        if (p == null) {
15958            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
15959            return false;
15960        }
15961        final ApplicationInfo applicationInfo = p.applicationInfo;
15962        if (applicationInfo == null) {
15963            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
15964            return false;
15965        }
15966        // TODO: triage flags as part of 26466827
15967        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
15968        try {
15969            mInstaller.clearAppData(p.volumeUuid, packageName, userId,
15970                    flags | Installer.FLAG_CLEAR_CACHE_ONLY);
15971        } catch (InstallerException e) {
15972            Slog.w(TAG, "Couldn't remove cache files for package "
15973                    + packageName + " u" + userId, e);
15974            return false;
15975        }
15976        return true;
15977    }
15978
15979    @Override
15980    public void getPackageSizeInfo(final String packageName, int userHandle,
15981            final IPackageStatsObserver observer) {
15982        mContext.enforceCallingOrSelfPermission(
15983                android.Manifest.permission.GET_PACKAGE_SIZE, null);
15984        if (packageName == null) {
15985            throw new IllegalArgumentException("Attempt to get size of null packageName");
15986        }
15987
15988        PackageStats stats = new PackageStats(packageName, userHandle);
15989
15990        /*
15991         * Queue up an async operation since the package measurement may take a
15992         * little while.
15993         */
15994        Message msg = mHandler.obtainMessage(INIT_COPY);
15995        msg.obj = new MeasureParams(stats, observer);
15996        mHandler.sendMessage(msg);
15997    }
15998
15999    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
16000            PackageStats pStats) {
16001        if (packageName == null) {
16002            Slog.w(TAG, "Attempt to get size of null packageName.");
16003            return false;
16004        }
16005        PackageParser.Package p;
16006        boolean dataOnly = false;
16007        String libDirRoot = null;
16008        String asecPath = null;
16009        PackageSetting ps = null;
16010        synchronized (mPackages) {
16011            p = mPackages.get(packageName);
16012            ps = mSettings.mPackages.get(packageName);
16013            if(p == null) {
16014                dataOnly = true;
16015                if((ps == null) || (ps.pkg == null)) {
16016                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
16017                    return false;
16018                }
16019                p = ps.pkg;
16020            }
16021            if (ps != null) {
16022                libDirRoot = ps.legacyNativeLibraryPathString;
16023            }
16024            if (p != null && (p.isForwardLocked() || p.applicationInfo.isExternalAsec())) {
16025                final long token = Binder.clearCallingIdentity();
16026                try {
16027                    String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
16028                    if (secureContainerId != null) {
16029                        asecPath = PackageHelper.getSdFilesystem(secureContainerId);
16030                    }
16031                } finally {
16032                    Binder.restoreCallingIdentity(token);
16033                }
16034            }
16035        }
16036        String publicSrcDir = null;
16037        if(!dataOnly) {
16038            final ApplicationInfo applicationInfo = p.applicationInfo;
16039            if (applicationInfo == null) {
16040                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
16041                return false;
16042            }
16043            if (p.isForwardLocked()) {
16044                publicSrcDir = applicationInfo.getBaseResourcePath();
16045            }
16046        }
16047        // TODO: extend to measure size of split APKs
16048        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
16049        // not just the first level.
16050        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
16051        // just the primary.
16052        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
16053
16054        String apkPath;
16055        File packageDir = new File(p.codePath);
16056
16057        if (packageDir.isDirectory() && p.canHaveOatDir()) {
16058            apkPath = packageDir.getAbsolutePath();
16059            // If libDirRoot is inside a package dir, set it to null to avoid it being counted twice
16060            if (libDirRoot != null && libDirRoot.startsWith(apkPath)) {
16061                libDirRoot = null;
16062            }
16063        } else {
16064            apkPath = p.baseCodePath;
16065        }
16066
16067        // TODO: triage flags as part of 26466827
16068        final int flags = StorageManager.FLAG_STORAGE_CE | StorageManager.FLAG_STORAGE_DE;
16069        try {
16070            mInstaller.getAppSize(p.volumeUuid, packageName, userHandle, flags, apkPath,
16071                    libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
16072        } catch (InstallerException e) {
16073            return false;
16074        }
16075
16076        // Fix-up for forward-locked applications in ASEC containers.
16077        if (!isExternal(p)) {
16078            pStats.codeSize += pStats.externalCodeSize;
16079            pStats.externalCodeSize = 0L;
16080        }
16081
16082        return true;
16083    }
16084
16085    private int getUidTargetSdkVersionLockedLPr(int uid) {
16086        Object obj = mSettings.getUserIdLPr(uid);
16087        if (obj instanceof SharedUserSetting) {
16088            final SharedUserSetting sus = (SharedUserSetting) obj;
16089            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
16090            final Iterator<PackageSetting> it = sus.packages.iterator();
16091            while (it.hasNext()) {
16092                final PackageSetting ps = it.next();
16093                if (ps.pkg != null) {
16094                    int v = ps.pkg.applicationInfo.targetSdkVersion;
16095                    if (v < vers) vers = v;
16096                }
16097            }
16098            return vers;
16099        } else if (obj instanceof PackageSetting) {
16100            final PackageSetting ps = (PackageSetting) obj;
16101            if (ps.pkg != null) {
16102                return ps.pkg.applicationInfo.targetSdkVersion;
16103            }
16104        }
16105        return Build.VERSION_CODES.CUR_DEVELOPMENT;
16106    }
16107
16108    @Override
16109    public void addPreferredActivity(IntentFilter filter, int match,
16110            ComponentName[] set, ComponentName activity, int userId) {
16111        addPreferredActivityInternal(filter, match, set, activity, true, userId,
16112                "Adding preferred");
16113    }
16114
16115    private void addPreferredActivityInternal(IntentFilter filter, int match,
16116            ComponentName[] set, ComponentName activity, boolean always, int userId,
16117            String opname) {
16118        // writer
16119        int callingUid = Binder.getCallingUid();
16120        enforceCrossUserPermission(callingUid, userId,
16121                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
16122        if (filter.countActions() == 0) {
16123            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16124            return;
16125        }
16126        synchronized (mPackages) {
16127            if (mContext.checkCallingOrSelfPermission(
16128                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16129                    != PackageManager.PERMISSION_GRANTED) {
16130                if (getUidTargetSdkVersionLockedLPr(callingUid)
16131                        < Build.VERSION_CODES.FROYO) {
16132                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
16133                            + callingUid);
16134                    return;
16135                }
16136                mContext.enforceCallingOrSelfPermission(
16137                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16138            }
16139
16140            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
16141            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
16142                    + userId + ":");
16143            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16144            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
16145            scheduleWritePackageRestrictionsLocked(userId);
16146        }
16147    }
16148
16149    @Override
16150    public void replacePreferredActivity(IntentFilter filter, int match,
16151            ComponentName[] set, ComponentName activity, int userId) {
16152        if (filter.countActions() != 1) {
16153            throw new IllegalArgumentException(
16154                    "replacePreferredActivity expects filter to have only 1 action.");
16155        }
16156        if (filter.countDataAuthorities() != 0
16157                || filter.countDataPaths() != 0
16158                || filter.countDataSchemes() > 1
16159                || filter.countDataTypes() != 0) {
16160            throw new IllegalArgumentException(
16161                    "replacePreferredActivity expects filter to have no data authorities, " +
16162                    "paths, or types; and at most one scheme.");
16163        }
16164
16165        final int callingUid = Binder.getCallingUid();
16166        enforceCrossUserPermission(callingUid, userId,
16167                true /* requireFullPermission */, false /* checkShell */,
16168                "replace preferred activity");
16169        synchronized (mPackages) {
16170            if (mContext.checkCallingOrSelfPermission(
16171                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16172                    != PackageManager.PERMISSION_GRANTED) {
16173                if (getUidTargetSdkVersionLockedLPr(callingUid)
16174                        < Build.VERSION_CODES.FROYO) {
16175                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
16176                            + Binder.getCallingUid());
16177                    return;
16178                }
16179                mContext.enforceCallingOrSelfPermission(
16180                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16181            }
16182
16183            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16184            if (pir != null) {
16185                // Get all of the existing entries that exactly match this filter.
16186                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
16187                if (existing != null && existing.size() == 1) {
16188                    PreferredActivity cur = existing.get(0);
16189                    if (DEBUG_PREFERRED) {
16190                        Slog.i(TAG, "Checking replace of preferred:");
16191                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16192                        if (!cur.mPref.mAlways) {
16193                            Slog.i(TAG, "  -- CUR; not mAlways!");
16194                        } else {
16195                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
16196                            Slog.i(TAG, "  -- CUR: mSet="
16197                                    + Arrays.toString(cur.mPref.mSetComponents));
16198                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
16199                            Slog.i(TAG, "  -- NEW: mMatch="
16200                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
16201                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
16202                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
16203                        }
16204                    }
16205                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
16206                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
16207                            && cur.mPref.sameSet(set)) {
16208                        // Setting the preferred activity to what it happens to be already
16209                        if (DEBUG_PREFERRED) {
16210                            Slog.i(TAG, "Replacing with same preferred activity "
16211                                    + cur.mPref.mShortComponent + " for user "
16212                                    + userId + ":");
16213                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16214                        }
16215                        return;
16216                    }
16217                }
16218
16219                if (existing != null) {
16220                    if (DEBUG_PREFERRED) {
16221                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
16222                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16223                    }
16224                    for (int i = 0; i < existing.size(); i++) {
16225                        PreferredActivity pa = existing.get(i);
16226                        if (DEBUG_PREFERRED) {
16227                            Slog.i(TAG, "Removing existing preferred activity "
16228                                    + pa.mPref.mComponent + ":");
16229                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
16230                        }
16231                        pir.removeFilter(pa);
16232                    }
16233                }
16234            }
16235            addPreferredActivityInternal(filter, match, set, activity, true, userId,
16236                    "Replacing preferred");
16237        }
16238    }
16239
16240    @Override
16241    public void clearPackagePreferredActivities(String packageName) {
16242        final int uid = Binder.getCallingUid();
16243        // writer
16244        synchronized (mPackages) {
16245            PackageParser.Package pkg = mPackages.get(packageName);
16246            if (pkg == null || pkg.applicationInfo.uid != uid) {
16247                if (mContext.checkCallingOrSelfPermission(
16248                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
16249                        != PackageManager.PERMISSION_GRANTED) {
16250                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
16251                            < Build.VERSION_CODES.FROYO) {
16252                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
16253                                + Binder.getCallingUid());
16254                        return;
16255                    }
16256                    mContext.enforceCallingOrSelfPermission(
16257                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16258                }
16259            }
16260
16261            int user = UserHandle.getCallingUserId();
16262            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
16263                scheduleWritePackageRestrictionsLocked(user);
16264            }
16265        }
16266    }
16267
16268    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16269    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
16270        ArrayList<PreferredActivity> removed = null;
16271        boolean changed = false;
16272        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
16273            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
16274            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
16275            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
16276                continue;
16277            }
16278            Iterator<PreferredActivity> it = pir.filterIterator();
16279            while (it.hasNext()) {
16280                PreferredActivity pa = it.next();
16281                // Mark entry for removal only if it matches the package name
16282                // and the entry is of type "always".
16283                if (packageName == null ||
16284                        (pa.mPref.mComponent.getPackageName().equals(packageName)
16285                                && pa.mPref.mAlways)) {
16286                    if (removed == null) {
16287                        removed = new ArrayList<PreferredActivity>();
16288                    }
16289                    removed.add(pa);
16290                }
16291            }
16292            if (removed != null) {
16293                for (int j=0; j<removed.size(); j++) {
16294                    PreferredActivity pa = removed.get(j);
16295                    pir.removeFilter(pa);
16296                }
16297                changed = true;
16298            }
16299        }
16300        return changed;
16301    }
16302
16303    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16304    private void clearIntentFilterVerificationsLPw(int userId) {
16305        final int packageCount = mPackages.size();
16306        for (int i = 0; i < packageCount; i++) {
16307            PackageParser.Package pkg = mPackages.valueAt(i);
16308            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
16309        }
16310    }
16311
16312    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
16313    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
16314        if (userId == UserHandle.USER_ALL) {
16315            if (mSettings.removeIntentFilterVerificationLPw(packageName,
16316                    sUserManager.getUserIds())) {
16317                for (int oneUserId : sUserManager.getUserIds()) {
16318                    scheduleWritePackageRestrictionsLocked(oneUserId);
16319                }
16320            }
16321        } else {
16322            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
16323                scheduleWritePackageRestrictionsLocked(userId);
16324            }
16325        }
16326    }
16327
16328    void clearDefaultBrowserIfNeeded(String packageName) {
16329        for (int oneUserId : sUserManager.getUserIds()) {
16330            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
16331            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
16332            if (packageName.equals(defaultBrowserPackageName)) {
16333                setDefaultBrowserPackageName(null, oneUserId);
16334            }
16335        }
16336    }
16337
16338    @Override
16339    public void resetApplicationPreferences(int userId) {
16340        mContext.enforceCallingOrSelfPermission(
16341                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
16342        // writer
16343        synchronized (mPackages) {
16344            final long identity = Binder.clearCallingIdentity();
16345            try {
16346                clearPackagePreferredActivitiesLPw(null, userId);
16347                mSettings.applyDefaultPreferredAppsLPw(this, userId);
16348                // TODO: We have to reset the default SMS and Phone. This requires
16349                // significant refactoring to keep all default apps in the package
16350                // manager (cleaner but more work) or have the services provide
16351                // callbacks to the package manager to request a default app reset.
16352                applyFactoryDefaultBrowserLPw(userId);
16353                clearIntentFilterVerificationsLPw(userId);
16354                primeDomainVerificationsLPw(userId);
16355                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
16356                scheduleWritePackageRestrictionsLocked(userId);
16357            } finally {
16358                Binder.restoreCallingIdentity(identity);
16359            }
16360        }
16361    }
16362
16363    @Override
16364    public int getPreferredActivities(List<IntentFilter> outFilters,
16365            List<ComponentName> outActivities, String packageName) {
16366
16367        int num = 0;
16368        final int userId = UserHandle.getCallingUserId();
16369        // reader
16370        synchronized (mPackages) {
16371            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
16372            if (pir != null) {
16373                final Iterator<PreferredActivity> it = pir.filterIterator();
16374                while (it.hasNext()) {
16375                    final PreferredActivity pa = it.next();
16376                    if (packageName == null
16377                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
16378                                    && pa.mPref.mAlways)) {
16379                        if (outFilters != null) {
16380                            outFilters.add(new IntentFilter(pa));
16381                        }
16382                        if (outActivities != null) {
16383                            outActivities.add(pa.mPref.mComponent);
16384                        }
16385                    }
16386                }
16387            }
16388        }
16389
16390        return num;
16391    }
16392
16393    @Override
16394    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
16395            int userId) {
16396        int callingUid = Binder.getCallingUid();
16397        if (callingUid != Process.SYSTEM_UID) {
16398            throw new SecurityException(
16399                    "addPersistentPreferredActivity can only be run by the system");
16400        }
16401        if (filter.countActions() == 0) {
16402            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
16403            return;
16404        }
16405        synchronized (mPackages) {
16406            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
16407                    ":");
16408            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
16409            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
16410                    new PersistentPreferredActivity(filter, activity));
16411            scheduleWritePackageRestrictionsLocked(userId);
16412        }
16413    }
16414
16415    @Override
16416    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
16417        int callingUid = Binder.getCallingUid();
16418        if (callingUid != Process.SYSTEM_UID) {
16419            throw new SecurityException(
16420                    "clearPackagePersistentPreferredActivities can only be run by the system");
16421        }
16422        ArrayList<PersistentPreferredActivity> removed = null;
16423        boolean changed = false;
16424        synchronized (mPackages) {
16425            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
16426                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
16427                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
16428                        .valueAt(i);
16429                if (userId != thisUserId) {
16430                    continue;
16431                }
16432                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
16433                while (it.hasNext()) {
16434                    PersistentPreferredActivity ppa = it.next();
16435                    // Mark entry for removal only if it matches the package name.
16436                    if (ppa.mComponent.getPackageName().equals(packageName)) {
16437                        if (removed == null) {
16438                            removed = new ArrayList<PersistentPreferredActivity>();
16439                        }
16440                        removed.add(ppa);
16441                    }
16442                }
16443                if (removed != null) {
16444                    for (int j=0; j<removed.size(); j++) {
16445                        PersistentPreferredActivity ppa = removed.get(j);
16446                        ppir.removeFilter(ppa);
16447                    }
16448                    changed = true;
16449                }
16450            }
16451
16452            if (changed) {
16453                scheduleWritePackageRestrictionsLocked(userId);
16454            }
16455        }
16456    }
16457
16458    /**
16459     * Common machinery for picking apart a restored XML blob and passing
16460     * it to a caller-supplied functor to be applied to the running system.
16461     */
16462    private void restoreFromXml(XmlPullParser parser, int userId,
16463            String expectedStartTag, BlobXmlRestorer functor)
16464            throws IOException, XmlPullParserException {
16465        int type;
16466        while ((type = parser.next()) != XmlPullParser.START_TAG
16467                && type != XmlPullParser.END_DOCUMENT) {
16468        }
16469        if (type != XmlPullParser.START_TAG) {
16470            // oops didn't find a start tag?!
16471            if (DEBUG_BACKUP) {
16472                Slog.e(TAG, "Didn't find start tag during restore");
16473            }
16474            return;
16475        }
16476Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
16477        // this is supposed to be TAG_PREFERRED_BACKUP
16478        if (!expectedStartTag.equals(parser.getName())) {
16479            if (DEBUG_BACKUP) {
16480                Slog.e(TAG, "Found unexpected tag " + parser.getName());
16481            }
16482            return;
16483        }
16484
16485        // skip interfering stuff, then we're aligned with the backing implementation
16486        while ((type = parser.next()) == XmlPullParser.TEXT) { }
16487Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
16488        functor.apply(parser, userId);
16489    }
16490
16491    private interface BlobXmlRestorer {
16492        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
16493    }
16494
16495    /**
16496     * Non-Binder method, support for the backup/restore mechanism: write the
16497     * full set of preferred activities in its canonical XML format.  Returns the
16498     * XML output as a byte array, or null if there is none.
16499     */
16500    @Override
16501    public byte[] getPreferredActivityBackup(int userId) {
16502        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16503            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
16504        }
16505
16506        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16507        try {
16508            final XmlSerializer serializer = new FastXmlSerializer();
16509            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16510            serializer.startDocument(null, true);
16511            serializer.startTag(null, TAG_PREFERRED_BACKUP);
16512
16513            synchronized (mPackages) {
16514                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
16515            }
16516
16517            serializer.endTag(null, TAG_PREFERRED_BACKUP);
16518            serializer.endDocument();
16519            serializer.flush();
16520        } catch (Exception e) {
16521            if (DEBUG_BACKUP) {
16522                Slog.e(TAG, "Unable to write preferred activities for backup", e);
16523            }
16524            return null;
16525        }
16526
16527        return dataStream.toByteArray();
16528    }
16529
16530    @Override
16531    public void restorePreferredActivities(byte[] backup, int userId) {
16532        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16533            throw new SecurityException("Only the system may call restorePreferredActivities()");
16534        }
16535
16536        try {
16537            final XmlPullParser parser = Xml.newPullParser();
16538            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16539            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
16540                    new BlobXmlRestorer() {
16541                        @Override
16542                        public void apply(XmlPullParser parser, int userId)
16543                                throws XmlPullParserException, IOException {
16544                            synchronized (mPackages) {
16545                                mSettings.readPreferredActivitiesLPw(parser, userId);
16546                            }
16547                        }
16548                    } );
16549        } catch (Exception e) {
16550            if (DEBUG_BACKUP) {
16551                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16552            }
16553        }
16554    }
16555
16556    /**
16557     * Non-Binder method, support for the backup/restore mechanism: write the
16558     * default browser (etc) settings in its canonical XML format.  Returns the default
16559     * browser XML representation as a byte array, or null if there is none.
16560     */
16561    @Override
16562    public byte[] getDefaultAppsBackup(int userId) {
16563        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16564            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
16565        }
16566
16567        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16568        try {
16569            final XmlSerializer serializer = new FastXmlSerializer();
16570            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16571            serializer.startDocument(null, true);
16572            serializer.startTag(null, TAG_DEFAULT_APPS);
16573
16574            synchronized (mPackages) {
16575                mSettings.writeDefaultAppsLPr(serializer, userId);
16576            }
16577
16578            serializer.endTag(null, TAG_DEFAULT_APPS);
16579            serializer.endDocument();
16580            serializer.flush();
16581        } catch (Exception e) {
16582            if (DEBUG_BACKUP) {
16583                Slog.e(TAG, "Unable to write default apps for backup", e);
16584            }
16585            return null;
16586        }
16587
16588        return dataStream.toByteArray();
16589    }
16590
16591    @Override
16592    public void restoreDefaultApps(byte[] backup, int userId) {
16593        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16594            throw new SecurityException("Only the system may call restoreDefaultApps()");
16595        }
16596
16597        try {
16598            final XmlPullParser parser = Xml.newPullParser();
16599            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16600            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
16601                    new BlobXmlRestorer() {
16602                        @Override
16603                        public void apply(XmlPullParser parser, int userId)
16604                                throws XmlPullParserException, IOException {
16605                            synchronized (mPackages) {
16606                                mSettings.readDefaultAppsLPw(parser, userId);
16607                            }
16608                        }
16609                    } );
16610        } catch (Exception e) {
16611            if (DEBUG_BACKUP) {
16612                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
16613            }
16614        }
16615    }
16616
16617    @Override
16618    public byte[] getIntentFilterVerificationBackup(int userId) {
16619        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16620            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
16621        }
16622
16623        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16624        try {
16625            final XmlSerializer serializer = new FastXmlSerializer();
16626            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16627            serializer.startDocument(null, true);
16628            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
16629
16630            synchronized (mPackages) {
16631                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
16632            }
16633
16634            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
16635            serializer.endDocument();
16636            serializer.flush();
16637        } catch (Exception e) {
16638            if (DEBUG_BACKUP) {
16639                Slog.e(TAG, "Unable to write default apps for backup", e);
16640            }
16641            return null;
16642        }
16643
16644        return dataStream.toByteArray();
16645    }
16646
16647    @Override
16648    public void restoreIntentFilterVerification(byte[] backup, int userId) {
16649        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16650            throw new SecurityException("Only the system may call restorePreferredActivities()");
16651        }
16652
16653        try {
16654            final XmlPullParser parser = Xml.newPullParser();
16655            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16656            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
16657                    new BlobXmlRestorer() {
16658                        @Override
16659                        public void apply(XmlPullParser parser, int userId)
16660                                throws XmlPullParserException, IOException {
16661                            synchronized (mPackages) {
16662                                mSettings.readAllDomainVerificationsLPr(parser, userId);
16663                                mSettings.writeLPr();
16664                            }
16665                        }
16666                    } );
16667        } catch (Exception e) {
16668            if (DEBUG_BACKUP) {
16669                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16670            }
16671        }
16672    }
16673
16674    @Override
16675    public byte[] getPermissionGrantBackup(int userId) {
16676        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16677            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
16678        }
16679
16680        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
16681        try {
16682            final XmlSerializer serializer = new FastXmlSerializer();
16683            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
16684            serializer.startDocument(null, true);
16685            serializer.startTag(null, TAG_PERMISSION_BACKUP);
16686
16687            synchronized (mPackages) {
16688                serializeRuntimePermissionGrantsLPr(serializer, userId);
16689            }
16690
16691            serializer.endTag(null, TAG_PERMISSION_BACKUP);
16692            serializer.endDocument();
16693            serializer.flush();
16694        } catch (Exception e) {
16695            if (DEBUG_BACKUP) {
16696                Slog.e(TAG, "Unable to write default apps for backup", e);
16697            }
16698            return null;
16699        }
16700
16701        return dataStream.toByteArray();
16702    }
16703
16704    @Override
16705    public void restorePermissionGrants(byte[] backup, int userId) {
16706        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
16707            throw new SecurityException("Only the system may call restorePermissionGrants()");
16708        }
16709
16710        try {
16711            final XmlPullParser parser = Xml.newPullParser();
16712            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
16713            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
16714                    new BlobXmlRestorer() {
16715                        @Override
16716                        public void apply(XmlPullParser parser, int userId)
16717                                throws XmlPullParserException, IOException {
16718                            synchronized (mPackages) {
16719                                processRestoredPermissionGrantsLPr(parser, userId);
16720                            }
16721                        }
16722                    } );
16723        } catch (Exception e) {
16724            if (DEBUG_BACKUP) {
16725                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
16726            }
16727        }
16728    }
16729
16730    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
16731            throws IOException {
16732        serializer.startTag(null, TAG_ALL_GRANTS);
16733
16734        final int N = mSettings.mPackages.size();
16735        for (int i = 0; i < N; i++) {
16736            final PackageSetting ps = mSettings.mPackages.valueAt(i);
16737            boolean pkgGrantsKnown = false;
16738
16739            PermissionsState packagePerms = ps.getPermissionsState();
16740
16741            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
16742                final int grantFlags = state.getFlags();
16743                // only look at grants that are not system/policy fixed
16744                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
16745                    final boolean isGranted = state.isGranted();
16746                    // And only back up the user-twiddled state bits
16747                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
16748                        final String packageName = mSettings.mPackages.keyAt(i);
16749                        if (!pkgGrantsKnown) {
16750                            serializer.startTag(null, TAG_GRANT);
16751                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
16752                            pkgGrantsKnown = true;
16753                        }
16754
16755                        final boolean userSet =
16756                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
16757                        final boolean userFixed =
16758                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
16759                        final boolean revoke =
16760                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
16761
16762                        serializer.startTag(null, TAG_PERMISSION);
16763                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
16764                        if (isGranted) {
16765                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
16766                        }
16767                        if (userSet) {
16768                            serializer.attribute(null, ATTR_USER_SET, "true");
16769                        }
16770                        if (userFixed) {
16771                            serializer.attribute(null, ATTR_USER_FIXED, "true");
16772                        }
16773                        if (revoke) {
16774                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
16775                        }
16776                        serializer.endTag(null, TAG_PERMISSION);
16777                    }
16778                }
16779            }
16780
16781            if (pkgGrantsKnown) {
16782                serializer.endTag(null, TAG_GRANT);
16783            }
16784        }
16785
16786        serializer.endTag(null, TAG_ALL_GRANTS);
16787    }
16788
16789    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
16790            throws XmlPullParserException, IOException {
16791        String pkgName = null;
16792        int outerDepth = parser.getDepth();
16793        int type;
16794        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
16795                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
16796            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
16797                continue;
16798            }
16799
16800            final String tagName = parser.getName();
16801            if (tagName.equals(TAG_GRANT)) {
16802                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
16803                if (DEBUG_BACKUP) {
16804                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
16805                }
16806            } else if (tagName.equals(TAG_PERMISSION)) {
16807
16808                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
16809                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
16810
16811                int newFlagSet = 0;
16812                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
16813                    newFlagSet |= FLAG_PERMISSION_USER_SET;
16814                }
16815                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
16816                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
16817                }
16818                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
16819                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
16820                }
16821                if (DEBUG_BACKUP) {
16822                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
16823                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
16824                }
16825                final PackageSetting ps = mSettings.mPackages.get(pkgName);
16826                if (ps != null) {
16827                    // Already installed so we apply the grant immediately
16828                    if (DEBUG_BACKUP) {
16829                        Slog.v(TAG, "        + already installed; applying");
16830                    }
16831                    PermissionsState perms = ps.getPermissionsState();
16832                    BasePermission bp = mSettings.mPermissions.get(permName);
16833                    if (bp != null) {
16834                        if (isGranted) {
16835                            perms.grantRuntimePermission(bp, userId);
16836                        }
16837                        if (newFlagSet != 0) {
16838                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
16839                        }
16840                    }
16841                } else {
16842                    // Need to wait for post-restore install to apply the grant
16843                    if (DEBUG_BACKUP) {
16844                        Slog.v(TAG, "        - not yet installed; saving for later");
16845                    }
16846                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
16847                            isGranted, newFlagSet, userId);
16848                }
16849            } else {
16850                PackageManagerService.reportSettingsProblem(Log.WARN,
16851                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
16852                XmlUtils.skipCurrentTag(parser);
16853            }
16854        }
16855
16856        scheduleWriteSettingsLocked();
16857        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
16858    }
16859
16860    @Override
16861    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
16862            int sourceUserId, int targetUserId, int flags) {
16863        mContext.enforceCallingOrSelfPermission(
16864                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16865        int callingUid = Binder.getCallingUid();
16866        enforceOwnerRights(ownerPackage, callingUid);
16867        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16868        if (intentFilter.countActions() == 0) {
16869            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
16870            return;
16871        }
16872        synchronized (mPackages) {
16873            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
16874                    ownerPackage, targetUserId, flags);
16875            CrossProfileIntentResolver resolver =
16876                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16877            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
16878            // We have all those whose filter is equal. Now checking if the rest is equal as well.
16879            if (existing != null) {
16880                int size = existing.size();
16881                for (int i = 0; i < size; i++) {
16882                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
16883                        return;
16884                    }
16885                }
16886            }
16887            resolver.addFilter(newFilter);
16888            scheduleWritePackageRestrictionsLocked(sourceUserId);
16889        }
16890    }
16891
16892    @Override
16893    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
16894        mContext.enforceCallingOrSelfPermission(
16895                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
16896        int callingUid = Binder.getCallingUid();
16897        enforceOwnerRights(ownerPackage, callingUid);
16898        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
16899        synchronized (mPackages) {
16900            CrossProfileIntentResolver resolver =
16901                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
16902            ArraySet<CrossProfileIntentFilter> set =
16903                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
16904            for (CrossProfileIntentFilter filter : set) {
16905                if (filter.getOwnerPackage().equals(ownerPackage)) {
16906                    resolver.removeFilter(filter);
16907                }
16908            }
16909            scheduleWritePackageRestrictionsLocked(sourceUserId);
16910        }
16911    }
16912
16913    // Enforcing that callingUid is owning pkg on userId
16914    private void enforceOwnerRights(String pkg, int callingUid) {
16915        // The system owns everything.
16916        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
16917            return;
16918        }
16919        int callingUserId = UserHandle.getUserId(callingUid);
16920        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
16921        if (pi == null) {
16922            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
16923                    + callingUserId);
16924        }
16925        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
16926            throw new SecurityException("Calling uid " + callingUid
16927                    + " does not own package " + pkg);
16928        }
16929    }
16930
16931    @Override
16932    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
16933        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
16934    }
16935
16936    private Intent getHomeIntent() {
16937        Intent intent = new Intent(Intent.ACTION_MAIN);
16938        intent.addCategory(Intent.CATEGORY_HOME);
16939        return intent;
16940    }
16941
16942    private IntentFilter getHomeFilter() {
16943        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
16944        filter.addCategory(Intent.CATEGORY_HOME);
16945        filter.addCategory(Intent.CATEGORY_DEFAULT);
16946        return filter;
16947    }
16948
16949    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
16950            int userId) {
16951        Intent intent  = getHomeIntent();
16952        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
16953                PackageManager.GET_META_DATA, userId);
16954        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
16955                true, false, false, userId);
16956
16957        allHomeCandidates.clear();
16958        if (list != null) {
16959            for (ResolveInfo ri : list) {
16960                allHomeCandidates.add(ri);
16961            }
16962        }
16963        return (preferred == null || preferred.activityInfo == null)
16964                ? null
16965                : new ComponentName(preferred.activityInfo.packageName,
16966                        preferred.activityInfo.name);
16967    }
16968
16969    @Override
16970    public void setHomeActivity(ComponentName comp, int userId) {
16971        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
16972        getHomeActivitiesAsUser(homeActivities, userId);
16973
16974        boolean found = false;
16975
16976        final int size = homeActivities.size();
16977        final ComponentName[] set = new ComponentName[size];
16978        for (int i = 0; i < size; i++) {
16979            final ResolveInfo candidate = homeActivities.get(i);
16980            final ActivityInfo info = candidate.activityInfo;
16981            final ComponentName activityName = new ComponentName(info.packageName, info.name);
16982            set[i] = activityName;
16983            if (!found && activityName.equals(comp)) {
16984                found = true;
16985            }
16986        }
16987        if (!found) {
16988            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
16989                    + userId);
16990        }
16991        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
16992                set, comp, userId);
16993    }
16994
16995    private @Nullable String getSetupWizardPackageName() {
16996        final Intent intent = new Intent(Intent.ACTION_MAIN);
16997        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
16998
16999        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
17000                MATCH_SYSTEM_ONLY | MATCH_DISABLED_COMPONENTS, UserHandle.myUserId());
17001        if (matches.size() == 1) {
17002            return matches.get(0).getComponentInfo().packageName;
17003        } else {
17004            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
17005                    + ": matches=" + matches);
17006            return null;
17007        }
17008    }
17009
17010    @Override
17011    public void setApplicationEnabledSetting(String appPackageName,
17012            int newState, int flags, int userId, String callingPackage) {
17013        if (!sUserManager.exists(userId)) return;
17014        if (callingPackage == null) {
17015            callingPackage = Integer.toString(Binder.getCallingUid());
17016        }
17017        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
17018    }
17019
17020    @Override
17021    public void setComponentEnabledSetting(ComponentName componentName,
17022            int newState, int flags, int userId) {
17023        if (!sUserManager.exists(userId)) return;
17024        setEnabledSetting(componentName.getPackageName(),
17025                componentName.getClassName(), newState, flags, userId, null);
17026    }
17027
17028    private void setEnabledSetting(final String packageName, String className, int newState,
17029            final int flags, int userId, String callingPackage) {
17030        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
17031              || newState == COMPONENT_ENABLED_STATE_ENABLED
17032              || newState == COMPONENT_ENABLED_STATE_DISABLED
17033              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
17034              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
17035            throw new IllegalArgumentException("Invalid new component state: "
17036                    + newState);
17037        }
17038        PackageSetting pkgSetting;
17039        final int uid = Binder.getCallingUid();
17040        final int permission = mContext.checkCallingOrSelfPermission(
17041                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17042        enforceCrossUserPermission(uid, userId,
17043                false /* requireFullPermission */, true /* checkShell */, "set enabled");
17044        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17045        boolean sendNow = false;
17046        boolean isApp = (className == null);
17047        String componentName = isApp ? packageName : className;
17048        int packageUid = -1;
17049        ArrayList<String> components;
17050
17051        // writer
17052        synchronized (mPackages) {
17053            pkgSetting = mSettings.mPackages.get(packageName);
17054            if (pkgSetting == null) {
17055                if (className == null) {
17056                    throw new IllegalArgumentException("Unknown package: " + packageName);
17057                }
17058                throw new IllegalArgumentException(
17059                        "Unknown component: " + packageName + "/" + className);
17060            }
17061            // Allow root and verify that userId is not being specified by a different user
17062            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
17063                throw new SecurityException(
17064                        "Permission Denial: attempt to change component state from pid="
17065                        + Binder.getCallingPid()
17066                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
17067            }
17068            if (className == null) {
17069                // We're dealing with an application/package level state change
17070                if (pkgSetting.getEnabled(userId) == newState) {
17071                    // Nothing to do
17072                    return;
17073                }
17074                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
17075                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
17076                    // Don't care about who enables an app.
17077                    callingPackage = null;
17078                }
17079                pkgSetting.setEnabled(newState, userId, callingPackage);
17080                // pkgSetting.pkg.mSetEnabled = newState;
17081            } else {
17082                // We're dealing with a component level state change
17083                // First, verify that this is a valid class name.
17084                PackageParser.Package pkg = pkgSetting.pkg;
17085                if (pkg == null || !pkg.hasComponentClassName(className)) {
17086                    if (pkg != null &&
17087                            pkg.applicationInfo.targetSdkVersion >=
17088                                    Build.VERSION_CODES.JELLY_BEAN) {
17089                        throw new IllegalArgumentException("Component class " + className
17090                                + " does not exist in " + packageName);
17091                    } else {
17092                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
17093                                + className + " does not exist in " + packageName);
17094                    }
17095                }
17096                switch (newState) {
17097                case COMPONENT_ENABLED_STATE_ENABLED:
17098                    if (!pkgSetting.enableComponentLPw(className, userId)) {
17099                        return;
17100                    }
17101                    break;
17102                case COMPONENT_ENABLED_STATE_DISABLED:
17103                    if (!pkgSetting.disableComponentLPw(className, userId)) {
17104                        return;
17105                    }
17106                    break;
17107                case COMPONENT_ENABLED_STATE_DEFAULT:
17108                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
17109                        return;
17110                    }
17111                    break;
17112                default:
17113                    Slog.e(TAG, "Invalid new component state: " + newState);
17114                    return;
17115                }
17116            }
17117            scheduleWritePackageRestrictionsLocked(userId);
17118            components = mPendingBroadcasts.get(userId, packageName);
17119            final boolean newPackage = components == null;
17120            if (newPackage) {
17121                components = new ArrayList<String>();
17122            }
17123            if (!components.contains(componentName)) {
17124                components.add(componentName);
17125            }
17126            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
17127                sendNow = true;
17128                // Purge entry from pending broadcast list if another one exists already
17129                // since we are sending one right away.
17130                mPendingBroadcasts.remove(userId, packageName);
17131            } else {
17132                if (newPackage) {
17133                    mPendingBroadcasts.put(userId, packageName, components);
17134                }
17135                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
17136                    // Schedule a message
17137                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
17138                }
17139            }
17140        }
17141
17142        long callingId = Binder.clearCallingIdentity();
17143        try {
17144            if (sendNow) {
17145                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
17146                sendPackageChangedBroadcast(packageName,
17147                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
17148            }
17149        } finally {
17150            Binder.restoreCallingIdentity(callingId);
17151        }
17152    }
17153
17154    @Override
17155    public void flushPackageRestrictionsAsUser(int userId) {
17156        if (!sUserManager.exists(userId)) {
17157            return;
17158        }
17159        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
17160                false /* checkShell */, "flushPackageRestrictions");
17161        synchronized (mPackages) {
17162            mSettings.writePackageRestrictionsLPr(userId);
17163            mDirtyUsers.remove(userId);
17164            if (mDirtyUsers.isEmpty()) {
17165                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
17166            }
17167        }
17168    }
17169
17170    private void sendPackageChangedBroadcast(String packageName,
17171            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
17172        if (DEBUG_INSTALL)
17173            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
17174                    + componentNames);
17175        Bundle extras = new Bundle(4);
17176        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
17177        String nameList[] = new String[componentNames.size()];
17178        componentNames.toArray(nameList);
17179        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
17180        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
17181        extras.putInt(Intent.EXTRA_UID, packageUid);
17182        // If this is not reporting a change of the overall package, then only send it
17183        // to registered receivers.  We don't want to launch a swath of apps for every
17184        // little component state change.
17185        final int flags = !componentNames.contains(packageName)
17186                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
17187        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
17188                new int[] {UserHandle.getUserId(packageUid)});
17189    }
17190
17191    @Override
17192    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
17193        if (!sUserManager.exists(userId)) return;
17194        final int uid = Binder.getCallingUid();
17195        final int permission = mContext.checkCallingOrSelfPermission(
17196                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
17197        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
17198        enforceCrossUserPermission(uid, userId,
17199                true /* requireFullPermission */, true /* checkShell */, "stop package");
17200        // writer
17201        synchronized (mPackages) {
17202            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
17203                    allowedByPermission, uid, userId)) {
17204                scheduleWritePackageRestrictionsLocked(userId);
17205            }
17206        }
17207    }
17208
17209    @Override
17210    public String getInstallerPackageName(String packageName) {
17211        // reader
17212        synchronized (mPackages) {
17213            return mSettings.getInstallerPackageNameLPr(packageName);
17214        }
17215    }
17216
17217    @Override
17218    public int getApplicationEnabledSetting(String packageName, int userId) {
17219        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17220        int uid = Binder.getCallingUid();
17221        enforceCrossUserPermission(uid, userId,
17222                false /* requireFullPermission */, false /* checkShell */, "get enabled");
17223        // reader
17224        synchronized (mPackages) {
17225            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
17226        }
17227    }
17228
17229    @Override
17230    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
17231        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
17232        int uid = Binder.getCallingUid();
17233        enforceCrossUserPermission(uid, userId,
17234                false /* requireFullPermission */, false /* checkShell */, "get component enabled");
17235        // reader
17236        synchronized (mPackages) {
17237            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
17238        }
17239    }
17240
17241    @Override
17242    public void enterSafeMode() {
17243        enforceSystemOrRoot("Only the system can request entering safe mode");
17244
17245        if (!mSystemReady) {
17246            mSafeMode = true;
17247        }
17248    }
17249
17250    @Override
17251    public void systemReady() {
17252        mSystemReady = true;
17253
17254        // Read the compatibilty setting when the system is ready.
17255        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
17256                mContext.getContentResolver(),
17257                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
17258        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
17259        if (DEBUG_SETTINGS) {
17260            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
17261        }
17262
17263        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
17264
17265        synchronized (mPackages) {
17266            // Verify that all of the preferred activity components actually
17267            // exist.  It is possible for applications to be updated and at
17268            // that point remove a previously declared activity component that
17269            // had been set as a preferred activity.  We try to clean this up
17270            // the next time we encounter that preferred activity, but it is
17271            // possible for the user flow to never be able to return to that
17272            // situation so here we do a sanity check to make sure we haven't
17273            // left any junk around.
17274            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
17275            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17276                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17277                removed.clear();
17278                for (PreferredActivity pa : pir.filterSet()) {
17279                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
17280                        removed.add(pa);
17281                    }
17282                }
17283                if (removed.size() > 0) {
17284                    for (int r=0; r<removed.size(); r++) {
17285                        PreferredActivity pa = removed.get(r);
17286                        Slog.w(TAG, "Removing dangling preferred activity: "
17287                                + pa.mPref.mComponent);
17288                        pir.removeFilter(pa);
17289                    }
17290                    mSettings.writePackageRestrictionsLPr(
17291                            mSettings.mPreferredActivities.keyAt(i));
17292                }
17293            }
17294
17295            for (int userId : UserManagerService.getInstance().getUserIds()) {
17296                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
17297                    grantPermissionsUserIds = ArrayUtils.appendInt(
17298                            grantPermissionsUserIds, userId);
17299                }
17300            }
17301        }
17302        sUserManager.systemReady();
17303
17304        // If we upgraded grant all default permissions before kicking off.
17305        for (int userId : grantPermissionsUserIds) {
17306            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
17307        }
17308
17309        // Kick off any messages waiting for system ready
17310        if (mPostSystemReadyMessages != null) {
17311            for (Message msg : mPostSystemReadyMessages) {
17312                msg.sendToTarget();
17313            }
17314            mPostSystemReadyMessages = null;
17315        }
17316
17317        // Watch for external volumes that come and go over time
17318        final StorageManager storage = mContext.getSystemService(StorageManager.class);
17319        storage.registerListener(mStorageListener);
17320
17321        mInstallerService.systemReady();
17322        mPackageDexOptimizer.systemReady();
17323
17324        MountServiceInternal mountServiceInternal = LocalServices.getService(
17325                MountServiceInternal.class);
17326        mountServiceInternal.addExternalStoragePolicy(
17327                new MountServiceInternal.ExternalStorageMountPolicy() {
17328            @Override
17329            public int getMountMode(int uid, String packageName) {
17330                if (Process.isIsolated(uid)) {
17331                    return Zygote.MOUNT_EXTERNAL_NONE;
17332                }
17333                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
17334                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17335                }
17336                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17337                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
17338                }
17339                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
17340                    return Zygote.MOUNT_EXTERNAL_READ;
17341                }
17342                return Zygote.MOUNT_EXTERNAL_WRITE;
17343            }
17344
17345            @Override
17346            public boolean hasExternalStorage(int uid, String packageName) {
17347                return true;
17348            }
17349        });
17350    }
17351
17352    @Override
17353    public boolean isSafeMode() {
17354        return mSafeMode;
17355    }
17356
17357    @Override
17358    public boolean hasSystemUidErrors() {
17359        return mHasSystemUidErrors;
17360    }
17361
17362    static String arrayToString(int[] array) {
17363        StringBuffer buf = new StringBuffer(128);
17364        buf.append('[');
17365        if (array != null) {
17366            for (int i=0; i<array.length; i++) {
17367                if (i > 0) buf.append(", ");
17368                buf.append(array[i]);
17369            }
17370        }
17371        buf.append(']');
17372        return buf.toString();
17373    }
17374
17375    static class DumpState {
17376        public static final int DUMP_LIBS = 1 << 0;
17377        public static final int DUMP_FEATURES = 1 << 1;
17378        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
17379        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
17380        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
17381        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
17382        public static final int DUMP_PERMISSIONS = 1 << 6;
17383        public static final int DUMP_PACKAGES = 1 << 7;
17384        public static final int DUMP_SHARED_USERS = 1 << 8;
17385        public static final int DUMP_MESSAGES = 1 << 9;
17386        public static final int DUMP_PROVIDERS = 1 << 10;
17387        public static final int DUMP_VERIFIERS = 1 << 11;
17388        public static final int DUMP_PREFERRED = 1 << 12;
17389        public static final int DUMP_PREFERRED_XML = 1 << 13;
17390        public static final int DUMP_KEYSETS = 1 << 14;
17391        public static final int DUMP_VERSION = 1 << 15;
17392        public static final int DUMP_INSTALLS = 1 << 16;
17393        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
17394        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
17395
17396        public static final int OPTION_SHOW_FILTERS = 1 << 0;
17397
17398        private int mTypes;
17399
17400        private int mOptions;
17401
17402        private boolean mTitlePrinted;
17403
17404        private SharedUserSetting mSharedUser;
17405
17406        public boolean isDumping(int type) {
17407            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
17408                return true;
17409            }
17410
17411            return (mTypes & type) != 0;
17412        }
17413
17414        public void setDump(int type) {
17415            mTypes |= type;
17416        }
17417
17418        public boolean isOptionEnabled(int option) {
17419            return (mOptions & option) != 0;
17420        }
17421
17422        public void setOptionEnabled(int option) {
17423            mOptions |= option;
17424        }
17425
17426        public boolean onTitlePrinted() {
17427            final boolean printed = mTitlePrinted;
17428            mTitlePrinted = true;
17429            return printed;
17430        }
17431
17432        public boolean getTitlePrinted() {
17433            return mTitlePrinted;
17434        }
17435
17436        public void setTitlePrinted(boolean enabled) {
17437            mTitlePrinted = enabled;
17438        }
17439
17440        public SharedUserSetting getSharedUser() {
17441            return mSharedUser;
17442        }
17443
17444        public void setSharedUser(SharedUserSetting user) {
17445            mSharedUser = user;
17446        }
17447    }
17448
17449    @Override
17450    public void onShellCommand(FileDescriptor in, FileDescriptor out,
17451            FileDescriptor err, String[] args, ResultReceiver resultReceiver) {
17452        (new PackageManagerShellCommand(this)).exec(
17453                this, in, out, err, args, resultReceiver);
17454    }
17455
17456    @Override
17457    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
17458        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
17459                != PackageManager.PERMISSION_GRANTED) {
17460            pw.println("Permission Denial: can't dump ActivityManager from from pid="
17461                    + Binder.getCallingPid()
17462                    + ", uid=" + Binder.getCallingUid()
17463                    + " without permission "
17464                    + android.Manifest.permission.DUMP);
17465            return;
17466        }
17467
17468        DumpState dumpState = new DumpState();
17469        boolean fullPreferred = false;
17470        boolean checkin = false;
17471
17472        String packageName = null;
17473        ArraySet<String> permissionNames = null;
17474
17475        int opti = 0;
17476        while (opti < args.length) {
17477            String opt = args[opti];
17478            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
17479                break;
17480            }
17481            opti++;
17482
17483            if ("-a".equals(opt)) {
17484                // Right now we only know how to print all.
17485            } else if ("-h".equals(opt)) {
17486                pw.println("Package manager dump options:");
17487                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
17488                pw.println("    --checkin: dump for a checkin");
17489                pw.println("    -f: print details of intent filters");
17490                pw.println("    -h: print this help");
17491                pw.println("  cmd may be one of:");
17492                pw.println("    l[ibraries]: list known shared libraries");
17493                pw.println("    f[eatures]: list device features");
17494                pw.println("    k[eysets]: print known keysets");
17495                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
17496                pw.println("    perm[issions]: dump permissions");
17497                pw.println("    permission [name ...]: dump declaration and use of given permission");
17498                pw.println("    pref[erred]: print preferred package settings");
17499                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
17500                pw.println("    prov[iders]: dump content providers");
17501                pw.println("    p[ackages]: dump installed packages");
17502                pw.println("    s[hared-users]: dump shared user IDs");
17503                pw.println("    m[essages]: print collected runtime messages");
17504                pw.println("    v[erifiers]: print package verifier info");
17505                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
17506                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
17507                pw.println("    version: print database version info");
17508                pw.println("    write: write current settings now");
17509                pw.println("    installs: details about install sessions");
17510                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
17511                pw.println("    <package.name>: info about given package");
17512                return;
17513            } else if ("--checkin".equals(opt)) {
17514                checkin = true;
17515            } else if ("-f".equals(opt)) {
17516                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17517            } else {
17518                pw.println("Unknown argument: " + opt + "; use -h for help");
17519            }
17520        }
17521
17522        // Is the caller requesting to dump a particular piece of data?
17523        if (opti < args.length) {
17524            String cmd = args[opti];
17525            opti++;
17526            // Is this a package name?
17527            if ("android".equals(cmd) || cmd.contains(".")) {
17528                packageName = cmd;
17529                // When dumping a single package, we always dump all of its
17530                // filter information since the amount of data will be reasonable.
17531                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
17532            } else if ("check-permission".equals(cmd)) {
17533                if (opti >= args.length) {
17534                    pw.println("Error: check-permission missing permission argument");
17535                    return;
17536                }
17537                String perm = args[opti];
17538                opti++;
17539                if (opti >= args.length) {
17540                    pw.println("Error: check-permission missing package argument");
17541                    return;
17542                }
17543                String pkg = args[opti];
17544                opti++;
17545                int user = UserHandle.getUserId(Binder.getCallingUid());
17546                if (opti < args.length) {
17547                    try {
17548                        user = Integer.parseInt(args[opti]);
17549                    } catch (NumberFormatException e) {
17550                        pw.println("Error: check-permission user argument is not a number: "
17551                                + args[opti]);
17552                        return;
17553                    }
17554                }
17555                pw.println(checkPermission(perm, pkg, user));
17556                return;
17557            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
17558                dumpState.setDump(DumpState.DUMP_LIBS);
17559            } else if ("f".equals(cmd) || "features".equals(cmd)) {
17560                dumpState.setDump(DumpState.DUMP_FEATURES);
17561            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
17562                if (opti >= args.length) {
17563                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
17564                            | DumpState.DUMP_SERVICE_RESOLVERS
17565                            | DumpState.DUMP_RECEIVER_RESOLVERS
17566                            | DumpState.DUMP_CONTENT_RESOLVERS);
17567                } else {
17568                    while (opti < args.length) {
17569                        String name = args[opti];
17570                        if ("a".equals(name) || "activity".equals(name)) {
17571                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
17572                        } else if ("s".equals(name) || "service".equals(name)) {
17573                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
17574                        } else if ("r".equals(name) || "receiver".equals(name)) {
17575                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
17576                        } else if ("c".equals(name) || "content".equals(name)) {
17577                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
17578                        } else {
17579                            pw.println("Error: unknown resolver table type: " + name);
17580                            return;
17581                        }
17582                        opti++;
17583                    }
17584                }
17585            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
17586                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
17587            } else if ("permission".equals(cmd)) {
17588                if (opti >= args.length) {
17589                    pw.println("Error: permission requires permission name");
17590                    return;
17591                }
17592                permissionNames = new ArraySet<>();
17593                while (opti < args.length) {
17594                    permissionNames.add(args[opti]);
17595                    opti++;
17596                }
17597                dumpState.setDump(DumpState.DUMP_PERMISSIONS
17598                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
17599            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
17600                dumpState.setDump(DumpState.DUMP_PREFERRED);
17601            } else if ("preferred-xml".equals(cmd)) {
17602                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
17603                if (opti < args.length && "--full".equals(args[opti])) {
17604                    fullPreferred = true;
17605                    opti++;
17606                }
17607            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
17608                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
17609            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
17610                dumpState.setDump(DumpState.DUMP_PACKAGES);
17611            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
17612                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
17613            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
17614                dumpState.setDump(DumpState.DUMP_PROVIDERS);
17615            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
17616                dumpState.setDump(DumpState.DUMP_MESSAGES);
17617            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
17618                dumpState.setDump(DumpState.DUMP_VERIFIERS);
17619            } else if ("i".equals(cmd) || "ifv".equals(cmd)
17620                    || "intent-filter-verifiers".equals(cmd)) {
17621                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
17622            } else if ("version".equals(cmd)) {
17623                dumpState.setDump(DumpState.DUMP_VERSION);
17624            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
17625                dumpState.setDump(DumpState.DUMP_KEYSETS);
17626            } else if ("installs".equals(cmd)) {
17627                dumpState.setDump(DumpState.DUMP_INSTALLS);
17628            } else if ("write".equals(cmd)) {
17629                synchronized (mPackages) {
17630                    mSettings.writeLPr();
17631                    pw.println("Settings written.");
17632                    return;
17633                }
17634            }
17635        }
17636
17637        if (checkin) {
17638            pw.println("vers,1");
17639        }
17640
17641        // reader
17642        synchronized (mPackages) {
17643            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
17644                if (!checkin) {
17645                    if (dumpState.onTitlePrinted())
17646                        pw.println();
17647                    pw.println("Database versions:");
17648                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
17649                }
17650            }
17651
17652            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
17653                if (!checkin) {
17654                    if (dumpState.onTitlePrinted())
17655                        pw.println();
17656                    pw.println("Verifiers:");
17657                    pw.print("  Required: ");
17658                    pw.print(mRequiredVerifierPackage);
17659                    pw.print(" (uid=");
17660                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17661                            UserHandle.USER_SYSTEM));
17662                    pw.println(")");
17663                } else if (mRequiredVerifierPackage != null) {
17664                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
17665                    pw.print(",");
17666                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
17667                            UserHandle.USER_SYSTEM));
17668                }
17669            }
17670
17671            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
17672                    packageName == null) {
17673                if (mIntentFilterVerifierComponent != null) {
17674                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
17675                    if (!checkin) {
17676                        if (dumpState.onTitlePrinted())
17677                            pw.println();
17678                        pw.println("Intent Filter Verifier:");
17679                        pw.print("  Using: ");
17680                        pw.print(verifierPackageName);
17681                        pw.print(" (uid=");
17682                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17683                                UserHandle.USER_SYSTEM));
17684                        pw.println(")");
17685                    } else if (verifierPackageName != null) {
17686                        pw.print("ifv,"); pw.print(verifierPackageName);
17687                        pw.print(",");
17688                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
17689                                UserHandle.USER_SYSTEM));
17690                    }
17691                } else {
17692                    pw.println();
17693                    pw.println("No Intent Filter Verifier available!");
17694                }
17695            }
17696
17697            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
17698                boolean printedHeader = false;
17699                final Iterator<String> it = mSharedLibraries.keySet().iterator();
17700                while (it.hasNext()) {
17701                    String name = it.next();
17702                    SharedLibraryEntry ent = mSharedLibraries.get(name);
17703                    if (!checkin) {
17704                        if (!printedHeader) {
17705                            if (dumpState.onTitlePrinted())
17706                                pw.println();
17707                            pw.println("Libraries:");
17708                            printedHeader = true;
17709                        }
17710                        pw.print("  ");
17711                    } else {
17712                        pw.print("lib,");
17713                    }
17714                    pw.print(name);
17715                    if (!checkin) {
17716                        pw.print(" -> ");
17717                    }
17718                    if (ent.path != null) {
17719                        if (!checkin) {
17720                            pw.print("(jar) ");
17721                            pw.print(ent.path);
17722                        } else {
17723                            pw.print(",jar,");
17724                            pw.print(ent.path);
17725                        }
17726                    } else {
17727                        if (!checkin) {
17728                            pw.print("(apk) ");
17729                            pw.print(ent.apk);
17730                        } else {
17731                            pw.print(",apk,");
17732                            pw.print(ent.apk);
17733                        }
17734                    }
17735                    pw.println();
17736                }
17737            }
17738
17739            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
17740                if (dumpState.onTitlePrinted())
17741                    pw.println();
17742                if (!checkin) {
17743                    pw.println("Features:");
17744                }
17745
17746                for (FeatureInfo feat : mAvailableFeatures.values()) {
17747                    if (checkin) {
17748                        pw.print("feat,");
17749                        pw.print(feat.name);
17750                        pw.print(",");
17751                        pw.println(feat.version);
17752                    } else {
17753                        pw.print("  ");
17754                        pw.print(feat.name);
17755                        if (feat.version > 0) {
17756                            pw.print(" version=");
17757                            pw.print(feat.version);
17758                        }
17759                        pw.println();
17760                    }
17761                }
17762            }
17763
17764            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
17765                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
17766                        : "Activity Resolver Table:", "  ", packageName,
17767                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17768                    dumpState.setTitlePrinted(true);
17769                }
17770            }
17771            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
17772                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
17773                        : "Receiver Resolver Table:", "  ", packageName,
17774                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17775                    dumpState.setTitlePrinted(true);
17776                }
17777            }
17778            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
17779                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
17780                        : "Service Resolver Table:", "  ", packageName,
17781                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17782                    dumpState.setTitlePrinted(true);
17783                }
17784            }
17785            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
17786                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
17787                        : "Provider Resolver Table:", "  ", packageName,
17788                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
17789                    dumpState.setTitlePrinted(true);
17790                }
17791            }
17792
17793            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
17794                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
17795                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
17796                    int user = mSettings.mPreferredActivities.keyAt(i);
17797                    if (pir.dump(pw,
17798                            dumpState.getTitlePrinted()
17799                                ? "\nPreferred Activities User " + user + ":"
17800                                : "Preferred Activities User " + user + ":", "  ",
17801                            packageName, true, false)) {
17802                        dumpState.setTitlePrinted(true);
17803                    }
17804                }
17805            }
17806
17807            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
17808                pw.flush();
17809                FileOutputStream fout = new FileOutputStream(fd);
17810                BufferedOutputStream str = new BufferedOutputStream(fout);
17811                XmlSerializer serializer = new FastXmlSerializer();
17812                try {
17813                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
17814                    serializer.startDocument(null, true);
17815                    serializer.setFeature(
17816                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
17817                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
17818                    serializer.endDocument();
17819                    serializer.flush();
17820                } catch (IllegalArgumentException e) {
17821                    pw.println("Failed writing: " + e);
17822                } catch (IllegalStateException e) {
17823                    pw.println("Failed writing: " + e);
17824                } catch (IOException e) {
17825                    pw.println("Failed writing: " + e);
17826                }
17827            }
17828
17829            if (!checkin
17830                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
17831                    && packageName == null) {
17832                pw.println();
17833                int count = mSettings.mPackages.size();
17834                if (count == 0) {
17835                    pw.println("No applications!");
17836                    pw.println();
17837                } else {
17838                    final String prefix = "  ";
17839                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
17840                    if (allPackageSettings.size() == 0) {
17841                        pw.println("No domain preferred apps!");
17842                        pw.println();
17843                    } else {
17844                        pw.println("App verification status:");
17845                        pw.println();
17846                        count = 0;
17847                        for (PackageSetting ps : allPackageSettings) {
17848                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
17849                            if (ivi == null || ivi.getPackageName() == null) continue;
17850                            pw.println(prefix + "Package: " + ivi.getPackageName());
17851                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
17852                            pw.println(prefix + "Status:  " + ivi.getStatusString());
17853                            pw.println();
17854                            count++;
17855                        }
17856                        if (count == 0) {
17857                            pw.println(prefix + "No app verification established.");
17858                            pw.println();
17859                        }
17860                        for (int userId : sUserManager.getUserIds()) {
17861                            pw.println("App linkages for user " + userId + ":");
17862                            pw.println();
17863                            count = 0;
17864                            for (PackageSetting ps : allPackageSettings) {
17865                                final long status = ps.getDomainVerificationStatusForUser(userId);
17866                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
17867                                    continue;
17868                                }
17869                                pw.println(prefix + "Package: " + ps.name);
17870                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
17871                                String statusStr = IntentFilterVerificationInfo.
17872                                        getStatusStringFromValue(status);
17873                                pw.println(prefix + "Status:  " + statusStr);
17874                                pw.println();
17875                                count++;
17876                            }
17877                            if (count == 0) {
17878                                pw.println(prefix + "No configured app linkages.");
17879                                pw.println();
17880                            }
17881                        }
17882                    }
17883                }
17884            }
17885
17886            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
17887                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
17888                if (packageName == null && permissionNames == null) {
17889                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
17890                        if (iperm == 0) {
17891                            if (dumpState.onTitlePrinted())
17892                                pw.println();
17893                            pw.println("AppOp Permissions:");
17894                        }
17895                        pw.print("  AppOp Permission ");
17896                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
17897                        pw.println(":");
17898                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
17899                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
17900                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
17901                        }
17902                    }
17903                }
17904            }
17905
17906            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
17907                boolean printedSomething = false;
17908                for (PackageParser.Provider p : mProviders.mProviders.values()) {
17909                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17910                        continue;
17911                    }
17912                    if (!printedSomething) {
17913                        if (dumpState.onTitlePrinted())
17914                            pw.println();
17915                        pw.println("Registered ContentProviders:");
17916                        printedSomething = true;
17917                    }
17918                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
17919                    pw.print("    "); pw.println(p.toString());
17920                }
17921                printedSomething = false;
17922                for (Map.Entry<String, PackageParser.Provider> entry :
17923                        mProvidersByAuthority.entrySet()) {
17924                    PackageParser.Provider p = entry.getValue();
17925                    if (packageName != null && !packageName.equals(p.info.packageName)) {
17926                        continue;
17927                    }
17928                    if (!printedSomething) {
17929                        if (dumpState.onTitlePrinted())
17930                            pw.println();
17931                        pw.println("ContentProvider Authorities:");
17932                        printedSomething = true;
17933                    }
17934                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
17935                    pw.print("    "); pw.println(p.toString());
17936                    if (p.info != null && p.info.applicationInfo != null) {
17937                        final String appInfo = p.info.applicationInfo.toString();
17938                        pw.print("      applicationInfo="); pw.println(appInfo);
17939                    }
17940                }
17941            }
17942
17943            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
17944                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
17945            }
17946
17947            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
17948                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
17949            }
17950
17951            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
17952                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
17953            }
17954
17955            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
17956                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
17957            }
17958
17959            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
17960                // XXX should handle packageName != null by dumping only install data that
17961                // the given package is involved with.
17962                if (dumpState.onTitlePrinted()) pw.println();
17963                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
17964            }
17965
17966            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
17967                if (dumpState.onTitlePrinted()) pw.println();
17968                mSettings.dumpReadMessagesLPr(pw, dumpState);
17969
17970                pw.println();
17971                pw.println("Package warning messages:");
17972                BufferedReader in = null;
17973                String line = null;
17974                try {
17975                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17976                    while ((line = in.readLine()) != null) {
17977                        if (line.contains("ignored: updated version")) continue;
17978                        pw.println(line);
17979                    }
17980                } catch (IOException ignored) {
17981                } finally {
17982                    IoUtils.closeQuietly(in);
17983                }
17984            }
17985
17986            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
17987                BufferedReader in = null;
17988                String line = null;
17989                try {
17990                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
17991                    while ((line = in.readLine()) != null) {
17992                        if (line.contains("ignored: updated version")) continue;
17993                        pw.print("msg,");
17994                        pw.println(line);
17995                    }
17996                } catch (IOException ignored) {
17997                } finally {
17998                    IoUtils.closeQuietly(in);
17999                }
18000            }
18001        }
18002    }
18003
18004    private String dumpDomainString(String packageName) {
18005        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
18006                .getList();
18007        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
18008
18009        ArraySet<String> result = new ArraySet<>();
18010        if (iviList.size() > 0) {
18011            for (IntentFilterVerificationInfo ivi : iviList) {
18012                for (String host : ivi.getDomains()) {
18013                    result.add(host);
18014                }
18015            }
18016        }
18017        if (filters != null && filters.size() > 0) {
18018            for (IntentFilter filter : filters) {
18019                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
18020                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
18021                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
18022                    result.addAll(filter.getHostsList());
18023                }
18024            }
18025        }
18026
18027        StringBuilder sb = new StringBuilder(result.size() * 16);
18028        for (String domain : result) {
18029            if (sb.length() > 0) sb.append(" ");
18030            sb.append(domain);
18031        }
18032        return sb.toString();
18033    }
18034
18035    // ------- apps on sdcard specific code -------
18036    static final boolean DEBUG_SD_INSTALL = false;
18037
18038    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
18039
18040    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
18041
18042    private boolean mMediaMounted = false;
18043
18044    static String getEncryptKey() {
18045        try {
18046            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
18047                    SD_ENCRYPTION_KEYSTORE_NAME);
18048            if (sdEncKey == null) {
18049                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
18050                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
18051                if (sdEncKey == null) {
18052                    Slog.e(TAG, "Failed to create encryption keys");
18053                    return null;
18054                }
18055            }
18056            return sdEncKey;
18057        } catch (NoSuchAlgorithmException nsae) {
18058            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
18059            return null;
18060        } catch (IOException ioe) {
18061            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
18062            return null;
18063        }
18064    }
18065
18066    /*
18067     * Update media status on PackageManager.
18068     */
18069    @Override
18070    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
18071        int callingUid = Binder.getCallingUid();
18072        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
18073            throw new SecurityException("Media status can only be updated by the system");
18074        }
18075        // reader; this apparently protects mMediaMounted, but should probably
18076        // be a different lock in that case.
18077        synchronized (mPackages) {
18078            Log.i(TAG, "Updating external media status from "
18079                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
18080                    + (mediaStatus ? "mounted" : "unmounted"));
18081            if (DEBUG_SD_INSTALL)
18082                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
18083                        + ", mMediaMounted=" + mMediaMounted);
18084            if (mediaStatus == mMediaMounted) {
18085                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
18086                        : 0, -1);
18087                mHandler.sendMessage(msg);
18088                return;
18089            }
18090            mMediaMounted = mediaStatus;
18091        }
18092        // Queue up an async operation since the package installation may take a
18093        // little while.
18094        mHandler.post(new Runnable() {
18095            public void run() {
18096                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
18097            }
18098        });
18099    }
18100
18101    /**
18102     * Called by MountService when the initial ASECs to scan are available.
18103     * Should block until all the ASEC containers are finished being scanned.
18104     */
18105    public void scanAvailableAsecs() {
18106        updateExternalMediaStatusInner(true, false, false);
18107    }
18108
18109    /*
18110     * Collect information of applications on external media, map them against
18111     * existing containers and update information based on current mount status.
18112     * Please note that we always have to report status if reportStatus has been
18113     * set to true especially when unloading packages.
18114     */
18115    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
18116            boolean externalStorage) {
18117        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
18118        int[] uidArr = EmptyArray.INT;
18119
18120        final String[] list = PackageHelper.getSecureContainerList();
18121        if (ArrayUtils.isEmpty(list)) {
18122            Log.i(TAG, "No secure containers found");
18123        } else {
18124            // Process list of secure containers and categorize them
18125            // as active or stale based on their package internal state.
18126
18127            // reader
18128            synchronized (mPackages) {
18129                for (String cid : list) {
18130                    // Leave stages untouched for now; installer service owns them
18131                    if (PackageInstallerService.isStageName(cid)) continue;
18132
18133                    if (DEBUG_SD_INSTALL)
18134                        Log.i(TAG, "Processing container " + cid);
18135                    String pkgName = getAsecPackageName(cid);
18136                    if (pkgName == null) {
18137                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
18138                        continue;
18139                    }
18140                    if (DEBUG_SD_INSTALL)
18141                        Log.i(TAG, "Looking for pkg : " + pkgName);
18142
18143                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
18144                    if (ps == null) {
18145                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
18146                        continue;
18147                    }
18148
18149                    /*
18150                     * Skip packages that are not external if we're unmounting
18151                     * external storage.
18152                     */
18153                    if (externalStorage && !isMounted && !isExternal(ps)) {
18154                        continue;
18155                    }
18156
18157                    final AsecInstallArgs args = new AsecInstallArgs(cid,
18158                            getAppDexInstructionSets(ps), ps.isForwardLocked());
18159                    // The package status is changed only if the code path
18160                    // matches between settings and the container id.
18161                    if (ps.codePathString != null
18162                            && ps.codePathString.startsWith(args.getCodePath())) {
18163                        if (DEBUG_SD_INSTALL) {
18164                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
18165                                    + " at code path: " + ps.codePathString);
18166                        }
18167
18168                        // We do have a valid package installed on sdcard
18169                        processCids.put(args, ps.codePathString);
18170                        final int uid = ps.appId;
18171                        if (uid != -1) {
18172                            uidArr = ArrayUtils.appendInt(uidArr, uid);
18173                        }
18174                    } else {
18175                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
18176                                + ps.codePathString);
18177                    }
18178                }
18179            }
18180
18181            Arrays.sort(uidArr);
18182        }
18183
18184        // Process packages with valid entries.
18185        if (isMounted) {
18186            if (DEBUG_SD_INSTALL)
18187                Log.i(TAG, "Loading packages");
18188            loadMediaPackages(processCids, uidArr, externalStorage);
18189            startCleaningPackages();
18190            mInstallerService.onSecureContainersAvailable();
18191        } else {
18192            if (DEBUG_SD_INSTALL)
18193                Log.i(TAG, "Unloading packages");
18194            unloadMediaPackages(processCids, uidArr, reportStatus);
18195        }
18196    }
18197
18198    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18199            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
18200        final int size = infos.size();
18201        final String[] packageNames = new String[size];
18202        final int[] packageUids = new int[size];
18203        for (int i = 0; i < size; i++) {
18204            final ApplicationInfo info = infos.get(i);
18205            packageNames[i] = info.packageName;
18206            packageUids[i] = info.uid;
18207        }
18208        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
18209                finishedReceiver);
18210    }
18211
18212    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18213            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18214        sendResourcesChangedBroadcast(mediaStatus, replacing,
18215                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
18216    }
18217
18218    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
18219            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
18220        int size = pkgList.length;
18221        if (size > 0) {
18222            // Send broadcasts here
18223            Bundle extras = new Bundle();
18224            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
18225            if (uidArr != null) {
18226                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
18227            }
18228            if (replacing) {
18229                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
18230            }
18231            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
18232                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
18233            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
18234        }
18235    }
18236
18237   /*
18238     * Look at potentially valid container ids from processCids If package
18239     * information doesn't match the one on record or package scanning fails,
18240     * the cid is added to list of removeCids. We currently don't delete stale
18241     * containers.
18242     */
18243    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
18244            boolean externalStorage) {
18245        ArrayList<String> pkgList = new ArrayList<String>();
18246        Set<AsecInstallArgs> keys = processCids.keySet();
18247
18248        for (AsecInstallArgs args : keys) {
18249            String codePath = processCids.get(args);
18250            if (DEBUG_SD_INSTALL)
18251                Log.i(TAG, "Loading container : " + args.cid);
18252            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
18253            try {
18254                // Make sure there are no container errors first.
18255                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
18256                    Slog.e(TAG, "Failed to mount cid : " + args.cid
18257                            + " when installing from sdcard");
18258                    continue;
18259                }
18260                // Check code path here.
18261                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
18262                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
18263                            + " does not match one in settings " + codePath);
18264                    continue;
18265                }
18266                // Parse package
18267                int parseFlags = mDefParseFlags;
18268                if (args.isExternalAsec()) {
18269                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
18270                }
18271                if (args.isFwdLocked()) {
18272                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
18273                }
18274
18275                synchronized (mInstallLock) {
18276                    PackageParser.Package pkg = null;
18277                    try {
18278                        pkg = scanPackageTracedLI(new File(codePath), parseFlags, 0, 0, null);
18279                    } catch (PackageManagerException e) {
18280                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
18281                    }
18282                    // Scan the package
18283                    if (pkg != null) {
18284                        /*
18285                         * TODO why is the lock being held? doPostInstall is
18286                         * called in other places without the lock. This needs
18287                         * to be straightened out.
18288                         */
18289                        // writer
18290                        synchronized (mPackages) {
18291                            retCode = PackageManager.INSTALL_SUCCEEDED;
18292                            pkgList.add(pkg.packageName);
18293                            // Post process args
18294                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
18295                                    pkg.applicationInfo.uid);
18296                        }
18297                    } else {
18298                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
18299                    }
18300                }
18301
18302            } finally {
18303                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
18304                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
18305                }
18306            }
18307        }
18308        // writer
18309        synchronized (mPackages) {
18310            // If the platform SDK has changed since the last time we booted,
18311            // we need to re-grant app permission to catch any new ones that
18312            // appear. This is really a hack, and means that apps can in some
18313            // cases get permissions that the user didn't initially explicitly
18314            // allow... it would be nice to have some better way to handle
18315            // this situation.
18316            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
18317                    : mSettings.getInternalVersion();
18318            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
18319                    : StorageManager.UUID_PRIVATE_INTERNAL;
18320
18321            int updateFlags = UPDATE_PERMISSIONS_ALL;
18322            if (ver.sdkVersion != mSdkVersion) {
18323                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18324                        + mSdkVersion + "; regranting permissions for external");
18325                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18326            }
18327            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18328
18329            // Yay, everything is now upgraded
18330            ver.forceCurrent();
18331
18332            // can downgrade to reader
18333            // Persist settings
18334            mSettings.writeLPr();
18335        }
18336        // Send a broadcast to let everyone know we are done processing
18337        if (pkgList.size() > 0) {
18338            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
18339        }
18340    }
18341
18342   /*
18343     * Utility method to unload a list of specified containers
18344     */
18345    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
18346        // Just unmount all valid containers.
18347        for (AsecInstallArgs arg : cidArgs) {
18348            synchronized (mInstallLock) {
18349                arg.doPostDeleteLI(false);
18350           }
18351       }
18352   }
18353
18354    /*
18355     * Unload packages mounted on external media. This involves deleting package
18356     * data from internal structures, sending broadcasts about disabled packages,
18357     * gc'ing to free up references, unmounting all secure containers
18358     * corresponding to packages on external media, and posting a
18359     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
18360     * that we always have to post this message if status has been requested no
18361     * matter what.
18362     */
18363    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
18364            final boolean reportStatus) {
18365        if (DEBUG_SD_INSTALL)
18366            Log.i(TAG, "unloading media packages");
18367        ArrayList<String> pkgList = new ArrayList<String>();
18368        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
18369        final Set<AsecInstallArgs> keys = processCids.keySet();
18370        for (AsecInstallArgs args : keys) {
18371            String pkgName = args.getPackageName();
18372            if (DEBUG_SD_INSTALL)
18373                Log.i(TAG, "Trying to unload pkg : " + pkgName);
18374            // Delete package internally
18375            PackageRemovedInfo outInfo = new PackageRemovedInfo();
18376            synchronized (mInstallLock) {
18377                boolean res = deletePackageLI(pkgName, null, false, null,
18378                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null);
18379                if (res) {
18380                    pkgList.add(pkgName);
18381                } else {
18382                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
18383                    failedList.add(args);
18384                }
18385            }
18386        }
18387
18388        // reader
18389        synchronized (mPackages) {
18390            // We didn't update the settings after removing each package;
18391            // write them now for all packages.
18392            mSettings.writeLPr();
18393        }
18394
18395        // We have to absolutely send UPDATED_MEDIA_STATUS only
18396        // after confirming that all the receivers processed the ordered
18397        // broadcast when packages get disabled, force a gc to clean things up.
18398        // and unload all the containers.
18399        if (pkgList.size() > 0) {
18400            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
18401                    new IIntentReceiver.Stub() {
18402                public void performReceive(Intent intent, int resultCode, String data,
18403                        Bundle extras, boolean ordered, boolean sticky,
18404                        int sendingUser) throws RemoteException {
18405                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
18406                            reportStatus ? 1 : 0, 1, keys);
18407                    mHandler.sendMessage(msg);
18408                }
18409            });
18410        } else {
18411            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
18412                    keys);
18413            mHandler.sendMessage(msg);
18414        }
18415    }
18416
18417    private void loadPrivatePackages(final VolumeInfo vol) {
18418        mHandler.post(new Runnable() {
18419            @Override
18420            public void run() {
18421                loadPrivatePackagesInner(vol);
18422            }
18423        });
18424    }
18425
18426    private void loadPrivatePackagesInner(VolumeInfo vol) {
18427        final String volumeUuid = vol.fsUuid;
18428        if (TextUtils.isEmpty(volumeUuid)) {
18429            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
18430            return;
18431        }
18432
18433        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
18434        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
18435
18436        final VersionInfo ver;
18437        final List<PackageSetting> packages;
18438        synchronized (mPackages) {
18439            ver = mSettings.findOrCreateVersion(volumeUuid);
18440            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18441        }
18442
18443        // TODO: introduce a new concept similar to "frozen" to prevent these
18444        // apps from being launched until after data has been fully reconciled
18445        for (PackageSetting ps : packages) {
18446            synchronized (mInstallLock) {
18447                final PackageParser.Package pkg;
18448                try {
18449                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
18450                    loaded.add(pkg.applicationInfo);
18451
18452                } catch (PackageManagerException e) {
18453                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
18454                }
18455
18456                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
18457                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
18458                }
18459            }
18460        }
18461
18462        // Reconcile app data for all started/unlocked users
18463        final StorageManager sm = mContext.getSystemService(StorageManager.class);
18464        final UserManager um = mContext.getSystemService(UserManager.class);
18465        for (UserInfo user : um.getUsers()) {
18466            final int flags;
18467            if (um.isUserUnlocked(user.id)) {
18468                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18469            } else if (um.isUserRunning(user.id)) {
18470                flags = StorageManager.FLAG_STORAGE_DE;
18471            } else {
18472                continue;
18473            }
18474
18475            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
18476            reconcileAppsData(volumeUuid, user.id, flags);
18477        }
18478
18479        synchronized (mPackages) {
18480            int updateFlags = UPDATE_PERMISSIONS_ALL;
18481            if (ver.sdkVersion != mSdkVersion) {
18482                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
18483                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
18484                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
18485            }
18486            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
18487
18488            // Yay, everything is now upgraded
18489            ver.forceCurrent();
18490
18491            mSettings.writeLPr();
18492        }
18493
18494        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
18495        sendResourcesChangedBroadcast(true, false, loaded, null);
18496    }
18497
18498    private void unloadPrivatePackages(final VolumeInfo vol) {
18499        mHandler.post(new Runnable() {
18500            @Override
18501            public void run() {
18502                unloadPrivatePackagesInner(vol);
18503            }
18504        });
18505    }
18506
18507    private void unloadPrivatePackagesInner(VolumeInfo vol) {
18508        final String volumeUuid = vol.fsUuid;
18509        if (TextUtils.isEmpty(volumeUuid)) {
18510            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
18511            return;
18512        }
18513
18514        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
18515        synchronized (mInstallLock) {
18516        synchronized (mPackages) {
18517            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
18518            for (PackageSetting ps : packages) {
18519                if (ps.pkg == null) continue;
18520
18521                final ApplicationInfo info = ps.pkg.applicationInfo;
18522                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
18523                if (deletePackageLI(ps.name, null, false, null,
18524                        PackageManager.DELETE_KEEP_DATA, outInfo, false, null)) {
18525                    unloaded.add(info);
18526                } else {
18527                    Slog.w(TAG, "Failed to unload " + ps.codePath);
18528                }
18529            }
18530
18531            mSettings.writeLPr();
18532        }
18533        }
18534
18535        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
18536        sendResourcesChangedBroadcast(false, false, unloaded, null);
18537    }
18538
18539    /**
18540     * Examine all users present on given mounted volume, and destroy data
18541     * belonging to users that are no longer valid, or whose user ID has been
18542     * recycled.
18543     */
18544    private void reconcileUsers(String volumeUuid) {
18545        // TODO: also reconcile DE directories
18546        final File[] files = FileUtils
18547                .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid));
18548        for (File file : files) {
18549            if (!file.isDirectory()) continue;
18550
18551            final int userId;
18552            final UserInfo info;
18553            try {
18554                userId = Integer.parseInt(file.getName());
18555                info = sUserManager.getUserInfo(userId);
18556            } catch (NumberFormatException e) {
18557                Slog.w(TAG, "Invalid user directory " + file);
18558                continue;
18559            }
18560
18561            boolean destroyUser = false;
18562            if (info == null) {
18563                logCriticalInfo(Log.WARN, "Destroying user directory " + file
18564                        + " because no matching user was found");
18565                destroyUser = true;
18566            } else {
18567                try {
18568                    UserManagerService.enforceSerialNumber(file, info.serialNumber);
18569                } catch (IOException e) {
18570                    logCriticalInfo(Log.WARN, "Destroying user directory " + file
18571                            + " because we failed to enforce serial number: " + e);
18572                    destroyUser = true;
18573                }
18574            }
18575
18576            if (destroyUser) {
18577                synchronized (mInstallLock) {
18578                    try {
18579                        mInstaller.removeUserDataDirs(volumeUuid, userId);
18580                    } catch (InstallerException e) {
18581                        Slog.w(TAG, "Failed to clean up user dirs", e);
18582                    }
18583                }
18584            }
18585        }
18586    }
18587
18588    private void assertPackageKnown(String volumeUuid, String packageName)
18589            throws PackageManagerException {
18590        synchronized (mPackages) {
18591            final PackageSetting ps = mSettings.mPackages.get(packageName);
18592            if (ps == null) {
18593                throw new PackageManagerException("Package " + packageName + " is unknown");
18594            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18595                throw new PackageManagerException(
18596                        "Package " + packageName + " found on unknown volume " + volumeUuid
18597                                + "; expected volume " + ps.volumeUuid);
18598            }
18599        }
18600    }
18601
18602    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
18603            throws PackageManagerException {
18604        synchronized (mPackages) {
18605            final PackageSetting ps = mSettings.mPackages.get(packageName);
18606            if (ps == null) {
18607                throw new PackageManagerException("Package " + packageName + " is unknown");
18608            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
18609                throw new PackageManagerException(
18610                        "Package " + packageName + " found on unknown volume " + volumeUuid
18611                                + "; expected volume " + ps.volumeUuid);
18612            } else if (!ps.getInstalled(userId)) {
18613                throw new PackageManagerException(
18614                        "Package " + packageName + " not installed for user " + userId);
18615            }
18616        }
18617    }
18618
18619    /**
18620     * Examine all apps present on given mounted volume, and destroy apps that
18621     * aren't expected, either due to uninstallation or reinstallation on
18622     * another volume.
18623     */
18624    private void reconcileApps(String volumeUuid) {
18625        final File[] files = FileUtils
18626                .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid));
18627        for (File file : files) {
18628            final boolean isPackage = (isApkFile(file) || file.isDirectory())
18629                    && !PackageInstallerService.isStageName(file.getName());
18630            if (!isPackage) {
18631                // Ignore entries which are not packages
18632                continue;
18633            }
18634
18635            try {
18636                final PackageLite pkg = PackageParser.parsePackageLite(file,
18637                        PackageParser.PARSE_MUST_BE_APK);
18638                assertPackageKnown(volumeUuid, pkg.packageName);
18639
18640            } catch (PackageParserException | PackageManagerException e) {
18641                logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18642                synchronized (mInstallLock) {
18643                    removeCodePathLI(file);
18644                }
18645            }
18646        }
18647    }
18648
18649    /**
18650     * Reconcile all app data for the given user.
18651     * <p>
18652     * Verifies that directories exist and that ownership and labeling is
18653     * correct for all installed apps on all mounted volumes.
18654     */
18655    void reconcileAppsData(int userId, int flags) {
18656        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18657        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
18658            final String volumeUuid = vol.getFsUuid();
18659            reconcileAppsData(volumeUuid, userId, flags);
18660        }
18661    }
18662
18663    /**
18664     * Reconcile all app data on given mounted volume.
18665     * <p>
18666     * Destroys app data that isn't expected, either due to uninstallation or
18667     * reinstallation on another volume.
18668     * <p>
18669     * Verifies that directories exist and that ownership and labeling is
18670     * correct for all installed apps.
18671     */
18672    private void reconcileAppsData(String volumeUuid, int userId, int flags) {
18673        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
18674                + Integer.toHexString(flags));
18675
18676        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
18677        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
18678
18679        boolean restoreconNeeded = false;
18680
18681        // First look for stale data that doesn't belong, and check if things
18682        // have changed since we did our last restorecon
18683        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18684            if (!isUserKeyUnlocked(userId)) {
18685                throw new RuntimeException(
18686                        "Yikes, someone asked us to reconcile CE storage while " + userId
18687                                + " was still locked; this would have caused massive data loss!");
18688            }
18689
18690            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir);
18691
18692            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
18693            for (File file : files) {
18694                final String packageName = file.getName();
18695                try {
18696                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18697                } catch (PackageManagerException e) {
18698                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18699                    synchronized (mInstallLock) {
18700                        destroyAppDataLI(volumeUuid, packageName, userId,
18701                                StorageManager.FLAG_STORAGE_CE);
18702                    }
18703                }
18704            }
18705        }
18706        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18707            restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir);
18708
18709            final File[] files = FileUtils.listFilesOrEmpty(deDir);
18710            for (File file : files) {
18711                final String packageName = file.getName();
18712                try {
18713                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
18714                } catch (PackageManagerException e) {
18715                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
18716                    synchronized (mInstallLock) {
18717                        destroyAppDataLI(volumeUuid, packageName, userId,
18718                                StorageManager.FLAG_STORAGE_DE);
18719                    }
18720                }
18721            }
18722        }
18723
18724        // Ensure that data directories are ready to roll for all packages
18725        // installed for this volume and user
18726        final List<PackageSetting> packages;
18727        synchronized (mPackages) {
18728            packages = mSettings.getVolumePackagesLPr(volumeUuid);
18729        }
18730        int preparedCount = 0;
18731        for (PackageSetting ps : packages) {
18732            final String packageName = ps.name;
18733            if (ps.pkg == null) {
18734                Slog.w(TAG, "Odd, missing scanned package " + packageName);
18735                // TODO: might be due to legacy ASEC apps; we should circle back
18736                // and reconcile again once they're scanned
18737                continue;
18738            }
18739
18740            if (ps.getInstalled(userId)) {
18741                prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18742
18743                if (maybeMigrateAppData(volumeUuid, userId, ps.pkg)) {
18744                    // We may have just shuffled around app data directories, so
18745                    // prepare them one more time
18746                    prepareAppData(volumeUuid, userId, flags, ps.pkg, restoreconNeeded);
18747                }
18748
18749                preparedCount++;
18750            }
18751        }
18752
18753        if (restoreconNeeded) {
18754            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18755                SELinuxMMAC.setRestoreconDone(ceDir);
18756            }
18757            if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
18758                SELinuxMMAC.setRestoreconDone(deDir);
18759            }
18760        }
18761
18762        Slog.v(TAG, "reconcileAppsData finished " + preparedCount
18763                + " packages; restoreconNeeded was " + restoreconNeeded);
18764    }
18765
18766    /**
18767     * Prepare app data for the given app just after it was installed or
18768     * upgraded. This method carefully only touches users that it's installed
18769     * for, and it forces a restorecon to handle any seinfo changes.
18770     * <p>
18771     * Verifies that directories exist and that ownership and labeling is
18772     * correct for all installed apps. If there is an ownership mismatch, it
18773     * will try recovering system apps by wiping data; third-party app data is
18774     * left intact.
18775     * <p>
18776     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
18777     */
18778    private void prepareAppDataAfterInstall(PackageParser.Package pkg) {
18779        prepareAppDataAfterInstallInternal(pkg);
18780        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18781        for (int i = 0; i < childCount; i++) {
18782            PackageParser.Package childPackage = pkg.childPackages.get(i);
18783            prepareAppDataAfterInstallInternal(childPackage);
18784        }
18785    }
18786
18787    private void prepareAppDataAfterInstallInternal(PackageParser.Package pkg) {
18788        final PackageSetting ps;
18789        synchronized (mPackages) {
18790            ps = mSettings.mPackages.get(pkg.packageName);
18791            mSettings.writeKernelMappingLPr(ps);
18792        }
18793
18794        final UserManager um = mContext.getSystemService(UserManager.class);
18795        for (UserInfo user : um.getUsers()) {
18796            final int flags;
18797            if (um.isUserUnlocked(user.id)) {
18798                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
18799            } else if (um.isUserRunning(user.id)) {
18800                flags = StorageManager.FLAG_STORAGE_DE;
18801            } else {
18802                continue;
18803            }
18804
18805            if (ps.getInstalled(user.id)) {
18806                // Whenever an app changes, force a restorecon of its data
18807                // TODO: when user data is locked, mark that we're still dirty
18808                prepareAppData(pkg.volumeUuid, user.id, flags, pkg, true);
18809            }
18810        }
18811    }
18812
18813    /**
18814     * Prepare app data for the given app.
18815     * <p>
18816     * Verifies that directories exist and that ownership and labeling is
18817     * correct for all installed apps. If there is an ownership mismatch, this
18818     * will try recovering system apps by wiping data; third-party app data is
18819     * left intact.
18820     */
18821    private void prepareAppData(String volumeUuid, int userId, int flags,
18822            PackageParser.Package pkg, boolean restoreconNeeded) {
18823        if (DEBUG_APP_DATA) {
18824            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
18825                    + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : ""));
18826        }
18827
18828        final String packageName = pkg.packageName;
18829        final ApplicationInfo app = pkg.applicationInfo;
18830        final int appId = UserHandle.getAppId(app.uid);
18831
18832        Preconditions.checkNotNull(app.seinfo);
18833
18834        synchronized (mInstallLock) {
18835            try {
18836                mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18837                        appId, app.seinfo, app.targetSdkVersion);
18838            } catch (InstallerException e) {
18839                if (app.isSystemApp()) {
18840                    logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
18841                            + ", but trying to recover: " + e);
18842                    destroyAppDataLI(volumeUuid, packageName, userId, flags);
18843                    try {
18844                        mInstaller.createAppData(volumeUuid, packageName, userId, flags,
18845                                appId, app.seinfo, app.targetSdkVersion);
18846                        logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
18847                    } catch (InstallerException e2) {
18848                        logCriticalInfo(Log.DEBUG, "Recovery failed!");
18849                    }
18850                } else {
18851                    Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
18852                }
18853            }
18854
18855            if (restoreconNeeded) {
18856                restoreconAppDataLI(volumeUuid, packageName, userId, flags, appId, app.seinfo);
18857            }
18858
18859            if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
18860                // Create a native library symlink only if we have native libraries
18861                // and if the native libraries are 32 bit libraries. We do not provide
18862                // this symlink for 64 bit libraries.
18863                if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
18864                    final String nativeLibPath = app.nativeLibraryDir;
18865                    try {
18866                        mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
18867                                nativeLibPath, userId);
18868                    } catch (InstallerException e) {
18869                        Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
18870                    }
18871                }
18872            }
18873        }
18874    }
18875
18876    /**
18877     * For system apps on non-FBE devices, this method migrates any existing
18878     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
18879     * requested by the app.
18880     */
18881    private boolean maybeMigrateAppData(String volumeUuid, int userId, PackageParser.Package pkg) {
18882        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
18883                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
18884            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
18885                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
18886            synchronized (mInstallLock) {
18887                try {
18888                    mInstaller.migrateAppData(volumeUuid, pkg.packageName, userId, storageTarget);
18889                } catch (InstallerException e) {
18890                    logCriticalInfo(Log.WARN,
18891                            "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
18892                }
18893            }
18894            return true;
18895        } else {
18896            return false;
18897        }
18898    }
18899
18900    private void unfreezePackage(String packageName) {
18901        synchronized (mPackages) {
18902            final PackageSetting ps = mSettings.mPackages.get(packageName);
18903            if (ps != null) {
18904                ps.frozen = false;
18905            }
18906        }
18907    }
18908
18909    @Override
18910    public int movePackage(final String packageName, final String volumeUuid) {
18911        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
18912
18913        final int moveId = mNextMoveId.getAndIncrement();
18914        mHandler.post(new Runnable() {
18915            @Override
18916            public void run() {
18917                try {
18918                    movePackageInternal(packageName, volumeUuid, moveId);
18919                } catch (PackageManagerException e) {
18920                    Slog.w(TAG, "Failed to move " + packageName, e);
18921                    mMoveCallbacks.notifyStatusChanged(moveId,
18922                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
18923                }
18924            }
18925        });
18926        return moveId;
18927    }
18928
18929    private void movePackageInternal(final String packageName, final String volumeUuid,
18930            final int moveId) throws PackageManagerException {
18931        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
18932        final StorageManager storage = mContext.getSystemService(StorageManager.class);
18933        final PackageManager pm = mContext.getPackageManager();
18934
18935        final boolean currentAsec;
18936        final String currentVolumeUuid;
18937        final File codeFile;
18938        final String installerPackageName;
18939        final String packageAbiOverride;
18940        final int appId;
18941        final String seinfo;
18942        final String label;
18943        final int targetSdkVersion;
18944
18945        // reader
18946        synchronized (mPackages) {
18947            final PackageParser.Package pkg = mPackages.get(packageName);
18948            final PackageSetting ps = mSettings.mPackages.get(packageName);
18949            if (pkg == null || ps == null) {
18950                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
18951            }
18952
18953            if (pkg.applicationInfo.isSystemApp()) {
18954                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
18955                        "Cannot move system application");
18956            }
18957
18958            if (pkg.applicationInfo.isExternalAsec()) {
18959                currentAsec = true;
18960                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
18961            } else if (pkg.applicationInfo.isForwardLocked()) {
18962                currentAsec = true;
18963                currentVolumeUuid = "forward_locked";
18964            } else {
18965                currentAsec = false;
18966                currentVolumeUuid = ps.volumeUuid;
18967
18968                final File probe = new File(pkg.codePath);
18969                final File probeOat = new File(probe, "oat");
18970                if (!probe.isDirectory() || !probeOat.isDirectory()) {
18971                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18972                            "Move only supported for modern cluster style installs");
18973                }
18974            }
18975
18976            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
18977                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
18978                        "Package already moved to " + volumeUuid);
18979            }
18980            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
18981                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
18982                        "Device admin cannot be moved");
18983            }
18984
18985            if (ps.frozen) {
18986                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
18987                        "Failed to move already frozen package");
18988            }
18989            ps.frozen = true;
18990
18991            codeFile = new File(pkg.codePath);
18992            installerPackageName = ps.installerPackageName;
18993            packageAbiOverride = ps.cpuAbiOverrideString;
18994            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
18995            seinfo = pkg.applicationInfo.seinfo;
18996            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
18997            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
18998        }
18999
19000        // Now that we're guarded by frozen state, kill app during move
19001        final long token = Binder.clearCallingIdentity();
19002        try {
19003            killApplication(packageName, appId, "move pkg");
19004        } finally {
19005            Binder.restoreCallingIdentity(token);
19006        }
19007
19008        final Bundle extras = new Bundle();
19009        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
19010        extras.putString(Intent.EXTRA_TITLE, label);
19011        mMoveCallbacks.notifyCreated(moveId, extras);
19012
19013        int installFlags;
19014        final boolean moveCompleteApp;
19015        final File measurePath;
19016
19017        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
19018            installFlags = INSTALL_INTERNAL;
19019            moveCompleteApp = !currentAsec;
19020            measurePath = Environment.getDataAppDirectory(volumeUuid);
19021        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
19022            installFlags = INSTALL_EXTERNAL;
19023            moveCompleteApp = false;
19024            measurePath = storage.getPrimaryPhysicalVolume().getPath();
19025        } else {
19026            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
19027            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
19028                    || !volume.isMountedWritable()) {
19029                unfreezePackage(packageName);
19030                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19031                        "Move location not mounted private volume");
19032            }
19033
19034            Preconditions.checkState(!currentAsec);
19035
19036            installFlags = INSTALL_INTERNAL;
19037            moveCompleteApp = true;
19038            measurePath = Environment.getDataAppDirectory(volumeUuid);
19039        }
19040
19041        final PackageStats stats = new PackageStats(null, -1);
19042        synchronized (mInstaller) {
19043            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
19044                unfreezePackage(packageName);
19045                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19046                        "Failed to measure package size");
19047            }
19048        }
19049
19050        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
19051                + stats.dataSize);
19052
19053        final long startFreeBytes = measurePath.getFreeSpace();
19054        final long sizeBytes;
19055        if (moveCompleteApp) {
19056            sizeBytes = stats.codeSize + stats.dataSize;
19057        } else {
19058            sizeBytes = stats.codeSize;
19059        }
19060
19061        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
19062            unfreezePackage(packageName);
19063            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
19064                    "Not enough free space to move");
19065        }
19066
19067        mMoveCallbacks.notifyStatusChanged(moveId, 10);
19068
19069        final CountDownLatch installedLatch = new CountDownLatch(1);
19070        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
19071            @Override
19072            public void onUserActionRequired(Intent intent) throws RemoteException {
19073                throw new IllegalStateException();
19074            }
19075
19076            @Override
19077            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
19078                    Bundle extras) throws RemoteException {
19079                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
19080                        + PackageManager.installStatusToString(returnCode, msg));
19081
19082                installedLatch.countDown();
19083
19084                // Regardless of success or failure of the move operation,
19085                // always unfreeze the package
19086                unfreezePackage(packageName);
19087
19088                final int status = PackageManager.installStatusToPublicStatus(returnCode);
19089                switch (status) {
19090                    case PackageInstaller.STATUS_SUCCESS:
19091                        mMoveCallbacks.notifyStatusChanged(moveId,
19092                                PackageManager.MOVE_SUCCEEDED);
19093                        break;
19094                    case PackageInstaller.STATUS_FAILURE_STORAGE:
19095                        mMoveCallbacks.notifyStatusChanged(moveId,
19096                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
19097                        break;
19098                    default:
19099                        mMoveCallbacks.notifyStatusChanged(moveId,
19100                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
19101                        break;
19102                }
19103            }
19104        };
19105
19106        final MoveInfo move;
19107        if (moveCompleteApp) {
19108            // Kick off a thread to report progress estimates
19109            new Thread() {
19110                @Override
19111                public void run() {
19112                    while (true) {
19113                        try {
19114                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
19115                                break;
19116                            }
19117                        } catch (InterruptedException ignored) {
19118                        }
19119
19120                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
19121                        final int progress = 10 + (int) MathUtils.constrain(
19122                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
19123                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
19124                    }
19125                }
19126            }.start();
19127
19128            final String dataAppName = codeFile.getName();
19129            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
19130                    dataAppName, appId, seinfo, targetSdkVersion);
19131        } else {
19132            move = null;
19133        }
19134
19135        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
19136
19137        final Message msg = mHandler.obtainMessage(INIT_COPY);
19138        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
19139        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
19140                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
19141                packageAbiOverride, null);
19142        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
19143        msg.obj = params;
19144
19145        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
19146                System.identityHashCode(msg.obj));
19147        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
19148                System.identityHashCode(msg.obj));
19149
19150        mHandler.sendMessage(msg);
19151    }
19152
19153    @Override
19154    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
19155        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
19156
19157        final int realMoveId = mNextMoveId.getAndIncrement();
19158        final Bundle extras = new Bundle();
19159        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
19160        mMoveCallbacks.notifyCreated(realMoveId, extras);
19161
19162        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
19163            @Override
19164            public void onCreated(int moveId, Bundle extras) {
19165                // Ignored
19166            }
19167
19168            @Override
19169            public void onStatusChanged(int moveId, int status, long estMillis) {
19170                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
19171            }
19172        };
19173
19174        final StorageManager storage = mContext.getSystemService(StorageManager.class);
19175        storage.setPrimaryStorageUuid(volumeUuid, callback);
19176        return realMoveId;
19177    }
19178
19179    @Override
19180    public int getMoveStatus(int moveId) {
19181        mContext.enforceCallingOrSelfPermission(
19182                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19183        return mMoveCallbacks.mLastStatus.get(moveId);
19184    }
19185
19186    @Override
19187    public void registerMoveCallback(IPackageMoveObserver callback) {
19188        mContext.enforceCallingOrSelfPermission(
19189                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19190        mMoveCallbacks.register(callback);
19191    }
19192
19193    @Override
19194    public void unregisterMoveCallback(IPackageMoveObserver callback) {
19195        mContext.enforceCallingOrSelfPermission(
19196                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
19197        mMoveCallbacks.unregister(callback);
19198    }
19199
19200    @Override
19201    public boolean setInstallLocation(int loc) {
19202        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
19203                null);
19204        if (getInstallLocation() == loc) {
19205            return true;
19206        }
19207        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
19208                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
19209            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
19210                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
19211            return true;
19212        }
19213        return false;
19214   }
19215
19216    @Override
19217    public int getInstallLocation() {
19218        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
19219                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
19220                PackageHelper.APP_INSTALL_AUTO);
19221    }
19222
19223    /** Called by UserManagerService */
19224    void cleanUpUser(UserManagerService userManager, int userHandle) {
19225        synchronized (mPackages) {
19226            mDirtyUsers.remove(userHandle);
19227            mUserNeedsBadging.delete(userHandle);
19228            mSettings.removeUserLPw(userHandle);
19229            mPendingBroadcasts.remove(userHandle);
19230            mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle);
19231        }
19232        synchronized (mInstallLock) {
19233            final StorageManager storage = mContext.getSystemService(StorageManager.class);
19234            for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
19235                final String volumeUuid = vol.getFsUuid();
19236                if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid);
19237                try {
19238                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
19239                } catch (InstallerException e) {
19240                    Slog.w(TAG, "Failed to remove user data", e);
19241                }
19242            }
19243            synchronized (mPackages) {
19244                removeUnusedPackagesLILPw(userManager, userHandle);
19245            }
19246        }
19247    }
19248
19249    /**
19250     * We're removing userHandle and would like to remove any downloaded packages
19251     * that are no longer in use by any other user.
19252     * @param userHandle the user being removed
19253     */
19254    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
19255        final boolean DEBUG_CLEAN_APKS = false;
19256        int [] users = userManager.getUserIds();
19257        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
19258        while (psit.hasNext()) {
19259            PackageSetting ps = psit.next();
19260            if (ps.pkg == null) {
19261                continue;
19262            }
19263            final String packageName = ps.pkg.packageName;
19264            // Skip over if system app
19265            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
19266                continue;
19267            }
19268            if (DEBUG_CLEAN_APKS) {
19269                Slog.i(TAG, "Checking package " + packageName);
19270            }
19271            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
19272            if (keep) {
19273                if (DEBUG_CLEAN_APKS) {
19274                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
19275                }
19276            } else {
19277                for (int i = 0; i < users.length; i++) {
19278                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
19279                        keep = true;
19280                        if (DEBUG_CLEAN_APKS) {
19281                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
19282                                    + users[i]);
19283                        }
19284                        break;
19285                    }
19286                }
19287            }
19288            if (!keep) {
19289                if (DEBUG_CLEAN_APKS) {
19290                    Slog.i(TAG, "  Removing package " + packageName);
19291                }
19292                mHandler.post(new Runnable() {
19293                    public void run() {
19294                        deletePackageX(packageName, userHandle, 0);
19295                    } //end run
19296                });
19297            }
19298        }
19299    }
19300
19301    /** Called by UserManagerService */
19302    void createNewUser(int userHandle) {
19303        synchronized (mInstallLock) {
19304            try {
19305                mInstaller.createUserConfig(userHandle);
19306            } catch (InstallerException e) {
19307                Slog.w(TAG, "Failed to create user config", e);
19308            }
19309            mSettings.createNewUserLI(this, mInstaller, userHandle);
19310        }
19311        synchronized (mPackages) {
19312            applyFactoryDefaultBrowserLPw(userHandle);
19313            primeDomainVerificationsLPw(userHandle);
19314        }
19315    }
19316
19317    void newUserCreated(final int userHandle) {
19318        mDefaultPermissionPolicy.grantDefaultPermissions(userHandle);
19319        // If permission review for legacy apps is required, we represent
19320        // dagerous permissions for such apps as always granted runtime
19321        // permissions to keep per user flag state whether review is needed.
19322        // Hence, if a new user is added we have to propagate dangerous
19323        // permission grants for these legacy apps.
19324        if (Build.PERMISSIONS_REVIEW_REQUIRED) {
19325            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
19326                    | UPDATE_PERMISSIONS_REPLACE_ALL);
19327        }
19328    }
19329
19330    @Override
19331    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
19332        mContext.enforceCallingOrSelfPermission(
19333                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
19334                "Only package verification agents can read the verifier device identity");
19335
19336        synchronized (mPackages) {
19337            return mSettings.getVerifierDeviceIdentityLPw();
19338        }
19339    }
19340
19341    @Override
19342    public void setPermissionEnforced(String permission, boolean enforced) {
19343        // TODO: Now that we no longer change GID for storage, this should to away.
19344        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
19345                "setPermissionEnforced");
19346        if (READ_EXTERNAL_STORAGE.equals(permission)) {
19347            synchronized (mPackages) {
19348                if (mSettings.mReadExternalStorageEnforced == null
19349                        || mSettings.mReadExternalStorageEnforced != enforced) {
19350                    mSettings.mReadExternalStorageEnforced = enforced;
19351                    mSettings.writeLPr();
19352                }
19353            }
19354            // kill any non-foreground processes so we restart them and
19355            // grant/revoke the GID.
19356            final IActivityManager am = ActivityManagerNative.getDefault();
19357            if (am != null) {
19358                final long token = Binder.clearCallingIdentity();
19359                try {
19360                    am.killProcessesBelowForeground("setPermissionEnforcement");
19361                } catch (RemoteException e) {
19362                } finally {
19363                    Binder.restoreCallingIdentity(token);
19364                }
19365            }
19366        } else {
19367            throw new IllegalArgumentException("No selective enforcement for " + permission);
19368        }
19369    }
19370
19371    @Override
19372    @Deprecated
19373    public boolean isPermissionEnforced(String permission) {
19374        return true;
19375    }
19376
19377    @Override
19378    public boolean isStorageLow() {
19379        final long token = Binder.clearCallingIdentity();
19380        try {
19381            final DeviceStorageMonitorInternal
19382                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
19383            if (dsm != null) {
19384                return dsm.isMemoryLow();
19385            } else {
19386                return false;
19387            }
19388        } finally {
19389            Binder.restoreCallingIdentity(token);
19390        }
19391    }
19392
19393    @Override
19394    public IPackageInstaller getPackageInstaller() {
19395        return mInstallerService;
19396    }
19397
19398    private boolean userNeedsBadging(int userId) {
19399        int index = mUserNeedsBadging.indexOfKey(userId);
19400        if (index < 0) {
19401            final UserInfo userInfo;
19402            final long token = Binder.clearCallingIdentity();
19403            try {
19404                userInfo = sUserManager.getUserInfo(userId);
19405            } finally {
19406                Binder.restoreCallingIdentity(token);
19407            }
19408            final boolean b;
19409            if (userInfo != null && userInfo.isManagedProfile()) {
19410                b = true;
19411            } else {
19412                b = false;
19413            }
19414            mUserNeedsBadging.put(userId, b);
19415            return b;
19416        }
19417        return mUserNeedsBadging.valueAt(index);
19418    }
19419
19420    @Override
19421    public KeySet getKeySetByAlias(String packageName, String alias) {
19422        if (packageName == null || alias == null) {
19423            return null;
19424        }
19425        synchronized(mPackages) {
19426            final PackageParser.Package pkg = mPackages.get(packageName);
19427            if (pkg == null) {
19428                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19429                throw new IllegalArgumentException("Unknown package: " + packageName);
19430            }
19431            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19432            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
19433        }
19434    }
19435
19436    @Override
19437    public KeySet getSigningKeySet(String packageName) {
19438        if (packageName == null) {
19439            return null;
19440        }
19441        synchronized(mPackages) {
19442            final PackageParser.Package pkg = mPackages.get(packageName);
19443            if (pkg == null) {
19444                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19445                throw new IllegalArgumentException("Unknown package: " + packageName);
19446            }
19447            if (pkg.applicationInfo.uid != Binder.getCallingUid()
19448                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
19449                throw new SecurityException("May not access signing KeySet of other apps.");
19450            }
19451            KeySetManagerService ksms = mSettings.mKeySetManagerService;
19452            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
19453        }
19454    }
19455
19456    @Override
19457    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
19458        if (packageName == null || ks == null) {
19459            return false;
19460        }
19461        synchronized(mPackages) {
19462            final PackageParser.Package pkg = mPackages.get(packageName);
19463            if (pkg == null) {
19464                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19465                throw new IllegalArgumentException("Unknown package: " + packageName);
19466            }
19467            IBinder ksh = ks.getToken();
19468            if (ksh instanceof KeySetHandle) {
19469                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19470                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
19471            }
19472            return false;
19473        }
19474    }
19475
19476    @Override
19477    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
19478        if (packageName == null || ks == null) {
19479            return false;
19480        }
19481        synchronized(mPackages) {
19482            final PackageParser.Package pkg = mPackages.get(packageName);
19483            if (pkg == null) {
19484                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
19485                throw new IllegalArgumentException("Unknown package: " + packageName);
19486            }
19487            IBinder ksh = ks.getToken();
19488            if (ksh instanceof KeySetHandle) {
19489                KeySetManagerService ksms = mSettings.mKeySetManagerService;
19490                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
19491            }
19492            return false;
19493        }
19494    }
19495
19496    private void deletePackageIfUnusedLPr(final String packageName) {
19497        PackageSetting ps = mSettings.mPackages.get(packageName);
19498        if (ps == null) {
19499            return;
19500        }
19501        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
19502            // TODO Implement atomic delete if package is unused
19503            // It is currently possible that the package will be deleted even if it is installed
19504            // after this method returns.
19505            mHandler.post(new Runnable() {
19506                public void run() {
19507                    deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS);
19508                }
19509            });
19510        }
19511    }
19512
19513    /**
19514     * Check and throw if the given before/after packages would be considered a
19515     * downgrade.
19516     */
19517    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
19518            throws PackageManagerException {
19519        if (after.versionCode < before.mVersionCode) {
19520            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19521                    "Update version code " + after.versionCode + " is older than current "
19522                    + before.mVersionCode);
19523        } else if (after.versionCode == before.mVersionCode) {
19524            if (after.baseRevisionCode < before.baseRevisionCode) {
19525                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19526                        "Update base revision code " + after.baseRevisionCode
19527                        + " is older than current " + before.baseRevisionCode);
19528            }
19529
19530            if (!ArrayUtils.isEmpty(after.splitNames)) {
19531                for (int i = 0; i < after.splitNames.length; i++) {
19532                    final String splitName = after.splitNames[i];
19533                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
19534                    if (j != -1) {
19535                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
19536                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
19537                                    "Update split " + splitName + " revision code "
19538                                    + after.splitRevisionCodes[i] + " is older than current "
19539                                    + before.splitRevisionCodes[j]);
19540                        }
19541                    }
19542                }
19543            }
19544        }
19545    }
19546
19547    private static class MoveCallbacks extends Handler {
19548        private static final int MSG_CREATED = 1;
19549        private static final int MSG_STATUS_CHANGED = 2;
19550
19551        private final RemoteCallbackList<IPackageMoveObserver>
19552                mCallbacks = new RemoteCallbackList<>();
19553
19554        private final SparseIntArray mLastStatus = new SparseIntArray();
19555
19556        public MoveCallbacks(Looper looper) {
19557            super(looper);
19558        }
19559
19560        public void register(IPackageMoveObserver callback) {
19561            mCallbacks.register(callback);
19562        }
19563
19564        public void unregister(IPackageMoveObserver callback) {
19565            mCallbacks.unregister(callback);
19566        }
19567
19568        @Override
19569        public void handleMessage(Message msg) {
19570            final SomeArgs args = (SomeArgs) msg.obj;
19571            final int n = mCallbacks.beginBroadcast();
19572            for (int i = 0; i < n; i++) {
19573                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
19574                try {
19575                    invokeCallback(callback, msg.what, args);
19576                } catch (RemoteException ignored) {
19577                }
19578            }
19579            mCallbacks.finishBroadcast();
19580            args.recycle();
19581        }
19582
19583        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
19584                throws RemoteException {
19585            switch (what) {
19586                case MSG_CREATED: {
19587                    callback.onCreated(args.argi1, (Bundle) args.arg2);
19588                    break;
19589                }
19590                case MSG_STATUS_CHANGED: {
19591                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
19592                    break;
19593                }
19594            }
19595        }
19596
19597        private void notifyCreated(int moveId, Bundle extras) {
19598            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
19599
19600            final SomeArgs args = SomeArgs.obtain();
19601            args.argi1 = moveId;
19602            args.arg2 = extras;
19603            obtainMessage(MSG_CREATED, args).sendToTarget();
19604        }
19605
19606        private void notifyStatusChanged(int moveId, int status) {
19607            notifyStatusChanged(moveId, status, -1);
19608        }
19609
19610        private void notifyStatusChanged(int moveId, int status, long estMillis) {
19611            Slog.v(TAG, "Move " + moveId + " status " + status);
19612
19613            final SomeArgs args = SomeArgs.obtain();
19614            args.argi1 = moveId;
19615            args.argi2 = status;
19616            args.arg3 = estMillis;
19617            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
19618
19619            synchronized (mLastStatus) {
19620                mLastStatus.put(moveId, status);
19621            }
19622        }
19623    }
19624
19625    private final static class OnPermissionChangeListeners extends Handler {
19626        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
19627
19628        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
19629                new RemoteCallbackList<>();
19630
19631        public OnPermissionChangeListeners(Looper looper) {
19632            super(looper);
19633        }
19634
19635        @Override
19636        public void handleMessage(Message msg) {
19637            switch (msg.what) {
19638                case MSG_ON_PERMISSIONS_CHANGED: {
19639                    final int uid = msg.arg1;
19640                    handleOnPermissionsChanged(uid);
19641                } break;
19642            }
19643        }
19644
19645        public void addListenerLocked(IOnPermissionsChangeListener listener) {
19646            mPermissionListeners.register(listener);
19647
19648        }
19649
19650        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
19651            mPermissionListeners.unregister(listener);
19652        }
19653
19654        public void onPermissionsChanged(int uid) {
19655            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
19656                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
19657            }
19658        }
19659
19660        private void handleOnPermissionsChanged(int uid) {
19661            final int count = mPermissionListeners.beginBroadcast();
19662            try {
19663                for (int i = 0; i < count; i++) {
19664                    IOnPermissionsChangeListener callback = mPermissionListeners
19665                            .getBroadcastItem(i);
19666                    try {
19667                        callback.onPermissionsChanged(uid);
19668                    } catch (RemoteException e) {
19669                        Log.e(TAG, "Permission listener is dead", e);
19670                    }
19671                }
19672            } finally {
19673                mPermissionListeners.finishBroadcast();
19674            }
19675        }
19676    }
19677
19678    private class PackageManagerInternalImpl extends PackageManagerInternal {
19679        @Override
19680        public void setLocationPackagesProvider(PackagesProvider provider) {
19681            synchronized (mPackages) {
19682                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
19683            }
19684        }
19685
19686        @Override
19687        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
19688            synchronized (mPackages) {
19689                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
19690            }
19691        }
19692
19693        @Override
19694        public void setSmsAppPackagesProvider(PackagesProvider provider) {
19695            synchronized (mPackages) {
19696                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
19697            }
19698        }
19699
19700        @Override
19701        public void setDialerAppPackagesProvider(PackagesProvider provider) {
19702            synchronized (mPackages) {
19703                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
19704            }
19705        }
19706
19707        @Override
19708        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
19709            synchronized (mPackages) {
19710                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
19711            }
19712        }
19713
19714        @Override
19715        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
19716            synchronized (mPackages) {
19717                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
19718            }
19719        }
19720
19721        @Override
19722        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
19723            synchronized (mPackages) {
19724                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
19725                        packageName, userId);
19726            }
19727        }
19728
19729        @Override
19730        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
19731            synchronized (mPackages) {
19732                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
19733                        packageName, userId);
19734            }
19735        }
19736
19737        @Override
19738        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
19739            synchronized (mPackages) {
19740                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
19741                        packageName, userId);
19742            }
19743        }
19744
19745        @Override
19746        public void setKeepUninstalledPackages(final List<String> packageList) {
19747            Preconditions.checkNotNull(packageList);
19748            List<String> removedFromList = null;
19749            synchronized (mPackages) {
19750                if (mKeepUninstalledPackages != null) {
19751                    final int packagesCount = mKeepUninstalledPackages.size();
19752                    for (int i = 0; i < packagesCount; i++) {
19753                        String oldPackage = mKeepUninstalledPackages.get(i);
19754                        if (packageList != null && packageList.contains(oldPackage)) {
19755                            continue;
19756                        }
19757                        if (removedFromList == null) {
19758                            removedFromList = new ArrayList<>();
19759                        }
19760                        removedFromList.add(oldPackage);
19761                    }
19762                }
19763                mKeepUninstalledPackages = new ArrayList<>(packageList);
19764                if (removedFromList != null) {
19765                    final int removedCount = removedFromList.size();
19766                    for (int i = 0; i < removedCount; i++) {
19767                        deletePackageIfUnusedLPr(removedFromList.get(i));
19768                    }
19769                }
19770            }
19771        }
19772
19773        @Override
19774        public boolean isPermissionsReviewRequired(String packageName, int userId) {
19775            synchronized (mPackages) {
19776                // If we do not support permission review, done.
19777                if (!Build.PERMISSIONS_REVIEW_REQUIRED) {
19778                    return false;
19779                }
19780
19781                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
19782                if (packageSetting == null) {
19783                    return false;
19784                }
19785
19786                // Permission review applies only to apps not supporting the new permission model.
19787                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
19788                    return false;
19789                }
19790
19791                // Legacy apps have the permission and get user consent on launch.
19792                PermissionsState permissionsState = packageSetting.getPermissionsState();
19793                return permissionsState.isPermissionReviewRequired(userId);
19794            }
19795        }
19796
19797        @Override
19798        public ApplicationInfo getApplicationInfo(String packageName, int userId) {
19799            return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId);
19800        }
19801
19802        @Override
19803        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
19804                int userId) {
19805            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
19806        }
19807    }
19808
19809    @Override
19810    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
19811        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
19812        synchronized (mPackages) {
19813            final long identity = Binder.clearCallingIdentity();
19814            try {
19815                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
19816                        packageNames, userId);
19817            } finally {
19818                Binder.restoreCallingIdentity(identity);
19819            }
19820        }
19821    }
19822
19823    private static void enforceSystemOrPhoneCaller(String tag) {
19824        int callingUid = Binder.getCallingUid();
19825        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
19826            throw new SecurityException(
19827                    "Cannot call " + tag + " from UID " + callingUid);
19828        }
19829    }
19830
19831    boolean isHistoricalPackageUsageAvailable() {
19832        return mPackageUsage.isHistoricalPackageUsageAvailable();
19833    }
19834
19835    /**
19836     * Return a <b>copy</b> of the collection of packages known to the package manager.
19837     * @return A copy of the values of mPackages.
19838     */
19839    Collection<PackageParser.Package> getPackages() {
19840        synchronized (mPackages) {
19841            return new ArrayList<>(mPackages.values());
19842        }
19843    }
19844
19845    /**
19846     * Logs process start information (including base APK hash) to the security log.
19847     * @hide
19848     */
19849    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
19850            String apkFile, int pid) {
19851        if (!SecurityLog.isLoggingEnabled()) {
19852            return;
19853        }
19854        Bundle data = new Bundle();
19855        data.putLong("startTimestamp", System.currentTimeMillis());
19856        data.putString("processName", processName);
19857        data.putInt("uid", uid);
19858        data.putString("seinfo", seinfo);
19859        data.putString("apkFile", apkFile);
19860        data.putInt("pid", pid);
19861        Message msg = mProcessLoggingHandler.obtainMessage(
19862                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
19863        msg.setData(data);
19864        mProcessLoggingHandler.sendMessage(msg);
19865    }
19866}
19867