PackageManagerService.java revision 18211fd8f6ff4a70a4b8b16fab642783d536102b
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.DELETE_PACKAGES;
20import static android.Manifest.permission.INSTALL_PACKAGES;
21import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
23import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
24import static android.Manifest.permission.WRITE_MEDIA_STORAGE;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
30import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
31import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
32import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
33import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
38import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
39import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
40import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
41import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
43import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
44import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
45import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
48import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
49import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
50import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
51import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
52import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
53import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
55import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
56import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
57import static android.content.pm.PackageManager.INSTALL_INTERNAL;
58import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
64import static android.content.pm.PackageManager.MATCH_ALL;
65import static android.content.pm.PackageManager.MATCH_ANY_USER;
66import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
67import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
69import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
70import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
71import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
72import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
73import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
74import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
75import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
76import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
77import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
78import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
79import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
80import static android.content.pm.PackageManager.PERMISSION_DENIED;
81import static android.content.pm.PackageManager.PERMISSION_GRANTED;
82import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED;
83import static android.content.pm.PackageParser.isApkFile;
84import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
85import static android.system.OsConstants.O_CREAT;
86import static android.system.OsConstants.O_RDWR;
87import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
89import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
90import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
91import static com.android.internal.util.ArrayUtils.appendInt;
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.getDefaultCompilerFilter;
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;
102import static dalvik.system.DexFile.getNonProfileGuidedCompilerFilter;
103
104import android.Manifest;
105import android.annotation.IntDef;
106import android.annotation.NonNull;
107import android.annotation.Nullable;
108import android.app.ActivityManager;
109import android.app.AppOpsManager;
110import android.app.IActivityManager;
111import android.app.ResourcesManager;
112import android.app.admin.IDevicePolicyManager;
113import android.app.admin.SecurityLog;
114import android.app.backup.IBackupManager;
115import android.content.BroadcastReceiver;
116import android.content.ComponentName;
117import android.content.ContentResolver;
118import android.content.Context;
119import android.content.IIntentReceiver;
120import android.content.Intent;
121import android.content.IntentFilter;
122import android.content.IntentSender;
123import android.content.IntentSender.SendIntentException;
124import android.content.ServiceConnection;
125import android.content.pm.ActivityInfo;
126import android.content.pm.ApplicationInfo;
127import android.content.pm.AppsQueryHelper;
128import android.content.pm.AuxiliaryResolveInfo;
129import android.content.pm.ChangedPackages;
130import android.content.pm.FallbackCategoryProvider;
131import android.content.pm.FeatureInfo;
132import android.content.pm.IOnPermissionsChangeListener;
133import android.content.pm.IPackageDataObserver;
134import android.content.pm.IPackageDeleteObserver;
135import android.content.pm.IPackageDeleteObserver2;
136import android.content.pm.IPackageInstallObserver2;
137import android.content.pm.IPackageInstaller;
138import android.content.pm.IPackageManager;
139import android.content.pm.IPackageMoveObserver;
140import android.content.pm.IPackageStatsObserver;
141import android.content.pm.InstantAppInfo;
142import android.content.pm.InstantAppRequest;
143import android.content.pm.InstantAppResolveInfo;
144import android.content.pm.InstrumentationInfo;
145import android.content.pm.IntentFilterVerificationInfo;
146import android.content.pm.KeySet;
147import android.content.pm.PackageCleanItem;
148import android.content.pm.PackageInfo;
149import android.content.pm.PackageInfoLite;
150import android.content.pm.PackageInstaller;
151import android.content.pm.PackageManager;
152import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
153import android.content.pm.PackageManagerInternal;
154import android.content.pm.PackageParser;
155import android.content.pm.PackageParser.ActivityIntentInfo;
156import android.content.pm.PackageParser.PackageLite;
157import android.content.pm.PackageParser.PackageParserException;
158import android.content.pm.PackageStats;
159import android.content.pm.PackageUserState;
160import android.content.pm.ParceledListSlice;
161import android.content.pm.PermissionGroupInfo;
162import android.content.pm.PermissionInfo;
163import android.content.pm.ProviderInfo;
164import android.content.pm.ResolveInfo;
165import android.content.pm.ServiceInfo;
166import android.content.pm.SharedLibraryInfo;
167import android.content.pm.Signature;
168import android.content.pm.UserInfo;
169import android.content.pm.VerifierDeviceIdentity;
170import android.content.pm.VerifierInfo;
171import android.content.pm.VersionedPackage;
172import android.content.res.Resources;
173import android.database.ContentObserver;
174import android.graphics.Bitmap;
175import android.hardware.display.DisplayManager;
176import android.net.Uri;
177import android.os.Binder;
178import android.os.Build;
179import android.os.Bundle;
180import android.os.Debug;
181import android.os.Environment;
182import android.os.Environment.UserEnvironment;
183import android.os.FileUtils;
184import android.os.Handler;
185import android.os.IBinder;
186import android.os.Looper;
187import android.os.Message;
188import android.os.Parcel;
189import android.os.ParcelFileDescriptor;
190import android.os.PatternMatcher;
191import android.os.Process;
192import android.os.RemoteCallbackList;
193import android.os.RemoteException;
194import android.os.ResultReceiver;
195import android.os.SELinux;
196import android.os.ServiceManager;
197import android.os.ShellCallback;
198import android.os.SystemClock;
199import android.os.SystemProperties;
200import android.os.Trace;
201import android.os.UserHandle;
202import android.os.UserManager;
203import android.os.UserManagerInternal;
204import android.os.storage.IStorageManager;
205import android.os.storage.StorageEventListener;
206import android.os.storage.StorageManager;
207import android.os.storage.StorageManagerInternal;
208import android.os.storage.VolumeInfo;
209import android.os.storage.VolumeRecord;
210import android.provider.Settings.Global;
211import android.provider.Settings.Secure;
212import android.security.KeyStore;
213import android.security.SystemKeyStore;
214import android.service.pm.PackageServiceDumpProto;
215import android.system.ErrnoException;
216import android.system.Os;
217import android.text.TextUtils;
218import android.text.format.DateUtils;
219import android.util.ArrayMap;
220import android.util.ArraySet;
221import android.util.Base64;
222import android.util.BootTimingsTraceLog;
223import android.util.DisplayMetrics;
224import android.util.EventLog;
225import android.util.ExceptionUtils;
226import android.util.Log;
227import android.util.LogPrinter;
228import android.util.MathUtils;
229import android.util.PackageUtils;
230import android.util.Pair;
231import android.util.PrintStreamPrinter;
232import android.util.Slog;
233import android.util.SparseArray;
234import android.util.SparseBooleanArray;
235import android.util.SparseIntArray;
236import android.util.Xml;
237import android.util.jar.StrictJarFile;
238import android.util.proto.ProtoOutputStream;
239import android.view.Display;
240
241import com.android.internal.R;
242import com.android.internal.annotations.GuardedBy;
243import com.android.internal.app.IMediaContainerService;
244import com.android.internal.app.ResolverActivity;
245import com.android.internal.content.NativeLibraryHelper;
246import com.android.internal.content.PackageHelper;
247import com.android.internal.logging.MetricsLogger;
248import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
249import com.android.internal.os.IParcelFileDescriptorFactory;
250import com.android.internal.os.RoSystemProperties;
251import com.android.internal.os.SomeArgs;
252import com.android.internal.os.Zygote;
253import com.android.internal.telephony.CarrierAppUtils;
254import com.android.internal.util.ArrayUtils;
255import com.android.internal.util.ConcurrentUtils;
256import com.android.internal.util.DumpUtils;
257import com.android.internal.util.FastPrintWriter;
258import com.android.internal.util.FastXmlSerializer;
259import com.android.internal.util.IndentingPrintWriter;
260import com.android.internal.util.Preconditions;
261import com.android.internal.util.XmlUtils;
262import com.android.server.AttributeCache;
263import com.android.server.DeviceIdleController;
264import com.android.server.EventLogTags;
265import com.android.server.FgThread;
266import com.android.server.IntentResolver;
267import com.android.server.LocalServices;
268import com.android.server.LockGuard;
269import com.android.server.ServiceThread;
270import com.android.server.SystemConfig;
271import com.android.server.SystemServerInitThreadPool;
272import com.android.server.Watchdog;
273import com.android.server.net.NetworkPolicyManagerInternal;
274import com.android.server.pm.Installer.InstallerException;
275import com.android.server.pm.PermissionsState.PermissionState;
276import com.android.server.pm.Settings.DatabaseVersion;
277import com.android.server.pm.Settings.VersionInfo;
278import com.android.server.pm.dex.DexManager;
279import com.android.server.storage.DeviceStorageMonitorInternal;
280
281import dalvik.system.CloseGuard;
282import dalvik.system.DexFile;
283import dalvik.system.VMRuntime;
284
285import libcore.io.IoUtils;
286import libcore.util.EmptyArray;
287
288import org.xmlpull.v1.XmlPullParser;
289import org.xmlpull.v1.XmlPullParserException;
290import org.xmlpull.v1.XmlSerializer;
291
292import java.io.BufferedOutputStream;
293import java.io.BufferedReader;
294import java.io.ByteArrayInputStream;
295import java.io.ByteArrayOutputStream;
296import java.io.File;
297import java.io.FileDescriptor;
298import java.io.FileInputStream;
299import java.io.FileOutputStream;
300import java.io.FileReader;
301import java.io.FilenameFilter;
302import java.io.IOException;
303import java.io.PrintWriter;
304import java.lang.annotation.Retention;
305import java.lang.annotation.RetentionPolicy;
306import java.nio.charset.StandardCharsets;
307import java.security.DigestInputStream;
308import java.security.MessageDigest;
309import java.security.NoSuchAlgorithmException;
310import java.security.PublicKey;
311import java.security.SecureRandom;
312import java.security.cert.Certificate;
313import java.security.cert.CertificateEncodingException;
314import java.security.cert.CertificateException;
315import java.text.SimpleDateFormat;
316import java.util.ArrayList;
317import java.util.Arrays;
318import java.util.Collection;
319import java.util.Collections;
320import java.util.Comparator;
321import java.util.Date;
322import java.util.HashMap;
323import java.util.HashSet;
324import java.util.Iterator;
325import java.util.List;
326import java.util.Map;
327import java.util.Objects;
328import java.util.Set;
329import java.util.concurrent.CountDownLatch;
330import java.util.concurrent.Future;
331import java.util.concurrent.TimeUnit;
332import java.util.concurrent.atomic.AtomicBoolean;
333import java.util.concurrent.atomic.AtomicInteger;
334
335/**
336 * Keep track of all those APKs everywhere.
337 * <p>
338 * Internally there are two important locks:
339 * <ul>
340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
341 * and other related state. It is a fine-grained lock that should only be held
342 * momentarily, as it's one of the most contended locks in the system.
343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
344 * operations typically involve heavy lifting of application data on disk. Since
345 * {@code installd} is single-threaded, and it's operations can often be slow,
346 * this lock should never be acquired while already holding {@link #mPackages}.
347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
348 * holding {@link #mInstallLock}.
349 * </ul>
350 * Many internal methods rely on the caller to hold the appropriate locks, and
351 * this contract is expressed through method name suffixes:
352 * <ul>
353 * <li>fooLI(): the caller must hold {@link #mInstallLock}
354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
355 * being modified must be frozen
356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
358 * </ul>
359 * <p>
360 * Because this class is very central to the platform's security; please run all
361 * CTS and unit tests whenever making modifications:
362 *
363 * <pre>
364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
366 * </pre>
367 */
368public class PackageManagerService extends IPackageManager.Stub
369        implements PackageSender {
370    static final String TAG = "PackageManager";
371    static final boolean DEBUG_SETTINGS = false;
372    static final boolean DEBUG_PREFERRED = false;
373    static final boolean DEBUG_UPGRADE = false;
374    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
375    private static final boolean DEBUG_BACKUP = false;
376    private static final boolean DEBUG_INSTALL = false;
377    private static final boolean DEBUG_REMOVE = false;
378    private static final boolean DEBUG_BROADCASTS = false;
379    private static final boolean DEBUG_SHOW_INFO = false;
380    private static final boolean DEBUG_PACKAGE_INFO = false;
381    private static final boolean DEBUG_INTENT_MATCHING = false;
382    private static final boolean DEBUG_PACKAGE_SCANNING = false;
383    private static final boolean DEBUG_VERIFY = false;
384    private static final boolean DEBUG_FILTERS = false;
385    private static final boolean DEBUG_PERMISSIONS = false;
386    private static final boolean DEBUG_SHARED_LIBRARIES = false;
387
388    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
389    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
390    // user, but by default initialize to this.
391    public static final boolean DEBUG_DEXOPT = false;
392
393    private static final boolean DEBUG_ABI_SELECTION = false;
394    private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE;
395    private static final boolean DEBUG_TRIAGED_MISSING = false;
396    private static final boolean DEBUG_APP_DATA = false;
397
398    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
399    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
400
401    private static final boolean HIDE_EPHEMERAL_APIS = false;
402
403    private static final boolean ENABLE_FREE_CACHE_V2 =
404            SystemProperties.getBoolean("fw.free_cache_v2", true);
405
406    private static final int RADIO_UID = Process.PHONE_UID;
407    private static final int LOG_UID = Process.LOG_UID;
408    private static final int NFC_UID = Process.NFC_UID;
409    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
410    private static final int SHELL_UID = Process.SHELL_UID;
411
412    // Cap the size of permission trees that 3rd party apps can define
413    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
414
415    // Suffix used during package installation when copying/moving
416    // package apks to install directory.
417    private static final String INSTALL_PACKAGE_SUFFIX = "-";
418
419    static final int SCAN_NO_DEX = 1<<1;
420    static final int SCAN_FORCE_DEX = 1<<2;
421    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
422    static final int SCAN_NEW_INSTALL = 1<<4;
423    static final int SCAN_UPDATE_TIME = 1<<5;
424    static final int SCAN_BOOTING = 1<<6;
425    static final int SCAN_TRUSTED_OVERLAY = 1<<7;
426    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8;
427    static final int SCAN_REPLACING = 1<<9;
428    static final int SCAN_REQUIRE_KNOWN = 1<<10;
429    static final int SCAN_MOVE = 1<<11;
430    static final int SCAN_INITIAL = 1<<12;
431    static final int SCAN_CHECK_ONLY = 1<<13;
432    static final int SCAN_DONT_KILL_APP = 1<<14;
433    static final int SCAN_IGNORE_FROZEN = 1<<15;
434    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16;
435    static final int SCAN_AS_INSTANT_APP = 1<<17;
436    static final int SCAN_AS_FULL_APP = 1<<18;
437    /** Should not be with the scan flags */
438    static final int FLAGS_REMOVE_CHATTY = 1<<31;
439
440    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
441
442    private static final int[] EMPTY_INT_ARRAY = new int[0];
443
444    private static final int TYPE_UNKNOWN = 0;
445    private static final int TYPE_ACTIVITY = 1;
446    private static final int TYPE_RECEIVER = 2;
447    private static final int TYPE_SERVICE = 3;
448    private static final int TYPE_PROVIDER = 4;
449    @IntDef(prefix = { "TYPE_" }, value = {
450            TYPE_UNKNOWN,
451            TYPE_ACTIVITY,
452            TYPE_RECEIVER,
453            TYPE_SERVICE,
454            TYPE_PROVIDER,
455    })
456    @Retention(RetentionPolicy.SOURCE)
457    public @interface ComponentType {}
458
459    /**
460     * Timeout (in milliseconds) after which the watchdog should declare that
461     * our handler thread is wedged.  The usual default for such things is one
462     * minute but we sometimes do very lengthy I/O operations on this thread,
463     * such as installing multi-gigabyte applications, so ours needs to be longer.
464     */
465    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
466
467    /**
468     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
469     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
470     * settings entry if available, otherwise we use the hardcoded default.  If it's been
471     * more than this long since the last fstrim, we force one during the boot sequence.
472     *
473     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
474     * one gets run at the next available charging+idle time.  This final mandatory
475     * no-fstrim check kicks in only of the other scheduling criteria is never met.
476     */
477    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
478
479    /**
480     * Whether verification is enabled by default.
481     */
482    private static final boolean DEFAULT_VERIFY_ENABLE = true;
483
484    /**
485     * The default maximum time to wait for the verification agent to return in
486     * milliseconds.
487     */
488    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
489
490    /**
491     * The default response for package verification timeout.
492     *
493     * This can be either PackageManager.VERIFICATION_ALLOW or
494     * PackageManager.VERIFICATION_REJECT.
495     */
496    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
497
498    static final String PLATFORM_PACKAGE_NAME = "android";
499
500    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
501
502    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
503            DEFAULT_CONTAINER_PACKAGE,
504            "com.android.defcontainer.DefaultContainerService");
505
506    private static final String KILL_APP_REASON_GIDS_CHANGED =
507            "permission grant or revoke changed gids";
508
509    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
510            "permissions revoked";
511
512    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
513
514    private static final String PACKAGE_SCHEME = "package";
515
516    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
517
518    /** Permission grant: not grant the permission. */
519    private static final int GRANT_DENIED = 1;
520
521    /** Permission grant: grant the permission as an install permission. */
522    private static final int GRANT_INSTALL = 2;
523
524    /** Permission grant: grant the permission as a runtime one. */
525    private static final int GRANT_RUNTIME = 3;
526
527    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
528    private static final int GRANT_UPGRADE = 4;
529
530    /** Canonical intent used to identify what counts as a "web browser" app */
531    private static final Intent sBrowserIntent;
532    static {
533        sBrowserIntent = new Intent();
534        sBrowserIntent.setAction(Intent.ACTION_VIEW);
535        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
536        sBrowserIntent.setData(Uri.parse("http:"));
537    }
538
539    /**
540     * The set of all protected actions [i.e. those actions for which a high priority
541     * intent filter is disallowed].
542     */
543    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
544    static {
545        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
546        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
547        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
548        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
549    }
550
551    // Compilation reasons.
552    public static final int REASON_FIRST_BOOT = 0;
553    public static final int REASON_BOOT = 1;
554    public static final int REASON_INSTALL = 2;
555    public static final int REASON_BACKGROUND_DEXOPT = 3;
556    public static final int REASON_AB_OTA = 4;
557
558    public static final int REASON_LAST = REASON_AB_OTA;
559
560    /** All dangerous permission names in the same order as the events in MetricsEvent */
561    private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList(
562            Manifest.permission.READ_CALENDAR,
563            Manifest.permission.WRITE_CALENDAR,
564            Manifest.permission.CAMERA,
565            Manifest.permission.READ_CONTACTS,
566            Manifest.permission.WRITE_CONTACTS,
567            Manifest.permission.GET_ACCOUNTS,
568            Manifest.permission.ACCESS_FINE_LOCATION,
569            Manifest.permission.ACCESS_COARSE_LOCATION,
570            Manifest.permission.RECORD_AUDIO,
571            Manifest.permission.READ_PHONE_STATE,
572            Manifest.permission.CALL_PHONE,
573            Manifest.permission.READ_CALL_LOG,
574            Manifest.permission.WRITE_CALL_LOG,
575            Manifest.permission.ADD_VOICEMAIL,
576            Manifest.permission.USE_SIP,
577            Manifest.permission.PROCESS_OUTGOING_CALLS,
578            Manifest.permission.READ_CELL_BROADCASTS,
579            Manifest.permission.BODY_SENSORS,
580            Manifest.permission.SEND_SMS,
581            Manifest.permission.RECEIVE_SMS,
582            Manifest.permission.READ_SMS,
583            Manifest.permission.RECEIVE_WAP_PUSH,
584            Manifest.permission.RECEIVE_MMS,
585            Manifest.permission.READ_EXTERNAL_STORAGE,
586            Manifest.permission.WRITE_EXTERNAL_STORAGE,
587            Manifest.permission.READ_PHONE_NUMBERS,
588            Manifest.permission.ANSWER_PHONE_CALLS);
589
590
591    /**
592     * Version number for the package parser cache. Increment this whenever the format or
593     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
594     */
595    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
596
597    /**
598     * Whether the package parser cache is enabled.
599     */
600    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
601
602    final ServiceThread mHandlerThread;
603
604    final PackageHandler mHandler;
605
606    private final ProcessLoggingHandler mProcessLoggingHandler;
607
608    /**
609     * Messages for {@link #mHandler} that need to wait for system ready before
610     * being dispatched.
611     */
612    private ArrayList<Message> mPostSystemReadyMessages;
613
614    final int mSdkVersion = Build.VERSION.SDK_INT;
615
616    final Context mContext;
617    final boolean mFactoryTest;
618    final boolean mOnlyCore;
619    final DisplayMetrics mMetrics;
620    final int mDefParseFlags;
621    final String[] mSeparateProcesses;
622    final boolean mIsUpgrade;
623    final boolean mIsPreNUpgrade;
624    final boolean mIsPreNMR1Upgrade;
625
626    // Have we told the Activity Manager to whitelist the default container service by uid yet?
627    @GuardedBy("mPackages")
628    boolean mDefaultContainerWhitelisted = false;
629
630    @GuardedBy("mPackages")
631    private boolean mDexOptDialogShown;
632
633    /** The location for ASEC container files on internal storage. */
634    final String mAsecInternalPath;
635
636    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
637    // LOCK HELD.  Can be called with mInstallLock held.
638    @GuardedBy("mInstallLock")
639    final Installer mInstaller;
640
641    /** Directory where installed third-party apps stored */
642    final File mAppInstallDir;
643
644    /**
645     * Directory to which applications installed internally have their
646     * 32 bit native libraries copied.
647     */
648    private File mAppLib32InstallDir;
649
650    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
651    // apps.
652    final File mDrmAppPrivateInstallDir;
653
654    // ----------------------------------------------------------------
655
656    // Lock for state used when installing and doing other long running
657    // operations.  Methods that must be called with this lock held have
658    // the suffix "LI".
659    final Object mInstallLock = new Object();
660
661    // ----------------------------------------------------------------
662
663    // Keys are String (package name), values are Package.  This also serves
664    // as the lock for the global state.  Methods that must be called with
665    // this lock held have the prefix "LP".
666    @GuardedBy("mPackages")
667    final ArrayMap<String, PackageParser.Package> mPackages =
668            new ArrayMap<String, PackageParser.Package>();
669
670    final ArrayMap<String, Set<String>> mKnownCodebase =
671            new ArrayMap<String, Set<String>>();
672
673    // Keys are isolated uids and values are the uid of the application
674    // that created the isolated proccess.
675    @GuardedBy("mPackages")
676    final SparseIntArray mIsolatedOwners = new SparseIntArray();
677
678    // List of APK paths to load for each user and package. This data is never
679    // persisted by the package manager. Instead, the overlay manager will
680    // ensure the data is up-to-date in runtime.
681    @GuardedBy("mPackages")
682    final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths =
683        new SparseArray<ArrayMap<String, ArrayList<String>>>();
684
685    /**
686     * Tracks new system packages [received in an OTA] that we expect to
687     * find updated user-installed versions. Keys are package name, values
688     * are package location.
689     */
690    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
691    /**
692     * Tracks high priority intent filters for protected actions. During boot, certain
693     * filter actions are protected and should never be allowed to have a high priority
694     * intent filter for them. However, there is one, and only one exception -- the
695     * setup wizard. It must be able to define a high priority intent filter for these
696     * actions to ensure there are no escapes from the wizard. We need to delay processing
697     * of these during boot as we need to look at all of the system packages in order
698     * to know which component is the setup wizard.
699     */
700    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
701    /**
702     * Whether or not processing protected filters should be deferred.
703     */
704    private boolean mDeferProtectedFilters = true;
705
706    /**
707     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
708     */
709    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
710    /**
711     * Whether or not system app permissions should be promoted from install to runtime.
712     */
713    boolean mPromoteSystemApps;
714
715    @GuardedBy("mPackages")
716    final Settings mSettings;
717
718    /**
719     * Set of package names that are currently "frozen", which means active
720     * surgery is being done on the code/data for that package. The platform
721     * will refuse to launch frozen packages to avoid race conditions.
722     *
723     * @see PackageFreezer
724     */
725    @GuardedBy("mPackages")
726    final ArraySet<String> mFrozenPackages = new ArraySet<>();
727
728    final ProtectedPackages mProtectedPackages;
729
730    boolean mFirstBoot;
731
732    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
733
734    // System configuration read by SystemConfig.
735    final int[] mGlobalGids;
736    final SparseArray<ArraySet<String>> mSystemPermissions;
737    @GuardedBy("mAvailableFeatures")
738    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
739
740    // If mac_permissions.xml was found for seinfo labeling.
741    boolean mFoundPolicyFile;
742
743    private final InstantAppRegistry mInstantAppRegistry;
744
745    @GuardedBy("mPackages")
746    int mChangedPackagesSequenceNumber;
747    /**
748     * List of changed [installed, removed or updated] packages.
749     * mapping from user id -> sequence number -> package name
750     */
751    @GuardedBy("mPackages")
752    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
753    /**
754     * The sequence number of the last change to a package.
755     * mapping from user id -> package name -> sequence number
756     */
757    @GuardedBy("mPackages")
758    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
759
760    class PackageParserCallback implements PackageParser.Callback {
761        @Override public final boolean hasFeature(String feature) {
762            return PackageManagerService.this.hasSystemFeature(feature, 0);
763        }
764
765        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
766                Collection<PackageParser.Package> allPackages, String targetPackageName) {
767            List<PackageParser.Package> overlayPackages = null;
768            for (PackageParser.Package p : allPackages) {
769                if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) {
770                    if (overlayPackages == null) {
771                        overlayPackages = new ArrayList<PackageParser.Package>();
772                    }
773                    overlayPackages.add(p);
774                }
775            }
776            if (overlayPackages != null) {
777                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
778                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
779                        return p1.mOverlayPriority - p2.mOverlayPriority;
780                    }
781                };
782                Collections.sort(overlayPackages, cmp);
783            }
784            return overlayPackages;
785        }
786
787        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
788                String targetPackageName, String targetPath) {
789            if ("android".equals(targetPackageName)) {
790                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
791                // native AssetManager.
792                return null;
793            }
794            List<PackageParser.Package> overlayPackages =
795                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
796            if (overlayPackages == null || overlayPackages.isEmpty()) {
797                return null;
798            }
799            List<String> overlayPathList = null;
800            for (PackageParser.Package overlayPackage : overlayPackages) {
801                if (targetPath == null) {
802                    if (overlayPathList == null) {
803                        overlayPathList = new ArrayList<String>();
804                    }
805                    overlayPathList.add(overlayPackage.baseCodePath);
806                    continue;
807                }
808
809                try {
810                    // Creates idmaps for system to parse correctly the Android manifest of the
811                    // target package.
812                    //
813                    // OverlayManagerService will update each of them with a correct gid from its
814                    // target package app id.
815                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
816                            UserHandle.getSharedAppGid(
817                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
818                    if (overlayPathList == null) {
819                        overlayPathList = new ArrayList<String>();
820                    }
821                    overlayPathList.add(overlayPackage.baseCodePath);
822                } catch (InstallerException e) {
823                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
824                            overlayPackage.baseCodePath);
825                }
826            }
827            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
828        }
829
830        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
831            synchronized (mPackages) {
832                return getStaticOverlayPathsLocked(
833                        mPackages.values(), targetPackageName, targetPath);
834            }
835        }
836
837        @Override public final String[] getOverlayApks(String targetPackageName) {
838            return getStaticOverlayPaths(targetPackageName, null);
839        }
840
841        @Override public final String[] getOverlayPaths(String targetPackageName,
842                String targetPath) {
843            return getStaticOverlayPaths(targetPackageName, targetPath);
844        }
845    };
846
847    class ParallelPackageParserCallback extends PackageParserCallback {
848        List<PackageParser.Package> mOverlayPackages = null;
849
850        void findStaticOverlayPackages() {
851            synchronized (mPackages) {
852                for (PackageParser.Package p : mPackages.values()) {
853                    if (p.mIsStaticOverlay) {
854                        if (mOverlayPackages == null) {
855                            mOverlayPackages = new ArrayList<PackageParser.Package>();
856                        }
857                        mOverlayPackages.add(p);
858                    }
859                }
860            }
861        }
862
863        @Override
864        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
865            // We can trust mOverlayPackages without holding mPackages because package uninstall
866            // can't happen while running parallel parsing.
867            // Moreover holding mPackages on each parsing thread causes dead-lock.
868            return mOverlayPackages == null ? null :
869                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
870        }
871    }
872
873    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
874    final ParallelPackageParserCallback mParallelPackageParserCallback =
875            new ParallelPackageParserCallback();
876
877    public static final class SharedLibraryEntry {
878        public final @Nullable String path;
879        public final @Nullable String apk;
880        public final @NonNull SharedLibraryInfo info;
881
882        SharedLibraryEntry(String _path, String _apk, String name, int version, int type,
883                String declaringPackageName, int declaringPackageVersionCode) {
884            path = _path;
885            apk = _apk;
886            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
887                    declaringPackageName, declaringPackageVersionCode), null);
888        }
889    }
890
891    // Currently known shared libraries.
892    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
893    final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
894            new ArrayMap<>();
895
896    // All available activities, for your resolving pleasure.
897    final ActivityIntentResolver mActivities =
898            new ActivityIntentResolver();
899
900    // All available receivers, for your resolving pleasure.
901    final ActivityIntentResolver mReceivers =
902            new ActivityIntentResolver();
903
904    // All available services, for your resolving pleasure.
905    final ServiceIntentResolver mServices = new ServiceIntentResolver();
906
907    // All available providers, for your resolving pleasure.
908    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
909
910    // Mapping from provider base names (first directory in content URI codePath)
911    // to the provider information.
912    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
913            new ArrayMap<String, PackageParser.Provider>();
914
915    // Mapping from instrumentation class names to info about them.
916    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
917            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
918
919    // Mapping from permission names to info about them.
920    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
921            new ArrayMap<String, PackageParser.PermissionGroup>();
922
923    // Packages whose data we have transfered into another package, thus
924    // should no longer exist.
925    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
926
927    // Broadcast actions that are only available to the system.
928    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
929
930    /** List of packages waiting for verification. */
931    final SparseArray<PackageVerificationState> mPendingVerification
932            = new SparseArray<PackageVerificationState>();
933
934    /** Set of packages associated with each app op permission. */
935    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
936
937    final PackageInstallerService mInstallerService;
938
939    private final PackageDexOptimizer mPackageDexOptimizer;
940    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
941    // is used by other apps).
942    private final DexManager mDexManager;
943
944    private AtomicInteger mNextMoveId = new AtomicInteger();
945    private final MoveCallbacks mMoveCallbacks;
946
947    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
948
949    // Cache of users who need badging.
950    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
951
952    /** Token for keys in mPendingVerification. */
953    private int mPendingVerificationToken = 0;
954
955    volatile boolean mSystemReady;
956    volatile boolean mSafeMode;
957    volatile boolean mHasSystemUidErrors;
958    private volatile boolean mEphemeralAppsDisabled;
959
960    ApplicationInfo mAndroidApplication;
961    final ActivityInfo mResolveActivity = new ActivityInfo();
962    final ResolveInfo mResolveInfo = new ResolveInfo();
963    ComponentName mResolveComponentName;
964    PackageParser.Package mPlatformPackage;
965    ComponentName mCustomResolverComponentName;
966
967    boolean mResolverReplaced = false;
968
969    private final @Nullable ComponentName mIntentFilterVerifierComponent;
970    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
971
972    private int mIntentFilterVerificationToken = 0;
973
974    /** The service connection to the ephemeral resolver */
975    final EphemeralResolverConnection mInstantAppResolverConnection;
976    /** Component used to show resolver settings for Instant Apps */
977    final ComponentName mInstantAppResolverSettingsComponent;
978
979    /** Activity used to install instant applications */
980    ActivityInfo mInstantAppInstallerActivity;
981    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
982
983    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
984            = new SparseArray<IntentFilterVerificationState>();
985
986    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
987
988    // List of packages names to keep cached, even if they are uninstalled for all users
989    private List<String> mKeepUninstalledPackages;
990
991    private UserManagerInternal mUserManagerInternal;
992
993    private DeviceIdleController.LocalService mDeviceIdleController;
994
995    private File mCacheDir;
996
997    private ArraySet<String> mPrivappPermissionsViolations;
998
999    private Future<?> mPrepareAppDataFuture;
1000
1001    private static class IFVerificationParams {
1002        PackageParser.Package pkg;
1003        boolean replacing;
1004        int userId;
1005        int verifierUid;
1006
1007        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1008                int _userId, int _verifierUid) {
1009            pkg = _pkg;
1010            replacing = _replacing;
1011            userId = _userId;
1012            replacing = _replacing;
1013            verifierUid = _verifierUid;
1014        }
1015    }
1016
1017    private interface IntentFilterVerifier<T extends IntentFilter> {
1018        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1019                                               T filter, String packageName);
1020        void startVerifications(int userId);
1021        void receiveVerificationResponse(int verificationId);
1022    }
1023
1024    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1025        private Context mContext;
1026        private ComponentName mIntentFilterVerifierComponent;
1027        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1028
1029        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1030            mContext = context;
1031            mIntentFilterVerifierComponent = verifierComponent;
1032        }
1033
1034        private String getDefaultScheme() {
1035            return IntentFilter.SCHEME_HTTPS;
1036        }
1037
1038        @Override
1039        public void startVerifications(int userId) {
1040            // Launch verifications requests
1041            int count = mCurrentIntentFilterVerifications.size();
1042            for (int n=0; n<count; n++) {
1043                int verificationId = mCurrentIntentFilterVerifications.get(n);
1044                final IntentFilterVerificationState ivs =
1045                        mIntentFilterVerificationStates.get(verificationId);
1046
1047                String packageName = ivs.getPackageName();
1048
1049                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1050                final int filterCount = filters.size();
1051                ArraySet<String> domainsSet = new ArraySet<>();
1052                for (int m=0; m<filterCount; m++) {
1053                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1054                    domainsSet.addAll(filter.getHostsList());
1055                }
1056                synchronized (mPackages) {
1057                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1058                            packageName, domainsSet) != null) {
1059                        scheduleWriteSettingsLocked();
1060                    }
1061                }
1062                sendVerificationRequest(userId, verificationId, ivs);
1063            }
1064            mCurrentIntentFilterVerifications.clear();
1065        }
1066
1067        private void sendVerificationRequest(int userId, int verificationId,
1068                IntentFilterVerificationState ivs) {
1069
1070            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1071            verificationIntent.putExtra(
1072                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1073                    verificationId);
1074            verificationIntent.putExtra(
1075                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1076                    getDefaultScheme());
1077            verificationIntent.putExtra(
1078                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1079                    ivs.getHostsString());
1080            verificationIntent.putExtra(
1081                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1082                    ivs.getPackageName());
1083            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1084            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1085
1086            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1087            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1088                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1089                    userId, false, "intent filter verifier");
1090
1091            UserHandle user = new UserHandle(userId);
1092            mContext.sendBroadcastAsUser(verificationIntent, user);
1093            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1094                    "Sending IntentFilter verification broadcast");
1095        }
1096
1097        public void receiveVerificationResponse(int verificationId) {
1098            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1099
1100            final boolean verified = ivs.isVerified();
1101
1102            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1103            final int count = filters.size();
1104            if (DEBUG_DOMAIN_VERIFICATION) {
1105                Slog.i(TAG, "Received verification response " + verificationId
1106                        + " for " + count + " filters, verified=" + verified);
1107            }
1108            for (int n=0; n<count; n++) {
1109                PackageParser.ActivityIntentInfo filter = filters.get(n);
1110                filter.setVerified(verified);
1111
1112                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1113                        + " verified with result:" + verified + " and hosts:"
1114                        + ivs.getHostsString());
1115            }
1116
1117            mIntentFilterVerificationStates.remove(verificationId);
1118
1119            final String packageName = ivs.getPackageName();
1120            IntentFilterVerificationInfo ivi = null;
1121
1122            synchronized (mPackages) {
1123                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1124            }
1125            if (ivi == null) {
1126                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1127                        + verificationId + " packageName:" + packageName);
1128                return;
1129            }
1130            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1131                    "Updating IntentFilterVerificationInfo for package " + packageName
1132                            +" verificationId:" + verificationId);
1133
1134            synchronized (mPackages) {
1135                if (verified) {
1136                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1137                } else {
1138                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1139                }
1140                scheduleWriteSettingsLocked();
1141
1142                final int userId = ivs.getUserId();
1143                if (userId != UserHandle.USER_ALL) {
1144                    final int userStatus =
1145                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1146
1147                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1148                    boolean needUpdate = false;
1149
1150                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1151                    // already been set by the User thru the Disambiguation dialog
1152                    switch (userStatus) {
1153                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1154                            if (verified) {
1155                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1156                            } else {
1157                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1158                            }
1159                            needUpdate = true;
1160                            break;
1161
1162                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1163                            if (verified) {
1164                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1165                                needUpdate = true;
1166                            }
1167                            break;
1168
1169                        default:
1170                            // Nothing to do
1171                    }
1172
1173                    if (needUpdate) {
1174                        mSettings.updateIntentFilterVerificationStatusLPw(
1175                                packageName, updatedStatus, userId);
1176                        scheduleWritePackageRestrictionsLocked(userId);
1177                    }
1178                }
1179            }
1180        }
1181
1182        @Override
1183        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1184                    ActivityIntentInfo filter, String packageName) {
1185            if (!hasValidDomains(filter)) {
1186                return false;
1187            }
1188            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1189            if (ivs == null) {
1190                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1191                        packageName);
1192            }
1193            if (DEBUG_DOMAIN_VERIFICATION) {
1194                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1195            }
1196            ivs.addFilter(filter);
1197            return true;
1198        }
1199
1200        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1201                int userId, int verificationId, String packageName) {
1202            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1203                    verifierUid, userId, packageName);
1204            ivs.setPendingState();
1205            synchronized (mPackages) {
1206                mIntentFilterVerificationStates.append(verificationId, ivs);
1207                mCurrentIntentFilterVerifications.add(verificationId);
1208            }
1209            return ivs;
1210        }
1211    }
1212
1213    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1214        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1215                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1216                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1217    }
1218
1219    // Set of pending broadcasts for aggregating enable/disable of components.
1220    static class PendingPackageBroadcasts {
1221        // for each user id, a map of <package name -> components within that package>
1222        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1223
1224        public PendingPackageBroadcasts() {
1225            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1226        }
1227
1228        public ArrayList<String> get(int userId, String packageName) {
1229            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1230            return packages.get(packageName);
1231        }
1232
1233        public void put(int userId, String packageName, ArrayList<String> components) {
1234            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1235            packages.put(packageName, components);
1236        }
1237
1238        public void remove(int userId, String packageName) {
1239            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1240            if (packages != null) {
1241                packages.remove(packageName);
1242            }
1243        }
1244
1245        public void remove(int userId) {
1246            mUidMap.remove(userId);
1247        }
1248
1249        public int userIdCount() {
1250            return mUidMap.size();
1251        }
1252
1253        public int userIdAt(int n) {
1254            return mUidMap.keyAt(n);
1255        }
1256
1257        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1258            return mUidMap.get(userId);
1259        }
1260
1261        public int size() {
1262            // total number of pending broadcast entries across all userIds
1263            int num = 0;
1264            for (int i = 0; i< mUidMap.size(); i++) {
1265                num += mUidMap.valueAt(i).size();
1266            }
1267            return num;
1268        }
1269
1270        public void clear() {
1271            mUidMap.clear();
1272        }
1273
1274        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1275            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1276            if (map == null) {
1277                map = new ArrayMap<String, ArrayList<String>>();
1278                mUidMap.put(userId, map);
1279            }
1280            return map;
1281        }
1282    }
1283    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1284
1285    // Service Connection to remote media container service to copy
1286    // package uri's from external media onto secure containers
1287    // or internal storage.
1288    private IMediaContainerService mContainerService = null;
1289
1290    static final int SEND_PENDING_BROADCAST = 1;
1291    static final int MCS_BOUND = 3;
1292    static final int END_COPY = 4;
1293    static final int INIT_COPY = 5;
1294    static final int MCS_UNBIND = 6;
1295    static final int START_CLEANING_PACKAGE = 7;
1296    static final int FIND_INSTALL_LOC = 8;
1297    static final int POST_INSTALL = 9;
1298    static final int MCS_RECONNECT = 10;
1299    static final int MCS_GIVE_UP = 11;
1300    static final int UPDATED_MEDIA_STATUS = 12;
1301    static final int WRITE_SETTINGS = 13;
1302    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1303    static final int PACKAGE_VERIFIED = 15;
1304    static final int CHECK_PENDING_VERIFICATION = 16;
1305    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1306    static final int INTENT_FILTER_VERIFIED = 18;
1307    static final int WRITE_PACKAGE_LIST = 19;
1308    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1309
1310    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1311
1312    // Delay time in millisecs
1313    static final int BROADCAST_DELAY = 10 * 1000;
1314
1315    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1316            2 * 60 * 60 * 1000L; /* two hours */
1317
1318    static UserManagerService sUserManager;
1319
1320    // Stores a list of users whose package restrictions file needs to be updated
1321    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1322
1323    final private DefaultContainerConnection mDefContainerConn =
1324            new DefaultContainerConnection();
1325    class DefaultContainerConnection implements ServiceConnection {
1326        public void onServiceConnected(ComponentName name, IBinder service) {
1327            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1328            final IMediaContainerService imcs = IMediaContainerService.Stub
1329                    .asInterface(Binder.allowBlocking(service));
1330            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1331        }
1332
1333        public void onServiceDisconnected(ComponentName name) {
1334            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1335        }
1336    }
1337
1338    // Recordkeeping of restore-after-install operations that are currently in flight
1339    // between the Package Manager and the Backup Manager
1340    static class PostInstallData {
1341        public InstallArgs args;
1342        public PackageInstalledInfo res;
1343
1344        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1345            args = _a;
1346            res = _r;
1347        }
1348    }
1349
1350    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1351    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1352
1353    // XML tags for backup/restore of various bits of state
1354    private static final String TAG_PREFERRED_BACKUP = "pa";
1355    private static final String TAG_DEFAULT_APPS = "da";
1356    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1357
1358    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1359    private static final String TAG_ALL_GRANTS = "rt-grants";
1360    private static final String TAG_GRANT = "grant";
1361    private static final String ATTR_PACKAGE_NAME = "pkg";
1362
1363    private static final String TAG_PERMISSION = "perm";
1364    private static final String ATTR_PERMISSION_NAME = "name";
1365    private static final String ATTR_IS_GRANTED = "g";
1366    private static final String ATTR_USER_SET = "set";
1367    private static final String ATTR_USER_FIXED = "fixed";
1368    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1369
1370    // System/policy permission grants are not backed up
1371    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1372            FLAG_PERMISSION_POLICY_FIXED
1373            | FLAG_PERMISSION_SYSTEM_FIXED
1374            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1375
1376    // And we back up these user-adjusted states
1377    private static final int USER_RUNTIME_GRANT_MASK =
1378            FLAG_PERMISSION_USER_SET
1379            | FLAG_PERMISSION_USER_FIXED
1380            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1381
1382    final @Nullable String mRequiredVerifierPackage;
1383    final @NonNull String mRequiredInstallerPackage;
1384    final @NonNull String mRequiredUninstallerPackage;
1385    final @Nullable String mSetupWizardPackage;
1386    final @Nullable String mStorageManagerPackage;
1387    final @NonNull String mServicesSystemSharedLibraryPackageName;
1388    final @NonNull String mSharedSystemSharedLibraryPackageName;
1389
1390    final boolean mPermissionReviewRequired;
1391
1392    private final PackageUsage mPackageUsage = new PackageUsage();
1393    private final CompilerStats mCompilerStats = new CompilerStats();
1394
1395    class PackageHandler extends Handler {
1396        private boolean mBound = false;
1397        final ArrayList<HandlerParams> mPendingInstalls =
1398            new ArrayList<HandlerParams>();
1399
1400        private boolean connectToService() {
1401            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1402                    " DefaultContainerService");
1403            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1404            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1405            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1406                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1407                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1408                mBound = true;
1409                return true;
1410            }
1411            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1412            return false;
1413        }
1414
1415        private void disconnectService() {
1416            mContainerService = null;
1417            mBound = false;
1418            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1419            mContext.unbindService(mDefContainerConn);
1420            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1421        }
1422
1423        PackageHandler(Looper looper) {
1424            super(looper);
1425        }
1426
1427        public void handleMessage(Message msg) {
1428            try {
1429                doHandleMessage(msg);
1430            } finally {
1431                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1432            }
1433        }
1434
1435        void doHandleMessage(Message msg) {
1436            switch (msg.what) {
1437                case INIT_COPY: {
1438                    HandlerParams params = (HandlerParams) msg.obj;
1439                    int idx = mPendingInstalls.size();
1440                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1441                    // If a bind was already initiated we dont really
1442                    // need to do anything. The pending install
1443                    // will be processed later on.
1444                    if (!mBound) {
1445                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1446                                System.identityHashCode(mHandler));
1447                        // If this is the only one pending we might
1448                        // have to bind to the service again.
1449                        if (!connectToService()) {
1450                            Slog.e(TAG, "Failed to bind to media container service");
1451                            params.serviceError();
1452                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1453                                    System.identityHashCode(mHandler));
1454                            if (params.traceMethod != null) {
1455                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1456                                        params.traceCookie);
1457                            }
1458                            return;
1459                        } else {
1460                            // Once we bind to the service, the first
1461                            // pending request will be processed.
1462                            mPendingInstalls.add(idx, params);
1463                        }
1464                    } else {
1465                        mPendingInstalls.add(idx, params);
1466                        // Already bound to the service. Just make
1467                        // sure we trigger off processing the first request.
1468                        if (idx == 0) {
1469                            mHandler.sendEmptyMessage(MCS_BOUND);
1470                        }
1471                    }
1472                    break;
1473                }
1474                case MCS_BOUND: {
1475                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1476                    if (msg.obj != null) {
1477                        mContainerService = (IMediaContainerService) msg.obj;
1478                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1479                                System.identityHashCode(mHandler));
1480                    }
1481                    if (mContainerService == null) {
1482                        if (!mBound) {
1483                            // Something seriously wrong since we are not bound and we are not
1484                            // waiting for connection. Bail out.
1485                            Slog.e(TAG, "Cannot bind to media container service");
1486                            for (HandlerParams params : mPendingInstalls) {
1487                                // Indicate service bind error
1488                                params.serviceError();
1489                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1490                                        System.identityHashCode(params));
1491                                if (params.traceMethod != null) {
1492                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1493                                            params.traceMethod, params.traceCookie);
1494                                }
1495                                return;
1496                            }
1497                            mPendingInstalls.clear();
1498                        } else {
1499                            Slog.w(TAG, "Waiting to connect to media container service");
1500                        }
1501                    } else if (mPendingInstalls.size() > 0) {
1502                        HandlerParams params = mPendingInstalls.get(0);
1503                        if (params != null) {
1504                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1505                                    System.identityHashCode(params));
1506                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1507                            if (params.startCopy()) {
1508                                // We are done...  look for more work or to
1509                                // go idle.
1510                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1511                                        "Checking for more work or unbind...");
1512                                // Delete pending install
1513                                if (mPendingInstalls.size() > 0) {
1514                                    mPendingInstalls.remove(0);
1515                                }
1516                                if (mPendingInstalls.size() == 0) {
1517                                    if (mBound) {
1518                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1519                                                "Posting delayed MCS_UNBIND");
1520                                        removeMessages(MCS_UNBIND);
1521                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1522                                        // Unbind after a little delay, to avoid
1523                                        // continual thrashing.
1524                                        sendMessageDelayed(ubmsg, 10000);
1525                                    }
1526                                } else {
1527                                    // There are more pending requests in queue.
1528                                    // Just post MCS_BOUND message to trigger processing
1529                                    // of next pending install.
1530                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1531                                            "Posting MCS_BOUND for next work");
1532                                    mHandler.sendEmptyMessage(MCS_BOUND);
1533                                }
1534                            }
1535                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1536                        }
1537                    } else {
1538                        // Should never happen ideally.
1539                        Slog.w(TAG, "Empty queue");
1540                    }
1541                    break;
1542                }
1543                case MCS_RECONNECT: {
1544                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1545                    if (mPendingInstalls.size() > 0) {
1546                        if (mBound) {
1547                            disconnectService();
1548                        }
1549                        if (!connectToService()) {
1550                            Slog.e(TAG, "Failed to bind to media container service");
1551                            for (HandlerParams params : mPendingInstalls) {
1552                                // Indicate service bind error
1553                                params.serviceError();
1554                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1555                                        System.identityHashCode(params));
1556                            }
1557                            mPendingInstalls.clear();
1558                        }
1559                    }
1560                    break;
1561                }
1562                case MCS_UNBIND: {
1563                    // If there is no actual work left, then time to unbind.
1564                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1565
1566                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1567                        if (mBound) {
1568                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1569
1570                            disconnectService();
1571                        }
1572                    } else if (mPendingInstalls.size() > 0) {
1573                        // There are more pending requests in queue.
1574                        // Just post MCS_BOUND message to trigger processing
1575                        // of next pending install.
1576                        mHandler.sendEmptyMessage(MCS_BOUND);
1577                    }
1578
1579                    break;
1580                }
1581                case MCS_GIVE_UP: {
1582                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1583                    HandlerParams params = mPendingInstalls.remove(0);
1584                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1585                            System.identityHashCode(params));
1586                    break;
1587                }
1588                case SEND_PENDING_BROADCAST: {
1589                    String packages[];
1590                    ArrayList<String> components[];
1591                    int size = 0;
1592                    int uids[];
1593                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1594                    synchronized (mPackages) {
1595                        if (mPendingBroadcasts == null) {
1596                            return;
1597                        }
1598                        size = mPendingBroadcasts.size();
1599                        if (size <= 0) {
1600                            // Nothing to be done. Just return
1601                            return;
1602                        }
1603                        packages = new String[size];
1604                        components = new ArrayList[size];
1605                        uids = new int[size];
1606                        int i = 0;  // filling out the above arrays
1607
1608                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1609                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1610                            Iterator<Map.Entry<String, ArrayList<String>>> it
1611                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1612                                            .entrySet().iterator();
1613                            while (it.hasNext() && i < size) {
1614                                Map.Entry<String, ArrayList<String>> ent = it.next();
1615                                packages[i] = ent.getKey();
1616                                components[i] = ent.getValue();
1617                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1618                                uids[i] = (ps != null)
1619                                        ? UserHandle.getUid(packageUserId, ps.appId)
1620                                        : -1;
1621                                i++;
1622                            }
1623                        }
1624                        size = i;
1625                        mPendingBroadcasts.clear();
1626                    }
1627                    // Send broadcasts
1628                    for (int i = 0; i < size; i++) {
1629                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1630                    }
1631                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1632                    break;
1633                }
1634                case START_CLEANING_PACKAGE: {
1635                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1636                    final String packageName = (String)msg.obj;
1637                    final int userId = msg.arg1;
1638                    final boolean andCode = msg.arg2 != 0;
1639                    synchronized (mPackages) {
1640                        if (userId == UserHandle.USER_ALL) {
1641                            int[] users = sUserManager.getUserIds();
1642                            for (int user : users) {
1643                                mSettings.addPackageToCleanLPw(
1644                                        new PackageCleanItem(user, packageName, andCode));
1645                            }
1646                        } else {
1647                            mSettings.addPackageToCleanLPw(
1648                                    new PackageCleanItem(userId, packageName, andCode));
1649                        }
1650                    }
1651                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1652                    startCleaningPackages();
1653                } break;
1654                case POST_INSTALL: {
1655                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1656
1657                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1658                    final boolean didRestore = (msg.arg2 != 0);
1659                    mRunningInstalls.delete(msg.arg1);
1660
1661                    if (data != null) {
1662                        InstallArgs args = data.args;
1663                        PackageInstalledInfo parentRes = data.res;
1664
1665                        final boolean grantPermissions = (args.installFlags
1666                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1667                        final boolean killApp = (args.installFlags
1668                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1669                        final String[] grantedPermissions = args.installGrantPermissions;
1670
1671                        // Handle the parent package
1672                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1673                                grantedPermissions, didRestore, args.installerPackageName,
1674                                args.observer);
1675
1676                        // Handle the child packages
1677                        final int childCount = (parentRes.addedChildPackages != null)
1678                                ? parentRes.addedChildPackages.size() : 0;
1679                        for (int i = 0; i < childCount; i++) {
1680                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1681                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1682                                    grantedPermissions, false, args.installerPackageName,
1683                                    args.observer);
1684                        }
1685
1686                        // Log tracing if needed
1687                        if (args.traceMethod != null) {
1688                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1689                                    args.traceCookie);
1690                        }
1691                    } else {
1692                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1693                    }
1694
1695                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1696                } break;
1697                case UPDATED_MEDIA_STATUS: {
1698                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1699                    boolean reportStatus = msg.arg1 == 1;
1700                    boolean doGc = msg.arg2 == 1;
1701                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1702                    if (doGc) {
1703                        // Force a gc to clear up stale containers.
1704                        Runtime.getRuntime().gc();
1705                    }
1706                    if (msg.obj != null) {
1707                        @SuppressWarnings("unchecked")
1708                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1709                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1710                        // Unload containers
1711                        unloadAllContainers(args);
1712                    }
1713                    if (reportStatus) {
1714                        try {
1715                            if (DEBUG_SD_INSTALL) Log.i(TAG,
1716                                    "Invoking StorageManagerService call back");
1717                            PackageHelper.getStorageManager().finishMediaUpdate();
1718                        } catch (RemoteException e) {
1719                            Log.e(TAG, "StorageManagerService not running?");
1720                        }
1721                    }
1722                } break;
1723                case WRITE_SETTINGS: {
1724                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1725                    synchronized (mPackages) {
1726                        removeMessages(WRITE_SETTINGS);
1727                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1728                        mSettings.writeLPr();
1729                        mDirtyUsers.clear();
1730                    }
1731                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1732                } break;
1733                case WRITE_PACKAGE_RESTRICTIONS: {
1734                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1735                    synchronized (mPackages) {
1736                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1737                        for (int userId : mDirtyUsers) {
1738                            mSettings.writePackageRestrictionsLPr(userId);
1739                        }
1740                        mDirtyUsers.clear();
1741                    }
1742                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1743                } break;
1744                case WRITE_PACKAGE_LIST: {
1745                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1746                    synchronized (mPackages) {
1747                        removeMessages(WRITE_PACKAGE_LIST);
1748                        mSettings.writePackageListLPr(msg.arg1);
1749                    }
1750                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1751                } break;
1752                case CHECK_PENDING_VERIFICATION: {
1753                    final int verificationId = msg.arg1;
1754                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1755
1756                    if ((state != null) && !state.timeoutExtended()) {
1757                        final InstallArgs args = state.getInstallArgs();
1758                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1759
1760                        Slog.i(TAG, "Verification timed out for " + originUri);
1761                        mPendingVerification.remove(verificationId);
1762
1763                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1764
1765                        final UserHandle user = args.getUser();
1766                        if (getDefaultVerificationResponse(user)
1767                                == PackageManager.VERIFICATION_ALLOW) {
1768                            Slog.i(TAG, "Continuing with installation of " + originUri);
1769                            state.setVerifierResponse(Binder.getCallingUid(),
1770                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1771                            broadcastPackageVerified(verificationId, originUri,
1772                                    PackageManager.VERIFICATION_ALLOW, user);
1773                            try {
1774                                ret = args.copyApk(mContainerService, true);
1775                            } catch (RemoteException e) {
1776                                Slog.e(TAG, "Could not contact the ContainerService");
1777                            }
1778                        } else {
1779                            broadcastPackageVerified(verificationId, originUri,
1780                                    PackageManager.VERIFICATION_REJECT, user);
1781                        }
1782
1783                        Trace.asyncTraceEnd(
1784                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1785
1786                        processPendingInstall(args, ret);
1787                        mHandler.sendEmptyMessage(MCS_UNBIND);
1788                    }
1789                    break;
1790                }
1791                case PACKAGE_VERIFIED: {
1792                    final int verificationId = msg.arg1;
1793
1794                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1795                    if (state == null) {
1796                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1797                        break;
1798                    }
1799
1800                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1801
1802                    state.setVerifierResponse(response.callerUid, response.code);
1803
1804                    if (state.isVerificationComplete()) {
1805                        mPendingVerification.remove(verificationId);
1806
1807                        final InstallArgs args = state.getInstallArgs();
1808                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1809
1810                        int ret;
1811                        if (state.isInstallAllowed()) {
1812                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1813                            broadcastPackageVerified(verificationId, originUri,
1814                                    response.code, state.getInstallArgs().getUser());
1815                            try {
1816                                ret = args.copyApk(mContainerService, true);
1817                            } catch (RemoteException e) {
1818                                Slog.e(TAG, "Could not contact the ContainerService");
1819                            }
1820                        } else {
1821                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1822                        }
1823
1824                        Trace.asyncTraceEnd(
1825                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1826
1827                        processPendingInstall(args, ret);
1828                        mHandler.sendEmptyMessage(MCS_UNBIND);
1829                    }
1830
1831                    break;
1832                }
1833                case START_INTENT_FILTER_VERIFICATIONS: {
1834                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1835                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1836                            params.replacing, params.pkg);
1837                    break;
1838                }
1839                case INTENT_FILTER_VERIFIED: {
1840                    final int verificationId = msg.arg1;
1841
1842                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1843                            verificationId);
1844                    if (state == null) {
1845                        Slog.w(TAG, "Invalid IntentFilter verification token "
1846                                + verificationId + " received");
1847                        break;
1848                    }
1849
1850                    final int userId = state.getUserId();
1851
1852                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1853                            "Processing IntentFilter verification with token:"
1854                            + verificationId + " and userId:" + userId);
1855
1856                    final IntentFilterVerificationResponse response =
1857                            (IntentFilterVerificationResponse) msg.obj;
1858
1859                    state.setVerifierResponse(response.callerUid, response.code);
1860
1861                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1862                            "IntentFilter verification with token:" + verificationId
1863                            + " and userId:" + userId
1864                            + " is settings verifier response with response code:"
1865                            + response.code);
1866
1867                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1868                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1869                                + response.getFailedDomainsString());
1870                    }
1871
1872                    if (state.isVerificationComplete()) {
1873                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1874                    } else {
1875                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1876                                "IntentFilter verification with token:" + verificationId
1877                                + " was not said to be complete");
1878                    }
1879
1880                    break;
1881                }
1882                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1883                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1884                            mInstantAppResolverConnection,
1885                            (InstantAppRequest) msg.obj,
1886                            mInstantAppInstallerActivity,
1887                            mHandler);
1888                }
1889            }
1890        }
1891    }
1892
1893    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1894            boolean killApp, String[] grantedPermissions,
1895            boolean launchedForRestore, String installerPackage,
1896            IPackageInstallObserver2 installObserver) {
1897        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1898            // Send the removed broadcasts
1899            if (res.removedInfo != null) {
1900                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1901            }
1902
1903            // Now that we successfully installed the package, grant runtime
1904            // permissions if requested before broadcasting the install. Also
1905            // for legacy apps in permission review mode we clear the permission
1906            // review flag which is used to emulate runtime permissions for
1907            // legacy apps.
1908            if (grantPermissions) {
1909                grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions);
1910            }
1911
1912            final boolean update = res.removedInfo != null
1913                    && res.removedInfo.removedPackage != null;
1914            final String origInstallerPackageName = res.removedInfo != null
1915                    ? res.removedInfo.installerPackageName : null;
1916
1917            // If this is the first time we have child packages for a disabled privileged
1918            // app that had no children, we grant requested runtime permissions to the new
1919            // children if the parent on the system image had them already granted.
1920            if (res.pkg.parentPackage != null) {
1921                synchronized (mPackages) {
1922                    grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg);
1923                }
1924            }
1925
1926            synchronized (mPackages) {
1927                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1928            }
1929
1930            final String packageName = res.pkg.applicationInfo.packageName;
1931
1932            // Determine the set of users who are adding this package for
1933            // the first time vs. those who are seeing an update.
1934            int[] firstUsers = EMPTY_INT_ARRAY;
1935            int[] updateUsers = EMPTY_INT_ARRAY;
1936            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1937            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1938            for (int newUser : res.newUsers) {
1939                if (ps.getInstantApp(newUser)) {
1940                    continue;
1941                }
1942                if (allNewUsers) {
1943                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1944                    continue;
1945                }
1946                boolean isNew = true;
1947                for (int origUser : res.origUsers) {
1948                    if (origUser == newUser) {
1949                        isNew = false;
1950                        break;
1951                    }
1952                }
1953                if (isNew) {
1954                    firstUsers = ArrayUtils.appendInt(firstUsers, newUser);
1955                } else {
1956                    updateUsers = ArrayUtils.appendInt(updateUsers, newUser);
1957                }
1958            }
1959
1960            // Send installed broadcasts if the package is not a static shared lib.
1961            if (res.pkg.staticSharedLibName == null) {
1962                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1963
1964                // Send added for users that see the package for the first time
1965                // sendPackageAddedForNewUsers also deals with system apps
1966                int appId = UserHandle.getAppId(res.uid);
1967                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1968                sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers);
1969
1970                // Send added for users that don't see the package for the first time
1971                Bundle extras = new Bundle(1);
1972                extras.putInt(Intent.EXTRA_UID, res.uid);
1973                if (update) {
1974                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
1975                }
1976                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1977                        extras, 0 /*flags*/,
1978                        null /*targetPackage*/, null /*finishedReceiver*/, updateUsers);
1979                if (origInstallerPackageName != null) {
1980                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1981                            extras, 0 /*flags*/,
1982                            origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1983                }
1984
1985                // Send replaced for users that don't see the package for the first time
1986                if (update) {
1987                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1988                            packageName, extras, 0 /*flags*/,
1989                            null /*targetPackage*/, null /*finishedReceiver*/,
1990                            updateUsers);
1991                    if (origInstallerPackageName != null) {
1992                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1993                                extras, 0 /*flags*/,
1994                                origInstallerPackageName, null /*finishedReceiver*/, updateUsers);
1995                    }
1996                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1997                            null /*package*/, null /*extras*/, 0 /*flags*/,
1998                            packageName /*targetPackage*/,
1999                            null /*finishedReceiver*/, updateUsers);
2000                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2001                    // First-install and we did a restore, so we're responsible for the
2002                    // first-launch broadcast.
2003                    if (DEBUG_BACKUP) {
2004                        Slog.i(TAG, "Post-restore of " + packageName
2005                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers));
2006                    }
2007                    sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers);
2008                }
2009
2010                // Send broadcast package appeared if forward locked/external for all users
2011                // treat asec-hosted packages like removable media on upgrade
2012                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2013                    if (DEBUG_INSTALL) {
2014                        Slog.i(TAG, "upgrading pkg " + res.pkg
2015                                + " is ASEC-hosted -> AVAILABLE");
2016                    }
2017                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2018                    ArrayList<String> pkgList = new ArrayList<>(1);
2019                    pkgList.add(packageName);
2020                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2021                }
2022            }
2023
2024            // Work that needs to happen on first install within each user
2025            if (firstUsers != null && firstUsers.length > 0) {
2026                synchronized (mPackages) {
2027                    for (int userId : firstUsers) {
2028                        // If this app is a browser and it's newly-installed for some
2029                        // users, clear any default-browser state in those users. The
2030                        // app's nature doesn't depend on the user, so we can just check
2031                        // its browser nature in any user and generalize.
2032                        if (packageIsBrowser(packageName, userId)) {
2033                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2034                        }
2035
2036                        // We may also need to apply pending (restored) runtime
2037                        // permission grants within these users.
2038                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2039                    }
2040                }
2041            }
2042
2043            // Log current value of "unknown sources" setting
2044            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2045                    getUnknownSourcesSettings());
2046
2047            // Remove the replaced package's older resources safely now
2048            // We delete after a gc for applications  on sdcard.
2049            if (res.removedInfo != null && res.removedInfo.args != null) {
2050                Runtime.getRuntime().gc();
2051                synchronized (mInstallLock) {
2052                    res.removedInfo.args.doPostDeleteLI(true);
2053                }
2054            } else {
2055                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2056                // and not block here.
2057                VMRuntime.getRuntime().requestConcurrentGC();
2058            }
2059
2060            // Notify DexManager that the package was installed for new users.
2061            // The updated users should already be indexed and the package code paths
2062            // should not change.
2063            // Don't notify the manager for ephemeral apps as they are not expected to
2064            // survive long enough to benefit of background optimizations.
2065            for (int userId : firstUsers) {
2066                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2067                // There's a race currently where some install events may interleave with an uninstall.
2068                // This can lead to package info being null (b/36642664).
2069                if (info != null) {
2070                    mDexManager.notifyPackageInstalled(info, userId);
2071                }
2072            }
2073        }
2074
2075        // If someone is watching installs - notify them
2076        if (installObserver != null) {
2077            try {
2078                Bundle extras = extrasForInstallResult(res);
2079                installObserver.onPackageInstalled(res.name, res.returnCode,
2080                        res.returnMsg, extras);
2081            } catch (RemoteException e) {
2082                Slog.i(TAG, "Observer no longer exists.");
2083            }
2084        }
2085    }
2086
2087    private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(
2088            PackageParser.Package pkg) {
2089        if (pkg.parentPackage == null) {
2090            return;
2091        }
2092        if (pkg.requestedPermissions == null) {
2093            return;
2094        }
2095        final PackageSetting disabledSysParentPs = mSettings
2096                .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
2097        if (disabledSysParentPs == null || disabledSysParentPs.pkg == null
2098                || !disabledSysParentPs.isPrivileged()
2099                || (disabledSysParentPs.childPackageNames != null
2100                        && !disabledSysParentPs.childPackageNames.isEmpty())) {
2101            return;
2102        }
2103        final int[] allUserIds = sUserManager.getUserIds();
2104        final int permCount = pkg.requestedPermissions.size();
2105        for (int i = 0; i < permCount; i++) {
2106            String permission = pkg.requestedPermissions.get(i);
2107            BasePermission bp = mSettings.mPermissions.get(permission);
2108            if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
2109                continue;
2110            }
2111            for (int userId : allUserIds) {
2112                if (disabledSysParentPs.getPermissionsState().hasRuntimePermission(
2113                        permission, userId)) {
2114                    grantRuntimePermission(pkg.packageName, permission, userId);
2115                }
2116            }
2117        }
2118    }
2119
2120    private StorageEventListener mStorageListener = new StorageEventListener() {
2121        @Override
2122        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2123            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2124                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2125                    final String volumeUuid = vol.getFsUuid();
2126
2127                    // Clean up any users or apps that were removed or recreated
2128                    // while this volume was missing
2129                    sUserManager.reconcileUsers(volumeUuid);
2130                    reconcileApps(volumeUuid);
2131
2132                    // Clean up any install sessions that expired or were
2133                    // cancelled while this volume was missing
2134                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2135
2136                    loadPrivatePackages(vol);
2137
2138                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2139                    unloadPrivatePackages(vol);
2140                }
2141            }
2142
2143            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
2144                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2145                    updateExternalMediaStatus(true, false);
2146                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2147                    updateExternalMediaStatus(false, false);
2148                }
2149            }
2150        }
2151
2152        @Override
2153        public void onVolumeForgotten(String fsUuid) {
2154            if (TextUtils.isEmpty(fsUuid)) {
2155                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2156                return;
2157            }
2158
2159            // Remove any apps installed on the forgotten volume
2160            synchronized (mPackages) {
2161                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2162                for (PackageSetting ps : packages) {
2163                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2164                    deletePackageVersioned(new VersionedPackage(ps.name,
2165                            PackageManager.VERSION_CODE_HIGHEST),
2166                            new LegacyPackageDeleteObserver(null).getBinder(),
2167                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2168                    // Try very hard to release any references to this package
2169                    // so we don't risk the system server being killed due to
2170                    // open FDs
2171                    AttributeCache.instance().removePackage(ps.name);
2172                }
2173
2174                mSettings.onVolumeForgotten(fsUuid);
2175                mSettings.writeLPr();
2176            }
2177        }
2178    };
2179
2180    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds,
2181            String[] grantedPermissions) {
2182        for (int userId : userIds) {
2183            grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions);
2184        }
2185    }
2186
2187    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId,
2188            String[] grantedPermissions) {
2189        SettingBase sb = (SettingBase) pkg.mExtras;
2190        if (sb == null) {
2191            return;
2192        }
2193
2194        PermissionsState permissionsState = sb.getPermissionsState();
2195
2196        final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
2197                | PackageManager.FLAG_PERMISSION_POLICY_FIXED;
2198
2199        final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
2200                >= Build.VERSION_CODES.M;
2201
2202        final boolean instantApp = isInstantApp(pkg.packageName, userId);
2203
2204        for (String permission : pkg.requestedPermissions) {
2205            final BasePermission bp;
2206            synchronized (mPackages) {
2207                bp = mSettings.mPermissions.get(permission);
2208            }
2209            if (bp != null && (bp.isRuntime() || bp.isDevelopment())
2210                    && (!instantApp || bp.isInstant())
2211                    && (supportsRuntimePermissions || !bp.isRuntimeOnly())
2212                    && (grantedPermissions == null
2213                           || ArrayUtils.contains(grantedPermissions, permission))) {
2214                final int flags = permissionsState.getPermissionFlags(permission, userId);
2215                if (supportsRuntimePermissions) {
2216                    // Installer cannot change immutable permissions.
2217                    if ((flags & immutableFlags) == 0) {
2218                        grantRuntimePermission(pkg.packageName, permission, userId);
2219                    }
2220                } else if (mPermissionReviewRequired) {
2221                    // In permission review mode we clear the review flag when we
2222                    // are asked to install the app with all permissions granted.
2223                    if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
2224                        updatePermissionFlags(permission, pkg.packageName,
2225                                PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId);
2226                    }
2227                }
2228            }
2229        }
2230    }
2231
2232    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2233        Bundle extras = null;
2234        switch (res.returnCode) {
2235            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2236                extras = new Bundle();
2237                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2238                        res.origPermission);
2239                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2240                        res.origPackage);
2241                break;
2242            }
2243            case PackageManager.INSTALL_SUCCEEDED: {
2244                extras = new Bundle();
2245                extras.putBoolean(Intent.EXTRA_REPLACING,
2246                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2247                break;
2248            }
2249        }
2250        return extras;
2251    }
2252
2253    void scheduleWriteSettingsLocked() {
2254        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2255            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2256        }
2257    }
2258
2259    void scheduleWritePackageListLocked(int userId) {
2260        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2261            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2262            msg.arg1 = userId;
2263            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2264        }
2265    }
2266
2267    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2268        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2269        scheduleWritePackageRestrictionsLocked(userId);
2270    }
2271
2272    void scheduleWritePackageRestrictionsLocked(int userId) {
2273        final int[] userIds = (userId == UserHandle.USER_ALL)
2274                ? sUserManager.getUserIds() : new int[]{userId};
2275        for (int nextUserId : userIds) {
2276            if (!sUserManager.exists(nextUserId)) return;
2277            mDirtyUsers.add(nextUserId);
2278            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2279                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2280            }
2281        }
2282    }
2283
2284    public static PackageManagerService main(Context context, Installer installer,
2285            boolean factoryTest, boolean onlyCore) {
2286        // Self-check for initial settings.
2287        PackageManagerServiceCompilerMapping.checkProperties();
2288
2289        PackageManagerService m = new PackageManagerService(context, installer,
2290                factoryTest, onlyCore);
2291        m.enableSystemUserPackages();
2292        ServiceManager.addService("package", m);
2293        return m;
2294    }
2295
2296    private void enableSystemUserPackages() {
2297        if (!UserManager.isSplitSystemUser()) {
2298            return;
2299        }
2300        // For system user, enable apps based on the following conditions:
2301        // - app is whitelisted or belong to one of these groups:
2302        //   -- system app which has no launcher icons
2303        //   -- system app which has INTERACT_ACROSS_USERS permission
2304        //   -- system IME app
2305        // - app is not in the blacklist
2306        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2307        Set<String> enableApps = new ArraySet<>();
2308        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2309                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2310                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2311        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2312        enableApps.addAll(wlApps);
2313        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2314                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2315        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2316        enableApps.removeAll(blApps);
2317        Log.i(TAG, "Applications installed for system user: " + enableApps);
2318        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2319                UserHandle.SYSTEM);
2320        final int allAppsSize = allAps.size();
2321        synchronized (mPackages) {
2322            for (int i = 0; i < allAppsSize; i++) {
2323                String pName = allAps.get(i);
2324                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2325                // Should not happen, but we shouldn't be failing if it does
2326                if (pkgSetting == null) {
2327                    continue;
2328                }
2329                boolean install = enableApps.contains(pName);
2330                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2331                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2332                            + " for system user");
2333                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2334                }
2335            }
2336            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2337        }
2338    }
2339
2340    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2341        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2342                Context.DISPLAY_SERVICE);
2343        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2344    }
2345
2346    /**
2347     * Requests that files preopted on a secondary system partition be copied to the data partition
2348     * if possible.  Note that the actual copying of the files is accomplished by init for security
2349     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2350     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2351     */
2352    private static void requestCopyPreoptedFiles() {
2353        final int WAIT_TIME_MS = 100;
2354        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2355        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2356            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2357            // We will wait for up to 100 seconds.
2358            final long timeStart = SystemClock.uptimeMillis();
2359            final long timeEnd = timeStart + 100 * 1000;
2360            long timeNow = timeStart;
2361            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2362                try {
2363                    Thread.sleep(WAIT_TIME_MS);
2364                } catch (InterruptedException e) {
2365                    // Do nothing
2366                }
2367                timeNow = SystemClock.uptimeMillis();
2368                if (timeNow > timeEnd) {
2369                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2370                    Slog.wtf(TAG, "cppreopt did not finish!");
2371                    break;
2372                }
2373            }
2374
2375            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2376        }
2377    }
2378
2379    public PackageManagerService(Context context, Installer installer,
2380            boolean factoryTest, boolean onlyCore) {
2381        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2382        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2383        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2384                SystemClock.uptimeMillis());
2385
2386        if (mSdkVersion <= 0) {
2387            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2388        }
2389
2390        mContext = context;
2391
2392        mPermissionReviewRequired = context.getResources().getBoolean(
2393                R.bool.config_permissionReviewRequired);
2394
2395        mFactoryTest = factoryTest;
2396        mOnlyCore = onlyCore;
2397        mMetrics = new DisplayMetrics();
2398        mSettings = new Settings(mPackages);
2399        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2400                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2401        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2402                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2403        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2404                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2405        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2406                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2407        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2408                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2409        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2410                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2411
2412        String separateProcesses = SystemProperties.get("debug.separate_processes");
2413        if (separateProcesses != null && separateProcesses.length() > 0) {
2414            if ("*".equals(separateProcesses)) {
2415                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2416                mSeparateProcesses = null;
2417                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2418            } else {
2419                mDefParseFlags = 0;
2420                mSeparateProcesses = separateProcesses.split(",");
2421                Slog.w(TAG, "Running with debug.separate_processes: "
2422                        + separateProcesses);
2423            }
2424        } else {
2425            mDefParseFlags = 0;
2426            mSeparateProcesses = null;
2427        }
2428
2429        mInstaller = installer;
2430        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2431                "*dexopt*");
2432        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock);
2433        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2434
2435        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2436                FgThread.get().getLooper());
2437
2438        getDefaultDisplayMetrics(context, mMetrics);
2439
2440        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2441        SystemConfig systemConfig = SystemConfig.getInstance();
2442        mGlobalGids = systemConfig.getGlobalGids();
2443        mSystemPermissions = systemConfig.getSystemPermissions();
2444        mAvailableFeatures = systemConfig.getAvailableFeatures();
2445        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2446
2447        mProtectedPackages = new ProtectedPackages(mContext);
2448
2449        synchronized (mInstallLock) {
2450        // writer
2451        synchronized (mPackages) {
2452            mHandlerThread = new ServiceThread(TAG,
2453                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2454            mHandlerThread.start();
2455            mHandler = new PackageHandler(mHandlerThread.getLooper());
2456            mProcessLoggingHandler = new ProcessLoggingHandler();
2457            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2458
2459            mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this);
2460            mInstantAppRegistry = new InstantAppRegistry(this);
2461
2462            File dataDir = Environment.getDataDirectory();
2463            mAppInstallDir = new File(dataDir, "app");
2464            mAppLib32InstallDir = new File(dataDir, "app-lib");
2465            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
2466            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
2467            sUserManager = new UserManagerService(context, this,
2468                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2469
2470            // Propagate permission configuration in to package manager.
2471            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
2472                    = systemConfig.getPermissions();
2473            for (int i=0; i<permConfig.size(); i++) {
2474                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
2475                BasePermission bp = mSettings.mPermissions.get(perm.name);
2476                if (bp == null) {
2477                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
2478                    mSettings.mPermissions.put(perm.name, bp);
2479                }
2480                if (perm.gids != null) {
2481                    bp.setGids(perm.gids, perm.perUser);
2482                }
2483            }
2484
2485            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2486            final int builtInLibCount = libConfig.size();
2487            for (int i = 0; i < builtInLibCount; i++) {
2488                String name = libConfig.keyAt(i);
2489                String path = libConfig.valueAt(i);
2490                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2491                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2492            }
2493
2494            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
2495
2496            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2497            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2498            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2499
2500            // Clean up orphaned packages for which the code path doesn't exist
2501            // and they are an update to a system app - caused by bug/32321269
2502            final int packageSettingCount = mSettings.mPackages.size();
2503            for (int i = packageSettingCount - 1; i >= 0; i--) {
2504                PackageSetting ps = mSettings.mPackages.valueAt(i);
2505                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2506                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2507                    mSettings.mPackages.removeAt(i);
2508                    mSettings.enableSystemPackageLPw(ps.name);
2509                }
2510            }
2511
2512            if (mFirstBoot) {
2513                requestCopyPreoptedFiles();
2514            }
2515
2516            String customResolverActivity = Resources.getSystem().getString(
2517                    R.string.config_customResolverActivity);
2518            if (TextUtils.isEmpty(customResolverActivity)) {
2519                customResolverActivity = null;
2520            } else {
2521                mCustomResolverComponentName = ComponentName.unflattenFromString(
2522                        customResolverActivity);
2523            }
2524
2525            long startTime = SystemClock.uptimeMillis();
2526
2527            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2528                    startTime);
2529
2530            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2531            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2532
2533            if (bootClassPath == null) {
2534                Slog.w(TAG, "No BOOTCLASSPATH found!");
2535            }
2536
2537            if (systemServerClassPath == null) {
2538                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2539            }
2540
2541            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2542
2543            final VersionInfo ver = mSettings.getInternalVersion();
2544            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2545            if (mIsUpgrade) {
2546                logCriticalInfo(Log.INFO,
2547                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2548            }
2549
2550            // when upgrading from pre-M, promote system app permissions from install to runtime
2551            mPromoteSystemApps =
2552                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2553
2554            // When upgrading from pre-N, we need to handle package extraction like first boot,
2555            // as there is no profiling data available.
2556            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2557
2558            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2559
2560            // save off the names of pre-existing system packages prior to scanning; we don't
2561            // want to automatically grant runtime permissions for new system apps
2562            if (mPromoteSystemApps) {
2563                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2564                while (pkgSettingIter.hasNext()) {
2565                    PackageSetting ps = pkgSettingIter.next();
2566                    if (isSystemApp(ps)) {
2567                        mExistingSystemPackages.add(ps.name);
2568                    }
2569                }
2570            }
2571
2572            mCacheDir = preparePackageParserCache(mIsUpgrade);
2573
2574            // Set flag to monitor and not change apk file paths when
2575            // scanning install directories.
2576            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2577
2578            if (mIsUpgrade || mFirstBoot) {
2579                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2580            }
2581
2582            // Collect vendor overlay packages. (Do this before scanning any apps.)
2583            // For security and version matching reason, only consider
2584            // overlay packages if they reside in the right directory.
2585            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags
2586                    | PackageParser.PARSE_IS_SYSTEM
2587                    | PackageParser.PARSE_IS_SYSTEM_DIR
2588                    | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
2589
2590            mParallelPackageParserCallback.findStaticOverlayPackages();
2591
2592            // Find base frameworks (resource packages without code).
2593            scanDirTracedLI(frameworkDir, mDefParseFlags
2594                    | PackageParser.PARSE_IS_SYSTEM
2595                    | PackageParser.PARSE_IS_SYSTEM_DIR
2596                    | PackageParser.PARSE_IS_PRIVILEGED,
2597                    scanFlags | SCAN_NO_DEX, 0);
2598
2599            // Collected privileged system packages.
2600            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2601            scanDirTracedLI(privilegedAppDir, mDefParseFlags
2602                    | PackageParser.PARSE_IS_SYSTEM
2603                    | PackageParser.PARSE_IS_SYSTEM_DIR
2604                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
2605
2606            // Collect ordinary system packages.
2607            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2608            scanDirTracedLI(systemAppDir, mDefParseFlags
2609                    | PackageParser.PARSE_IS_SYSTEM
2610                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2611
2612            // Collect all vendor packages.
2613            File vendorAppDir = new File("/vendor/app");
2614            try {
2615                vendorAppDir = vendorAppDir.getCanonicalFile();
2616            } catch (IOException e) {
2617                // failed to look up canonical path, continue with original one
2618            }
2619            scanDirTracedLI(vendorAppDir, mDefParseFlags
2620                    | PackageParser.PARSE_IS_SYSTEM
2621                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2622
2623            // Collect all OEM packages.
2624            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2625            scanDirTracedLI(oemAppDir, mDefParseFlags
2626                    | PackageParser.PARSE_IS_SYSTEM
2627                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
2628
2629            // Prune any system packages that no longer exist.
2630            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
2631            if (!mOnlyCore) {
2632                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2633                while (psit.hasNext()) {
2634                    PackageSetting ps = psit.next();
2635
2636                    /*
2637                     * If this is not a system app, it can't be a
2638                     * disable system app.
2639                     */
2640                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2641                        continue;
2642                    }
2643
2644                    /*
2645                     * If the package is scanned, it's not erased.
2646                     */
2647                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2648                    if (scannedPkg != null) {
2649                        /*
2650                         * If the system app is both scanned and in the
2651                         * disabled packages list, then it must have been
2652                         * added via OTA. Remove it from the currently
2653                         * scanned package so the previously user-installed
2654                         * application can be scanned.
2655                         */
2656                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2657                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
2658                                    + ps.name + "; removing system app.  Last known codePath="
2659                                    + ps.codePathString + ", installStatus=" + ps.installStatus
2660                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
2661                                    + scannedPkg.mVersionCode);
2662                            removePackageLI(scannedPkg, true);
2663                            mExpectingBetter.put(ps.name, ps.codePath);
2664                        }
2665
2666                        continue;
2667                    }
2668
2669                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2670                        psit.remove();
2671                        logCriticalInfo(Log.WARN, "System package " + ps.name
2672                                + " no longer exists; it's data will be wiped");
2673                        // Actual deletion of code and data will be handled by later
2674                        // reconciliation step
2675                    } else {
2676                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2677                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2678                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2679                        }
2680                    }
2681                }
2682            }
2683
2684            //look for any incomplete package installations
2685            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2686            for (int i = 0; i < deletePkgsList.size(); i++) {
2687                // Actual deletion of code and data will be handled by later
2688                // reconciliation step
2689                final String packageName = deletePkgsList.get(i).name;
2690                logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName);
2691                synchronized (mPackages) {
2692                    mSettings.removePackageLPw(packageName);
2693                }
2694            }
2695
2696            //delete tmp files
2697            deleteTempPackageFiles();
2698
2699            // Remove any shared userIDs that have no associated packages
2700            mSettings.pruneSharedUsersLPw();
2701
2702            if (!mOnlyCore) {
2703                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2704                        SystemClock.uptimeMillis());
2705                scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2706
2707                scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags
2708                        | PackageParser.PARSE_FORWARD_LOCK,
2709                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2710
2711                /**
2712                 * Remove disable package settings for any updated system
2713                 * apps that were removed via an OTA. If they're not a
2714                 * previously-updated app, remove them completely.
2715                 * Otherwise, just revoke their system-level permissions.
2716                 */
2717                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2718                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2719                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2720
2721                    String msg;
2722                    if (deletedPkg == null) {
2723                        msg = "Updated system package " + deletedAppName
2724                                + " no longer exists; it's data will be wiped";
2725                        // Actual deletion of code and data will be handled by later
2726                        // reconciliation step
2727                    } else {
2728                        msg = "Updated system app + " + deletedAppName
2729                                + " no longer present; removing system privileges for "
2730                                + deletedAppName;
2731
2732                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2733
2734                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2735                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2736                    }
2737                    logCriticalInfo(Log.WARN, msg);
2738                }
2739
2740                /**
2741                 * Make sure all system apps that we expected to appear on
2742                 * the userdata partition actually showed up. If they never
2743                 * appeared, crawl back and revive the system version.
2744                 */
2745                for (int i = 0; i < mExpectingBetter.size(); i++) {
2746                    final String packageName = mExpectingBetter.keyAt(i);
2747                    if (!mPackages.containsKey(packageName)) {
2748                        final File scanFile = mExpectingBetter.valueAt(i);
2749
2750                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2751                                + " but never showed up; reverting to system");
2752
2753                        int reparseFlags = mDefParseFlags;
2754                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2755                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2756                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2757                                    | PackageParser.PARSE_IS_PRIVILEGED;
2758                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2759                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2760                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2761                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2762                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2763                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2764                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2765                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2766                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2767                        } else {
2768                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2769                            continue;
2770                        }
2771
2772                        mSettings.enableSystemPackageLPw(packageName);
2773
2774                        try {
2775                            scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null);
2776                        } catch (PackageManagerException e) {
2777                            Slog.e(TAG, "Failed to parse original system package: "
2778                                    + e.getMessage());
2779                        }
2780                    }
2781                }
2782            }
2783            mExpectingBetter.clear();
2784
2785            // Resolve the storage manager.
2786            mStorageManagerPackage = getStorageManagerPackageName();
2787
2788            // Resolve protected action filters. Only the setup wizard is allowed to
2789            // have a high priority filter for these actions.
2790            mSetupWizardPackage = getSetupWizardPackageName();
2791            if (mProtectedFilters.size() > 0) {
2792                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2793                    Slog.i(TAG, "No setup wizard;"
2794                        + " All protected intents capped to priority 0");
2795                }
2796                for (ActivityIntentInfo filter : mProtectedFilters) {
2797                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2798                        if (DEBUG_FILTERS) {
2799                            Slog.i(TAG, "Found setup wizard;"
2800                                + " allow priority " + filter.getPriority() + ";"
2801                                + " package: " + filter.activity.info.packageName
2802                                + " activity: " + filter.activity.className
2803                                + " priority: " + filter.getPriority());
2804                        }
2805                        // skip setup wizard; allow it to keep the high priority filter
2806                        continue;
2807                    }
2808                    if (DEBUG_FILTERS) {
2809                        Slog.i(TAG, "Protected action; cap priority to 0;"
2810                                + " package: " + filter.activity.info.packageName
2811                                + " activity: " + filter.activity.className
2812                                + " origPrio: " + filter.getPriority());
2813                    }
2814                    filter.setPriority(0);
2815                }
2816            }
2817            mDeferProtectedFilters = false;
2818            mProtectedFilters.clear();
2819
2820            // Now that we know all of the shared libraries, update all clients to have
2821            // the correct library paths.
2822            updateAllSharedLibrariesLPw(null);
2823
2824            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2825                // NOTE: We ignore potential failures here during a system scan (like
2826                // the rest of the commands above) because there's precious little we
2827                // can do about it. A settings error is reported, though.
2828                adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
2829            }
2830
2831            // Now that we know all the packages we are keeping,
2832            // read and update their last usage times.
2833            mPackageUsage.read(mPackages);
2834            mCompilerStats.read();
2835
2836            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2837                    SystemClock.uptimeMillis());
2838            Slog.i(TAG, "Time to scan packages: "
2839                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2840                    + " seconds");
2841
2842            // If the platform SDK has changed since the last time we booted,
2843            // we need to re-grant app permission to catch any new ones that
2844            // appear.  This is really a hack, and means that apps can in some
2845            // cases get permissions that the user didn't initially explicitly
2846            // allow...  it would be nice to have some better way to handle
2847            // this situation.
2848            int updateFlags = UPDATE_PERMISSIONS_ALL;
2849            if (ver.sdkVersion != mSdkVersion) {
2850                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
2851                        + mSdkVersion + "; regranting permissions for internal storage");
2852                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
2853            }
2854            updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags);
2855            ver.sdkVersion = mSdkVersion;
2856
2857            // If this is the first boot or an update from pre-M, and it is a normal
2858            // boot, then we need to initialize the default preferred apps across
2859            // all defined users.
2860            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
2861                for (UserInfo user : sUserManager.getUsers(true)) {
2862                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
2863                    applyFactoryDefaultBrowserLPw(user.id);
2864                    primeDomainVerificationsLPw(user.id);
2865                }
2866            }
2867
2868            // Prepare storage for system user really early during boot,
2869            // since core system apps like SettingsProvider and SystemUI
2870            // can't wait for user to start
2871            final int storageFlags;
2872            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
2873                storageFlags = StorageManager.FLAG_STORAGE_DE;
2874            } else {
2875                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
2876            }
2877            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
2878                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
2879                    true /* onlyCoreApps */);
2880            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
2881                BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync",
2882                        Trace.TRACE_TAG_PACKAGE_MANAGER);
2883                traceLog.traceBegin("AppDataFixup");
2884                try {
2885                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
2886                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
2887                } catch (InstallerException e) {
2888                    Slog.w(TAG, "Trouble fixing GIDs", e);
2889                }
2890                traceLog.traceEnd();
2891
2892                traceLog.traceBegin("AppDataPrepare");
2893                if (deferPackages == null || deferPackages.isEmpty()) {
2894                    return;
2895                }
2896                int count = 0;
2897                for (String pkgName : deferPackages) {
2898                    PackageParser.Package pkg = null;
2899                    synchronized (mPackages) {
2900                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
2901                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
2902                            pkg = ps.pkg;
2903                        }
2904                    }
2905                    if (pkg != null) {
2906                        synchronized (mInstallLock) {
2907                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
2908                                    true /* maybeMigrateAppData */);
2909                        }
2910                        count++;
2911                    }
2912                }
2913                traceLog.traceEnd();
2914                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
2915            }, "prepareAppData");
2916
2917            // If this is first boot after an OTA, and a normal boot, then
2918            // we need to clear code cache directories.
2919            // Note that we do *not* clear the application profiles. These remain valid
2920            // across OTAs and are used to drive profile verification (post OTA) and
2921            // profile compilation (without waiting to collect a fresh set of profiles).
2922            if (mIsUpgrade && !onlyCore) {
2923                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2924                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2925                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2926                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
2927                        // No apps are running this early, so no need to freeze
2928                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
2929                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
2930                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
2931                    }
2932                }
2933                ver.fingerprint = Build.FINGERPRINT;
2934            }
2935
2936            checkDefaultBrowser();
2937
2938            // clear only after permissions and other defaults have been updated
2939            mExistingSystemPackages.clear();
2940            mPromoteSystemApps = false;
2941
2942            // All the changes are done during package scanning.
2943            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2944
2945            // can downgrade to reader
2946            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
2947            mSettings.writeLPr();
2948            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2949
2950            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2951                    SystemClock.uptimeMillis());
2952
2953            if (!mOnlyCore) {
2954                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
2955                mRequiredInstallerPackage = getRequiredInstallerLPr();
2956                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
2957                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2958                if (mIntentFilterVerifierComponent != null) {
2959                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2960                            mIntentFilterVerifierComponent);
2961                } else {
2962                    mIntentFilterVerifier = null;
2963                }
2964                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2965                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
2966                        SharedLibraryInfo.VERSION_UNDEFINED);
2967                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
2968                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2969                        SharedLibraryInfo.VERSION_UNDEFINED);
2970            } else {
2971                mRequiredVerifierPackage = null;
2972                mRequiredInstallerPackage = null;
2973                mRequiredUninstallerPackage = null;
2974                mIntentFilterVerifierComponent = null;
2975                mIntentFilterVerifier = null;
2976                mServicesSystemSharedLibraryPackageName = null;
2977                mSharedSystemSharedLibraryPackageName = null;
2978            }
2979
2980            mInstallerService = new PackageInstallerService(context, this);
2981            final Pair<ComponentName, String> instantAppResolverComponent =
2982                    getInstantAppResolverLPr();
2983            if (instantAppResolverComponent != null) {
2984                if (DEBUG_EPHEMERAL) {
2985                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2986                }
2987                mInstantAppResolverConnection = new EphemeralResolverConnection(
2988                        mContext, instantAppResolverComponent.first,
2989                        instantAppResolverComponent.second);
2990                mInstantAppResolverSettingsComponent =
2991                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
2992            } else {
2993                mInstantAppResolverConnection = null;
2994                mInstantAppResolverSettingsComponent = null;
2995            }
2996            updateInstantAppInstallerLocked(null);
2997
2998            // Read and update the usage of dex files.
2999            // Do this at the end of PM init so that all the packages have their
3000            // data directory reconciled.
3001            // At this point we know the code paths of the packages, so we can validate
3002            // the disk file and build the internal cache.
3003            // The usage file is expected to be small so loading and verifying it
3004            // should take a fairly small time compare to the other activities (e.g. package
3005            // scanning).
3006            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3007            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3008            for (int userId : currentUserIds) {
3009                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3010            }
3011            mDexManager.load(userPackages);
3012        } // synchronized (mPackages)
3013        } // synchronized (mInstallLock)
3014
3015        // Now after opening every single application zip, make sure they
3016        // are all flushed.  Not really needed, but keeps things nice and
3017        // tidy.
3018        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3019        Runtime.getRuntime().gc();
3020        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3021
3022        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3023        FallbackCategoryProvider.loadFallbacks();
3024        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3025
3026        // The initial scanning above does many calls into installd while
3027        // holding the mPackages lock, but we're mostly interested in yelling
3028        // once we have a booted system.
3029        mInstaller.setWarnIfHeld(mPackages);
3030
3031        // Expose private service for system components to use.
3032        LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
3033        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3034    }
3035
3036    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3037        // we're only interested in updating the installer appliction when 1) it's not
3038        // already set or 2) the modified package is the installer
3039        if (mInstantAppInstallerActivity != null
3040                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3041                        .equals(modifiedPackage)) {
3042            return;
3043        }
3044        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3045    }
3046
3047    private static File preparePackageParserCache(boolean isUpgrade) {
3048        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3049            return null;
3050        }
3051
3052        // Disable package parsing on eng builds to allow for faster incremental development.
3053        if ("eng".equals(Build.TYPE)) {
3054            return null;
3055        }
3056
3057        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3058            Slog.i(TAG, "Disabling package parser cache due to system property.");
3059            return null;
3060        }
3061
3062        // The base directory for the package parser cache lives under /data/system/.
3063        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3064                "package_cache");
3065        if (cacheBaseDir == null) {
3066            return null;
3067        }
3068
3069        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3070        // This also serves to "GC" unused entries when the package cache version changes (which
3071        // can only happen during upgrades).
3072        if (isUpgrade) {
3073            FileUtils.deleteContents(cacheBaseDir);
3074        }
3075
3076
3077        // Return the versioned package cache directory. This is something like
3078        // "/data/system/package_cache/1"
3079        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3080
3081        // The following is a workaround to aid development on non-numbered userdebug
3082        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3083        // the system partition is newer.
3084        //
3085        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3086        // that starts with "eng." to signify that this is an engineering build and not
3087        // destined for release.
3088        if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3089            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3090
3091            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3092            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3093            // in general and should not be used for production changes. In this specific case,
3094            // we know that they will work.
3095            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3096            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3097                FileUtils.deleteContents(cacheBaseDir);
3098                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3099            }
3100        }
3101
3102        return cacheDir;
3103    }
3104
3105    @Override
3106    public boolean isFirstBoot() {
3107        // allow instant applications
3108        return mFirstBoot;
3109    }
3110
3111    @Override
3112    public boolean isOnlyCoreApps() {
3113        // allow instant applications
3114        return mOnlyCore;
3115    }
3116
3117    @Override
3118    public boolean isUpgrade() {
3119        // allow instant applications
3120        return mIsUpgrade;
3121    }
3122
3123    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3124        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3125
3126        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3127                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3128                UserHandle.USER_SYSTEM);
3129        if (matches.size() == 1) {
3130            return matches.get(0).getComponentInfo().packageName;
3131        } else if (matches.size() == 0) {
3132            Log.e(TAG, "There should probably be a verifier, but, none were found");
3133            return null;
3134        }
3135        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3136    }
3137
3138    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3139        synchronized (mPackages) {
3140            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3141            if (libraryEntry == null) {
3142                throw new IllegalStateException("Missing required shared library:" + name);
3143            }
3144            return libraryEntry.apk;
3145        }
3146    }
3147
3148    private @NonNull String getRequiredInstallerLPr() {
3149        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3150        intent.addCategory(Intent.CATEGORY_DEFAULT);
3151        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3152
3153        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3154                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3155                UserHandle.USER_SYSTEM);
3156        if (matches.size() == 1) {
3157            ResolveInfo resolveInfo = matches.get(0);
3158            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3159                throw new RuntimeException("The installer must be a privileged app");
3160            }
3161            return matches.get(0).getComponentInfo().packageName;
3162        } else {
3163            throw new RuntimeException("There must be exactly one installer; found " + matches);
3164        }
3165    }
3166
3167    private @NonNull String getRequiredUninstallerLPr() {
3168        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3169        intent.addCategory(Intent.CATEGORY_DEFAULT);
3170        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3171
3172        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3173                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3174                UserHandle.USER_SYSTEM);
3175        if (resolveInfo == null ||
3176                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3177            throw new RuntimeException("There must be exactly one uninstaller; found "
3178                    + resolveInfo);
3179        }
3180        return resolveInfo.getComponentInfo().packageName;
3181    }
3182
3183    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3184        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3185
3186        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3187                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3188                UserHandle.USER_SYSTEM);
3189        ResolveInfo best = null;
3190        final int N = matches.size();
3191        for (int i = 0; i < N; i++) {
3192            final ResolveInfo cur = matches.get(i);
3193            final String packageName = cur.getComponentInfo().packageName;
3194            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3195                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3196                continue;
3197            }
3198
3199            if (best == null || cur.priority > best.priority) {
3200                best = cur;
3201            }
3202        }
3203
3204        if (best != null) {
3205            return best.getComponentInfo().getComponentName();
3206        }
3207        Slog.w(TAG, "Intent filter verifier not found");
3208        return null;
3209    }
3210
3211    @Override
3212    public @Nullable ComponentName getInstantAppResolverComponent() {
3213        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3214            return null;
3215        }
3216        synchronized (mPackages) {
3217            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3218            if (instantAppResolver == null) {
3219                return null;
3220            }
3221            return instantAppResolver.first;
3222        }
3223    }
3224
3225    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3226        final String[] packageArray =
3227                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3228        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3229            if (DEBUG_EPHEMERAL) {
3230                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3231            }
3232            return null;
3233        }
3234
3235        final int callingUid = Binder.getCallingUid();
3236        final int resolveFlags =
3237                MATCH_DIRECT_BOOT_AWARE
3238                | MATCH_DIRECT_BOOT_UNAWARE
3239                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3240        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3241        final Intent resolverIntent = new Intent(actionName);
3242        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3243                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3244        // temporarily look for the old action
3245        if (resolvers.size() == 0) {
3246            if (DEBUG_EPHEMERAL) {
3247                Slog.d(TAG, "Ephemeral resolver not found with new action; try old one");
3248            }
3249            actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE;
3250            resolverIntent.setAction(actionName);
3251            resolvers = queryIntentServicesInternal(resolverIntent, null,
3252                    resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3253        }
3254        final int N = resolvers.size();
3255        if (N == 0) {
3256            if (DEBUG_EPHEMERAL) {
3257                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3258            }
3259            return null;
3260        }
3261
3262        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3263        for (int i = 0; i < N; i++) {
3264            final ResolveInfo info = resolvers.get(i);
3265
3266            if (info.serviceInfo == null) {
3267                continue;
3268            }
3269
3270            final String packageName = info.serviceInfo.packageName;
3271            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3272                if (DEBUG_EPHEMERAL) {
3273                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3274                            + " pkg: " + packageName + ", info:" + info);
3275                }
3276                continue;
3277            }
3278
3279            if (DEBUG_EPHEMERAL) {
3280                Slog.v(TAG, "Ephemeral resolver found;"
3281                        + " pkg: " + packageName + ", info:" + info);
3282            }
3283            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3284        }
3285        if (DEBUG_EPHEMERAL) {
3286            Slog.v(TAG, "Ephemeral resolver NOT found");
3287        }
3288        return null;
3289    }
3290
3291    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3292        final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE);
3293        intent.addCategory(Intent.CATEGORY_DEFAULT);
3294        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3295
3296        final int resolveFlags =
3297                MATCH_DIRECT_BOOT_AWARE
3298                | MATCH_DIRECT_BOOT_UNAWARE
3299                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3300        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3301                resolveFlags, UserHandle.USER_SYSTEM);
3302        // temporarily look for the old action
3303        if (matches.isEmpty()) {
3304            if (DEBUG_EPHEMERAL) {
3305                Slog.d(TAG, "Ephemeral installer not found with new action; try old one");
3306            }
3307            intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE);
3308            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3309                    resolveFlags, UserHandle.USER_SYSTEM);
3310        }
3311        Iterator<ResolveInfo> iter = matches.iterator();
3312        while (iter.hasNext()) {
3313            final ResolveInfo rInfo = iter.next();
3314            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3315            if (ps != null) {
3316                final PermissionsState permissionsState = ps.getPermissionsState();
3317                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) {
3318                    continue;
3319                }
3320            }
3321            iter.remove();
3322        }
3323        if (matches.size() == 0) {
3324            return null;
3325        } else if (matches.size() == 1) {
3326            return (ActivityInfo) matches.get(0).getComponentInfo();
3327        } else {
3328            throw new RuntimeException(
3329                    "There must be at most one ephemeral installer; found " + matches);
3330        }
3331    }
3332
3333    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3334            @NonNull ComponentName resolver) {
3335        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3336                .addCategory(Intent.CATEGORY_DEFAULT)
3337                .setPackage(resolver.getPackageName());
3338        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3339        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3340                UserHandle.USER_SYSTEM);
3341        // temporarily look for the old action
3342        if (matches.isEmpty()) {
3343            if (DEBUG_EPHEMERAL) {
3344                Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one");
3345            }
3346            intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS);
3347            matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3348                    UserHandle.USER_SYSTEM);
3349        }
3350        if (matches.isEmpty()) {
3351            return null;
3352        }
3353        return matches.get(0).getComponentInfo().getComponentName();
3354    }
3355
3356    private void primeDomainVerificationsLPw(int userId) {
3357        if (DEBUG_DOMAIN_VERIFICATION) {
3358            Slog.d(TAG, "Priming domain verifications in user " + userId);
3359        }
3360
3361        SystemConfig systemConfig = SystemConfig.getInstance();
3362        ArraySet<String> packages = systemConfig.getLinkedApps();
3363
3364        for (String packageName : packages) {
3365            PackageParser.Package pkg = mPackages.get(packageName);
3366            if (pkg != null) {
3367                if (!pkg.isSystemApp()) {
3368                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3369                    continue;
3370                }
3371
3372                ArraySet<String> domains = null;
3373                for (PackageParser.Activity a : pkg.activities) {
3374                    for (ActivityIntentInfo filter : a.intents) {
3375                        if (hasValidDomains(filter)) {
3376                            if (domains == null) {
3377                                domains = new ArraySet<String>();
3378                            }
3379                            domains.addAll(filter.getHostsList());
3380                        }
3381                    }
3382                }
3383
3384                if (domains != null && domains.size() > 0) {
3385                    if (DEBUG_DOMAIN_VERIFICATION) {
3386                        Slog.v(TAG, "      + " + packageName);
3387                    }
3388                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3389                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3390                    // and then 'always' in the per-user state actually used for intent resolution.
3391                    final IntentFilterVerificationInfo ivi;
3392                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3393                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3394                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3395                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3396                } else {
3397                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3398                            + "' does not handle web links");
3399                }
3400            } else {
3401                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3402            }
3403        }
3404
3405        scheduleWritePackageRestrictionsLocked(userId);
3406        scheduleWriteSettingsLocked();
3407    }
3408
3409    private void applyFactoryDefaultBrowserLPw(int userId) {
3410        // The default browser app's package name is stored in a string resource,
3411        // with a product-specific overlay used for vendor customization.
3412        String browserPkg = mContext.getResources().getString(
3413                com.android.internal.R.string.default_browser);
3414        if (!TextUtils.isEmpty(browserPkg)) {
3415            // non-empty string => required to be a known package
3416            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3417            if (ps == null) {
3418                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3419                browserPkg = null;
3420            } else {
3421                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3422            }
3423        }
3424
3425        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3426        // default.  If there's more than one, just leave everything alone.
3427        if (browserPkg == null) {
3428            calculateDefaultBrowserLPw(userId);
3429        }
3430    }
3431
3432    private void calculateDefaultBrowserLPw(int userId) {
3433        List<String> allBrowsers = resolveAllBrowserApps(userId);
3434        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3435        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3436    }
3437
3438    private List<String> resolveAllBrowserApps(int userId) {
3439        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3440        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3441                PackageManager.MATCH_ALL, userId);
3442
3443        final int count = list.size();
3444        List<String> result = new ArrayList<String>(count);
3445        for (int i=0; i<count; i++) {
3446            ResolveInfo info = list.get(i);
3447            if (info.activityInfo == null
3448                    || !info.handleAllWebDataURI
3449                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3450                    || result.contains(info.activityInfo.packageName)) {
3451                continue;
3452            }
3453            result.add(info.activityInfo.packageName);
3454        }
3455
3456        return result;
3457    }
3458
3459    private boolean packageIsBrowser(String packageName, int userId) {
3460        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3461                PackageManager.MATCH_ALL, userId);
3462        final int N = list.size();
3463        for (int i = 0; i < N; i++) {
3464            ResolveInfo info = list.get(i);
3465            if (packageName.equals(info.activityInfo.packageName)) {
3466                return true;
3467            }
3468        }
3469        return false;
3470    }
3471
3472    private void checkDefaultBrowser() {
3473        final int myUserId = UserHandle.myUserId();
3474        final String packageName = getDefaultBrowserPackageName(myUserId);
3475        if (packageName != null) {
3476            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3477            if (info == null) {
3478                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3479                synchronized (mPackages) {
3480                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3481                }
3482            }
3483        }
3484    }
3485
3486    @Override
3487    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3488            throws RemoteException {
3489        try {
3490            return super.onTransact(code, data, reply, flags);
3491        } catch (RuntimeException e) {
3492            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3493                Slog.wtf(TAG, "Package Manager Crash", e);
3494            }
3495            throw e;
3496        }
3497    }
3498
3499    static int[] appendInts(int[] cur, int[] add) {
3500        if (add == null) return cur;
3501        if (cur == null) return add;
3502        final int N = add.length;
3503        for (int i=0; i<N; i++) {
3504            cur = appendInt(cur, add[i]);
3505        }
3506        return cur;
3507    }
3508
3509    /**
3510     * Returns whether or not a full application can see an instant application.
3511     * <p>
3512     * Currently, there are three cases in which this can occur:
3513     * <ol>
3514     * <li>The calling application is a "special" process. The special
3515     *     processes are {@link Process#SYSTEM_UID}, {@link Process#SHELL_UID}
3516     *     and {@code 0}</li>
3517     * <li>The calling application has the permission
3518     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}</li>
3519     * <li>[TODO] The calling application is the default launcher on the
3520     *     system partition.</li>
3521     * </ol>
3522     */
3523    private boolean canViewInstantApps(int callingUid, int userId) {
3524        if (callingUid == Process.SYSTEM_UID
3525                || callingUid == Process.SHELL_UID
3526                || callingUid == Process.ROOT_UID) {
3527            return true;
3528        }
3529        if (mContext.checkCallingOrSelfPermission(
3530                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3531            return true;
3532        }
3533        if (mContext.checkCallingOrSelfPermission(
3534                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3535            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3536            if (homeComponent != null
3537                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3538                return true;
3539            }
3540        }
3541        return false;
3542    }
3543
3544    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3545        if (!sUserManager.exists(userId)) return null;
3546        if (ps == null) {
3547            return null;
3548        }
3549        PackageParser.Package p = ps.pkg;
3550        if (p == null) {
3551            return null;
3552        }
3553        final int callingUid = Binder.getCallingUid();
3554        // Filter out ephemeral app metadata:
3555        //   * The system/shell/root can see metadata for any app
3556        //   * An installed app can see metadata for 1) other installed apps
3557        //     and 2) ephemeral apps that have explicitly interacted with it
3558        //   * Ephemeral apps can only see their own data and exposed installed apps
3559        //   * Holding a signature permission allows seeing instant apps
3560        if (filterAppAccessLPr(ps, callingUid, userId)) {
3561            return null;
3562        }
3563
3564        final PermissionsState permissionsState = ps.getPermissionsState();
3565
3566        // Compute GIDs only if requested
3567        final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3568                ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3569        // Compute granted permissions only if package has requested permissions
3570        final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3571                ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3572        final PackageUserState state = ps.readUserState(userId);
3573
3574        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3575                && ps.isSystem()) {
3576            flags |= MATCH_ANY_USER;
3577        }
3578
3579        PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3580                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3581
3582        if (packageInfo == null) {
3583            return null;
3584        }
3585
3586        rebaseEnabledOverlays(packageInfo.applicationInfo, userId);
3587
3588        packageInfo.packageName = packageInfo.applicationInfo.packageName =
3589                resolveExternalPackageNameLPr(p);
3590
3591        return packageInfo;
3592    }
3593
3594    @Override
3595    public void checkPackageStartable(String packageName, int userId) {
3596        final int callingUid = Binder.getCallingUid();
3597        if (getInstantAppPackageName(callingUid) != null) {
3598            throw new SecurityException("Instant applications don't have access to this method");
3599        }
3600        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3601        synchronized (mPackages) {
3602            final PackageSetting ps = mSettings.mPackages.get(packageName);
3603            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3604                throw new SecurityException("Package " + packageName + " was not found!");
3605            }
3606
3607            if (!ps.getInstalled(userId)) {
3608                throw new SecurityException(
3609                        "Package " + packageName + " was not installed for user " + userId + "!");
3610            }
3611
3612            if (mSafeMode && !ps.isSystem()) {
3613                throw new SecurityException("Package " + packageName + " not a system app!");
3614            }
3615
3616            if (mFrozenPackages.contains(packageName)) {
3617                throw new SecurityException("Package " + packageName + " is currently frozen!");
3618            }
3619
3620            if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware()
3621                    || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) {
3622                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3623            }
3624        }
3625    }
3626
3627    @Override
3628    public boolean isPackageAvailable(String packageName, int userId) {
3629        if (!sUserManager.exists(userId)) return false;
3630        final int callingUid = Binder.getCallingUid();
3631        enforceCrossUserPermission(callingUid, userId,
3632                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3633        synchronized (mPackages) {
3634            PackageParser.Package p = mPackages.get(packageName);
3635            if (p != null) {
3636                final PackageSetting ps = (PackageSetting) p.mExtras;
3637                if (filterAppAccessLPr(ps, callingUid, userId)) {
3638                    return false;
3639                }
3640                if (ps != null) {
3641                    final PackageUserState state = ps.readUserState(userId);
3642                    if (state != null) {
3643                        return PackageParser.isAvailable(state);
3644                    }
3645                }
3646            }
3647        }
3648        return false;
3649    }
3650
3651    @Override
3652    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3653        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3654                flags, Binder.getCallingUid(), userId);
3655    }
3656
3657    @Override
3658    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
3659            int flags, int userId) {
3660        return getPackageInfoInternal(versionedPackage.getPackageName(),
3661                versionedPackage.getVersionCode(), flags, Binder.getCallingUid(), userId);
3662    }
3663
3664    /**
3665     * Important: The provided filterCallingUid is used exclusively to filter out packages
3666     * that can be seen based on user state. It's typically the original caller uid prior
3667     * to clearing. Because it can only be provided by trusted code, it's value can be
3668     * trusted and will be used as-is; unlike userId which will be validated by this method.
3669     */
3670    private PackageInfo getPackageInfoInternal(String packageName, int versionCode,
3671            int flags, int filterCallingUid, int userId) {
3672        if (!sUserManager.exists(userId)) return null;
3673        flags = updateFlagsForPackage(flags, userId, packageName);
3674        enforceCrossUserPermission(Binder.getCallingUid(), userId,
3675                false /* requireFullPermission */, false /* checkShell */, "get package info");
3676
3677        // reader
3678        synchronized (mPackages) {
3679            // Normalize package name to handle renamed packages and static libs
3680            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
3681
3682            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
3683            if (matchFactoryOnly) {
3684                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
3685                if (ps != null) {
3686                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3687                        return null;
3688                    }
3689                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3690                        return null;
3691                    }
3692                    return generatePackageInfo(ps, flags, userId);
3693                }
3694            }
3695
3696            PackageParser.Package p = mPackages.get(packageName);
3697            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
3698                return null;
3699            }
3700            if (DEBUG_PACKAGE_INFO)
3701                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
3702            if (p != null) {
3703                final PackageSetting ps = (PackageSetting) p.mExtras;
3704                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3705                    return null;
3706                }
3707                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
3708                    return null;
3709                }
3710                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
3711            }
3712            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
3713                final PackageSetting ps = mSettings.mPackages.get(packageName);
3714                if (ps == null) return null;
3715                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
3716                    return null;
3717                }
3718                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
3719                    return null;
3720                }
3721                return generatePackageInfo(ps, flags, userId);
3722            }
3723        }
3724        return null;
3725    }
3726
3727    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
3728        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
3729            return true;
3730        }
3731        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
3732            return true;
3733        }
3734        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
3735            return true;
3736        }
3737        return false;
3738    }
3739
3740    private boolean isComponentVisibleToInstantApp(
3741            @Nullable ComponentName component, @ComponentType int type) {
3742        if (type == TYPE_ACTIVITY) {
3743            final PackageParser.Activity activity = mActivities.mActivities.get(component);
3744            return activity != null
3745                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3746                    : false;
3747        } else if (type == TYPE_RECEIVER) {
3748            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
3749            return activity != null
3750                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3751                    : false;
3752        } else if (type == TYPE_SERVICE) {
3753            final PackageParser.Service service = mServices.mServices.get(component);
3754            return service != null
3755                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3756                    : false;
3757        } else if (type == TYPE_PROVIDER) {
3758            final PackageParser.Provider provider = mProviders.mProviders.get(component);
3759            return provider != null
3760                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
3761                    : false;
3762        } else if (type == TYPE_UNKNOWN) {
3763            return isComponentVisibleToInstantApp(component);
3764        }
3765        return false;
3766    }
3767
3768    /**
3769     * Returns whether or not access to the application should be filtered.
3770     * <p>
3771     * Access may be limited based upon whether the calling or target applications
3772     * are instant applications.
3773     *
3774     * @see #canAccessInstantApps(int)
3775     */
3776    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
3777            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
3778        // if we're in an isolated process, get the real calling UID
3779        if (Process.isIsolated(callingUid)) {
3780            callingUid = mIsolatedOwners.get(callingUid);
3781        }
3782        final String instantAppPkgName = getInstantAppPackageName(callingUid);
3783        final boolean callerIsInstantApp = instantAppPkgName != null;
3784        if (ps == null) {
3785            if (callerIsInstantApp) {
3786                // pretend the application exists, but, needs to be filtered
3787                return true;
3788            }
3789            return false;
3790        }
3791        // if the target and caller are the same application, don't filter
3792        if (isCallerSameApp(ps.name, callingUid)) {
3793            return false;
3794        }
3795        if (callerIsInstantApp) {
3796            // request for a specific component; if it hasn't been explicitly exposed, filter
3797            if (component != null) {
3798                return !isComponentVisibleToInstantApp(component, componentType);
3799            }
3800            // request for application; if no components have been explicitly exposed, filter
3801            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
3802        }
3803        if (ps.getInstantApp(userId)) {
3804            // caller can see all components of all instant applications, don't filter
3805            if (canViewInstantApps(callingUid, userId)) {
3806                return false;
3807            }
3808            // request for a specific instant application component, filter
3809            if (component != null) {
3810                return true;
3811            }
3812            // request for an instant application; if the caller hasn't been granted access, filter
3813            return !mInstantAppRegistry.isInstantAccessGranted(
3814                    userId, UserHandle.getAppId(callingUid), ps.appId);
3815        }
3816        return false;
3817    }
3818
3819    /**
3820     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
3821     */
3822    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
3823        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
3824    }
3825
3826    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
3827            int flags) {
3828        // Callers can access only the libs they depend on, otherwise they need to explicitly
3829        // ask for the shared libraries given the caller is allowed to access all static libs.
3830        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
3831            // System/shell/root get to see all static libs
3832            final int appId = UserHandle.getAppId(uid);
3833            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
3834                    || appId == Process.ROOT_UID) {
3835                return false;
3836            }
3837        }
3838
3839        // No package means no static lib as it is always on internal storage
3840        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
3841            return false;
3842        }
3843
3844        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
3845                ps.pkg.staticSharedLibVersion);
3846        if (libEntry == null) {
3847            return false;
3848        }
3849
3850        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
3851        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
3852        if (uidPackageNames == null) {
3853            return true;
3854        }
3855
3856        for (String uidPackageName : uidPackageNames) {
3857            if (ps.name.equals(uidPackageName)) {
3858                return false;
3859            }
3860            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
3861            if (uidPs != null) {
3862                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
3863                        libEntry.info.getName());
3864                if (index < 0) {
3865                    continue;
3866                }
3867                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) {
3868                    return false;
3869                }
3870            }
3871        }
3872        return true;
3873    }
3874
3875    @Override
3876    public String[] currentToCanonicalPackageNames(String[] names) {
3877        final int callingUid = Binder.getCallingUid();
3878        if (getInstantAppPackageName(callingUid) != null) {
3879            return names;
3880        }
3881        final String[] out = new String[names.length];
3882        // reader
3883        synchronized (mPackages) {
3884            final int callingUserId = UserHandle.getUserId(callingUid);
3885            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3886            for (int i=names.length-1; i>=0; i--) {
3887                final PackageSetting ps = mSettings.mPackages.get(names[i]);
3888                boolean translateName = false;
3889                if (ps != null && ps.realName != null) {
3890                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
3891                    translateName = !targetIsInstantApp
3892                            || canViewInstantApps
3893                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3894                                    UserHandle.getAppId(callingUid), ps.appId);
3895                }
3896                out[i] = translateName ? ps.realName : names[i];
3897            }
3898        }
3899        return out;
3900    }
3901
3902    @Override
3903    public String[] canonicalToCurrentPackageNames(String[] names) {
3904        final int callingUid = Binder.getCallingUid();
3905        if (getInstantAppPackageName(callingUid) != null) {
3906            return names;
3907        }
3908        final String[] out = new String[names.length];
3909        // reader
3910        synchronized (mPackages) {
3911            final int callingUserId = UserHandle.getUserId(callingUid);
3912            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
3913            for (int i=names.length-1; i>=0; i--) {
3914                final String cur = mSettings.getRenamedPackageLPr(names[i]);
3915                boolean translateName = false;
3916                if (cur != null) {
3917                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
3918                    final boolean targetIsInstantApp =
3919                            ps != null && ps.getInstantApp(callingUserId);
3920                    translateName = !targetIsInstantApp
3921                            || canViewInstantApps
3922                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
3923                                    UserHandle.getAppId(callingUid), ps.appId);
3924                }
3925                out[i] = translateName ? cur : names[i];
3926            }
3927        }
3928        return out;
3929    }
3930
3931    @Override
3932    public int getPackageUid(String packageName, int flags, int userId) {
3933        if (!sUserManager.exists(userId)) return -1;
3934        final int callingUid = Binder.getCallingUid();
3935        flags = updateFlagsForPackage(flags, userId, packageName);
3936        enforceCrossUserPermission(callingUid, userId,
3937                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
3938
3939        // reader
3940        synchronized (mPackages) {
3941            final PackageParser.Package p = mPackages.get(packageName);
3942            if (p != null && p.isMatch(flags)) {
3943                PackageSetting ps = (PackageSetting) p.mExtras;
3944                if (filterAppAccessLPr(ps, callingUid, userId)) {
3945                    return -1;
3946                }
3947                return UserHandle.getUid(userId, p.applicationInfo.uid);
3948            }
3949            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3950                final PackageSetting ps = mSettings.mPackages.get(packageName);
3951                if (ps != null && ps.isMatch(flags)
3952                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3953                    return UserHandle.getUid(userId, ps.appId);
3954                }
3955            }
3956        }
3957
3958        return -1;
3959    }
3960
3961    @Override
3962    public int[] getPackageGids(String packageName, int flags, int userId) {
3963        if (!sUserManager.exists(userId)) return null;
3964        final int callingUid = Binder.getCallingUid();
3965        flags = updateFlagsForPackage(flags, userId, packageName);
3966        enforceCrossUserPermission(callingUid, userId,
3967                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
3968
3969        // reader
3970        synchronized (mPackages) {
3971            final PackageParser.Package p = mPackages.get(packageName);
3972            if (p != null && p.isMatch(flags)) {
3973                PackageSetting ps = (PackageSetting) p.mExtras;
3974                if (filterAppAccessLPr(ps, callingUid, userId)) {
3975                    return null;
3976                }
3977                // TODO: Shouldn't this be checking for package installed state for userId and
3978                // return null?
3979                return ps.getPermissionsState().computeGids(userId);
3980            }
3981            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
3982                final PackageSetting ps = mSettings.mPackages.get(packageName);
3983                if (ps != null && ps.isMatch(flags)
3984                        && !filterAppAccessLPr(ps, callingUid, userId)) {
3985                    return ps.getPermissionsState().computeGids(userId);
3986                }
3987            }
3988        }
3989
3990        return null;
3991    }
3992
3993    static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) {
3994        if (bp.perm != null) {
3995            return PackageParser.generatePermissionInfo(bp.perm, flags);
3996        }
3997        PermissionInfo pi = new PermissionInfo();
3998        pi.name = bp.name;
3999        pi.packageName = bp.sourcePackage;
4000        pi.nonLocalizedLabel = bp.name;
4001        pi.protectionLevel = bp.protectionLevel;
4002        return pi;
4003    }
4004
4005    @Override
4006    public PermissionInfo getPermissionInfo(String name, int flags) {
4007        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4008            return null;
4009        }
4010        // reader
4011        synchronized (mPackages) {
4012            final BasePermission p = mSettings.mPermissions.get(name);
4013            if (p != null) {
4014                return generatePermissionInfo(p, flags);
4015            }
4016            return null;
4017        }
4018    }
4019
4020    @Override
4021    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group,
4022            int flags) {
4023        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4024            return null;
4025        }
4026        // reader
4027        synchronized (mPackages) {
4028            if (group != null && !mPermissionGroups.containsKey(group)) {
4029                // This is thrown as NameNotFoundException
4030                return null;
4031            }
4032
4033            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
4034            for (BasePermission p : mSettings.mPermissions.values()) {
4035                if (group == null) {
4036                    if (p.perm == null || p.perm.info.group == null) {
4037                        out.add(generatePermissionInfo(p, flags));
4038                    }
4039                } else {
4040                    if (p.perm != null && group.equals(p.perm.info.group)) {
4041                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
4042                    }
4043                }
4044            }
4045            return new ParceledListSlice<>(out);
4046        }
4047    }
4048
4049    @Override
4050    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
4051        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4052            return null;
4053        }
4054        // reader
4055        synchronized (mPackages) {
4056            return PackageParser.generatePermissionGroupInfo(
4057                    mPermissionGroups.get(name), flags);
4058        }
4059    }
4060
4061    @Override
4062    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4063        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4064            return ParceledListSlice.emptyList();
4065        }
4066        // reader
4067        synchronized (mPackages) {
4068            final int N = mPermissionGroups.size();
4069            ArrayList<PermissionGroupInfo> out
4070                    = new ArrayList<PermissionGroupInfo>(N);
4071            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
4072                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
4073            }
4074            return new ParceledListSlice<>(out);
4075        }
4076    }
4077
4078    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4079            int filterCallingUid, int userId) {
4080        if (!sUserManager.exists(userId)) return null;
4081        PackageSetting ps = mSettings.mPackages.get(packageName);
4082        if (ps != null) {
4083            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4084                return null;
4085            }
4086            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4087                return null;
4088            }
4089            if (ps.pkg == null) {
4090                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4091                if (pInfo != null) {
4092                    return pInfo.applicationInfo;
4093                }
4094                return null;
4095            }
4096            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4097                    ps.readUserState(userId), userId);
4098            if (ai != null) {
4099                rebaseEnabledOverlays(ai, userId);
4100                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4101            }
4102            return ai;
4103        }
4104        return null;
4105    }
4106
4107    @Override
4108    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4109        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4110    }
4111
4112    /**
4113     * Important: The provided filterCallingUid is used exclusively to filter out applications
4114     * that can be seen based on user state. It's typically the original caller uid prior
4115     * to clearing. Because it can only be provided by trusted code, it's value can be
4116     * trusted and will be used as-is; unlike userId which will be validated by this method.
4117     */
4118    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4119            int filterCallingUid, int userId) {
4120        if (!sUserManager.exists(userId)) return null;
4121        flags = updateFlagsForApplication(flags, userId, packageName);
4122        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4123                false /* requireFullPermission */, false /* checkShell */, "get application info");
4124
4125        // writer
4126        synchronized (mPackages) {
4127            // Normalize package name to handle renamed packages and static libs
4128            packageName = resolveInternalPackageNameLPr(packageName,
4129                    PackageManager.VERSION_CODE_HIGHEST);
4130
4131            PackageParser.Package p = mPackages.get(packageName);
4132            if (DEBUG_PACKAGE_INFO) Log.v(
4133                    TAG, "getApplicationInfo " + packageName
4134                    + ": " + p);
4135            if (p != null) {
4136                PackageSetting ps = mSettings.mPackages.get(packageName);
4137                if (ps == null) return null;
4138                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4139                    return null;
4140                }
4141                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4142                    return null;
4143                }
4144                // Note: isEnabledLP() does not apply here - always return info
4145                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4146                        p, flags, ps.readUserState(userId), userId);
4147                if (ai != null) {
4148                    rebaseEnabledOverlays(ai, userId);
4149                    ai.packageName = resolveExternalPackageNameLPr(p);
4150                }
4151                return ai;
4152            }
4153            if ("android".equals(packageName)||"system".equals(packageName)) {
4154                return mAndroidApplication;
4155            }
4156            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4157                // Already generates the external package name
4158                return generateApplicationInfoFromSettingsLPw(packageName,
4159                        flags, filterCallingUid, userId);
4160            }
4161        }
4162        return null;
4163    }
4164
4165    private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) {
4166        List<String> paths = new ArrayList<>();
4167        ArrayMap<String, ArrayList<String>> userSpecificOverlays =
4168            mEnabledOverlayPaths.get(userId);
4169        if (userSpecificOverlays != null) {
4170            if (!"android".equals(ai.packageName)) {
4171                ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android");
4172                if (frameworkOverlays != null) {
4173                    paths.addAll(frameworkOverlays);
4174                }
4175            }
4176
4177            ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName);
4178            if (appOverlays != null) {
4179                paths.addAll(appOverlays);
4180            }
4181        }
4182        ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null;
4183    }
4184
4185    private String normalizePackageNameLPr(String packageName) {
4186        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4187        return normalizedPackageName != null ? normalizedPackageName : packageName;
4188    }
4189
4190    @Override
4191    public void deletePreloadsFileCache() {
4192        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4193            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4194        }
4195        File dir = Environment.getDataPreloadsFileCacheDirectory();
4196        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4197        FileUtils.deleteContents(dir);
4198    }
4199
4200    @Override
4201    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4202            final int storageFlags, final IPackageDataObserver observer) {
4203        mContext.enforceCallingOrSelfPermission(
4204                android.Manifest.permission.CLEAR_APP_CACHE, null);
4205        mHandler.post(() -> {
4206            boolean success = false;
4207            try {
4208                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4209                success = true;
4210            } catch (IOException e) {
4211                Slog.w(TAG, e);
4212            }
4213            if (observer != null) {
4214                try {
4215                    observer.onRemoveCompleted(null, success);
4216                } catch (RemoteException e) {
4217                    Slog.w(TAG, e);
4218                }
4219            }
4220        });
4221    }
4222
4223    @Override
4224    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4225            final int storageFlags, final IntentSender pi) {
4226        mContext.enforceCallingOrSelfPermission(
4227                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4228        mHandler.post(() -> {
4229            boolean success = false;
4230            try {
4231                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4232                success = true;
4233            } catch (IOException e) {
4234                Slog.w(TAG, e);
4235            }
4236            if (pi != null) {
4237                try {
4238                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4239                } catch (SendIntentException e) {
4240                    Slog.w(TAG, e);
4241                }
4242            }
4243        });
4244    }
4245
4246    /**
4247     * Blocking call to clear various types of cached data across the system
4248     * until the requested bytes are available.
4249     */
4250    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4251        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4252        final File file = storage.findPathForUuid(volumeUuid);
4253        if (file.getUsableSpace() >= bytes) return;
4254
4255        if (ENABLE_FREE_CACHE_V2) {
4256            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4257                    volumeUuid);
4258            final boolean aggressive = (storageFlags
4259                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4260            final boolean defyReserved = (storageFlags
4261                    & StorageManager.FLAG_ALLOCATE_DEFY_RESERVED) != 0;
4262            final long reservedBytes = (aggressive || defyReserved) ? 0
4263                    : storage.getStorageCacheBytes(file);
4264
4265            // 1. Pre-flight to determine if we have any chance to succeed
4266            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4267            if (internalVolume && (aggressive || SystemProperties
4268                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4269                deletePreloadsFileCache();
4270                if (file.getUsableSpace() >= bytes) return;
4271            }
4272
4273            // 3. Consider parsed APK data (aggressive only)
4274            if (internalVolume && aggressive) {
4275                FileUtils.deleteContents(mCacheDir);
4276                if (file.getUsableSpace() >= bytes) return;
4277            }
4278
4279            // 4. Consider cached app data (above quotas)
4280            try {
4281                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4282                        Installer.FLAG_FREE_CACHE_V2);
4283            } catch (InstallerException ignored) {
4284            }
4285            if (file.getUsableSpace() >= bytes) return;
4286
4287            // 5. Consider shared libraries with refcount=0 and age>min cache period
4288            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4289                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4290                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4291                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4292                return;
4293            }
4294
4295            // 6. Consider dexopt output (aggressive only)
4296            // TODO: Implement
4297
4298            // 7. Consider installed instant apps unused longer than min cache period
4299            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4300                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4301                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4302                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4303                return;
4304            }
4305
4306            // 8. Consider cached app data (below quotas)
4307            try {
4308                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4309                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4310            } catch (InstallerException ignored) {
4311            }
4312            if (file.getUsableSpace() >= bytes) return;
4313
4314            // 9. Consider DropBox entries
4315            // TODO: Implement
4316
4317            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4318            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4319                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4320                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4321                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4322                return;
4323            }
4324        } else {
4325            try {
4326                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4327            } catch (InstallerException ignored) {
4328            }
4329            if (file.getUsableSpace() >= bytes) return;
4330        }
4331
4332        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4333    }
4334
4335    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4336            throws IOException {
4337        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4338        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4339
4340        List<VersionedPackage> packagesToDelete = null;
4341        final long now = System.currentTimeMillis();
4342
4343        synchronized (mPackages) {
4344            final int[] allUsers = sUserManager.getUserIds();
4345            final int libCount = mSharedLibraries.size();
4346            for (int i = 0; i < libCount; i++) {
4347                final SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4348                if (versionedLib == null) {
4349                    continue;
4350                }
4351                final int versionCount = versionedLib.size();
4352                for (int j = 0; j < versionCount; j++) {
4353                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4354                    // Skip packages that are not static shared libs.
4355                    if (!libInfo.isStatic()) {
4356                        break;
4357                    }
4358                    // Important: We skip static shared libs used for some user since
4359                    // in such a case we need to keep the APK on the device. The check for
4360                    // a lib being used for any user is performed by the uninstall call.
4361                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4362                    // Resolve the package name - we use synthetic package names internally
4363                    final String internalPackageName = resolveInternalPackageNameLPr(
4364                            declaringPackage.getPackageName(), declaringPackage.getVersionCode());
4365                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4366                    // Skip unused static shared libs cached less than the min period
4367                    // to prevent pruning a lib needed by a subsequently installed package.
4368                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4369                        continue;
4370                    }
4371                    if (packagesToDelete == null) {
4372                        packagesToDelete = new ArrayList<>();
4373                    }
4374                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4375                            declaringPackage.getVersionCode()));
4376                }
4377            }
4378        }
4379
4380        if (packagesToDelete != null) {
4381            final int packageCount = packagesToDelete.size();
4382            for (int i = 0; i < packageCount; i++) {
4383                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4384                // Delete the package synchronously (will fail of the lib used for any user).
4385                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getVersionCode(),
4386                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4387                                == PackageManager.DELETE_SUCCEEDED) {
4388                    if (volume.getUsableSpace() >= neededSpace) {
4389                        return true;
4390                    }
4391                }
4392            }
4393        }
4394
4395        return false;
4396    }
4397
4398    /**
4399     * Update given flags based on encryption status of current user.
4400     */
4401    private int updateFlags(int flags, int userId) {
4402        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4403                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4404            // Caller expressed an explicit opinion about what encryption
4405            // aware/unaware components they want to see, so fall through and
4406            // give them what they want
4407        } else {
4408            // Caller expressed no opinion, so match based on user state
4409            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4410                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4411            } else {
4412                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4413            }
4414        }
4415        return flags;
4416    }
4417
4418    private UserManagerInternal getUserManagerInternal() {
4419        if (mUserManagerInternal == null) {
4420            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4421        }
4422        return mUserManagerInternal;
4423    }
4424
4425    private DeviceIdleController.LocalService getDeviceIdleController() {
4426        if (mDeviceIdleController == null) {
4427            mDeviceIdleController =
4428                    LocalServices.getService(DeviceIdleController.LocalService.class);
4429        }
4430        return mDeviceIdleController;
4431    }
4432
4433    /**
4434     * Update given flags when being used to request {@link PackageInfo}.
4435     */
4436    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4437        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4438        boolean triaged = true;
4439        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4440                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4441            // Caller is asking for component details, so they'd better be
4442            // asking for specific encryption matching behavior, or be triaged
4443            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4444                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4445                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4446                triaged = false;
4447            }
4448        }
4449        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4450                | PackageManager.MATCH_SYSTEM_ONLY
4451                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4452            triaged = false;
4453        }
4454        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4455            enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
4456                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4457                    + Debug.getCallers(5));
4458        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4459                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4460            // If the caller wants all packages and has a restricted profile associated with it,
4461            // then match all users. This is to make sure that launchers that need to access work
4462            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4463            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4464            flags |= PackageManager.MATCH_ANY_USER;
4465        }
4466        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4467            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4468                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4469        }
4470        return updateFlags(flags, userId);
4471    }
4472
4473    /**
4474     * Update given flags when being used to request {@link ApplicationInfo}.
4475     */
4476    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4477        return updateFlagsForPackage(flags, userId, cookie);
4478    }
4479
4480    /**
4481     * Update given flags when being used to request {@link ComponentInfo}.
4482     */
4483    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4484        if (cookie instanceof Intent) {
4485            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4486                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4487            }
4488        }
4489
4490        boolean triaged = true;
4491        // Caller is asking for component details, so they'd better be
4492        // asking for specific encryption matching behavior, or be triaged
4493        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4494                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4495                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4496            triaged = false;
4497        }
4498        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4499            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4500                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4501        }
4502
4503        return updateFlags(flags, userId);
4504    }
4505
4506    /**
4507     * Update given intent when being used to request {@link ResolveInfo}.
4508     */
4509    private Intent updateIntentForResolve(Intent intent) {
4510        if (intent.getSelector() != null) {
4511            intent = intent.getSelector();
4512        }
4513        if (DEBUG_PREFERRED) {
4514            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4515        }
4516        return intent;
4517    }
4518
4519    /**
4520     * Update given flags when being used to request {@link ResolveInfo}.
4521     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4522     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4523     * flag set. However, this flag is only honoured in three circumstances:
4524     * <ul>
4525     * <li>when called from a system process</li>
4526     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4527     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4528     * action and a {@code android.intent.category.BROWSABLE} category</li>
4529     * </ul>
4530     */
4531    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4532        return updateFlagsForResolve(flags, userId, intent, callingUid,
4533                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4534    }
4535    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4536            boolean wantInstantApps) {
4537        return updateFlagsForResolve(flags, userId, intent, callingUid,
4538                wantInstantApps, false /*onlyExposedExplicitly*/);
4539    }
4540    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4541            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4542        // Safe mode means we shouldn't match any third-party components
4543        if (mSafeMode) {
4544            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4545        }
4546        if (getInstantAppPackageName(callingUid) != null) {
4547            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4548            if (onlyExposedExplicitly) {
4549                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4550            }
4551            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4552            flags |= PackageManager.MATCH_INSTANT;
4553        } else {
4554            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4555            final boolean allowMatchInstant =
4556                    (wantInstantApps
4557                            && Intent.ACTION_VIEW.equals(intent.getAction())
4558                            && hasWebURI(intent))
4559                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4560            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4561                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4562            if (!allowMatchInstant) {
4563                flags &= ~PackageManager.MATCH_INSTANT;
4564            }
4565        }
4566        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4567    }
4568
4569    private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state,
4570            int userId) {
4571        ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId);
4572        if (ret != null) {
4573            rebaseEnabledOverlays(ret.applicationInfo, userId);
4574        }
4575        return ret;
4576    }
4577
4578    private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags,
4579            PackageUserState state, int userId) {
4580        ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId);
4581        if (ai != null) {
4582            rebaseEnabledOverlays(ai.applicationInfo, userId);
4583        }
4584        return ai;
4585    }
4586
4587    @Override
4588    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4589        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4590    }
4591
4592    /**
4593     * Important: The provided filterCallingUid is used exclusively to filter out activities
4594     * that can be seen based on user state. It's typically the original caller uid prior
4595     * to clearing. Because it can only be provided by trusted code, it's value can be
4596     * trusted and will be used as-is; unlike userId which will be validated by this method.
4597     */
4598    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4599            int filterCallingUid, int userId) {
4600        if (!sUserManager.exists(userId)) return null;
4601        flags = updateFlagsForComponent(flags, userId, component);
4602        enforceCrossUserPermission(Binder.getCallingUid(), userId,
4603                false /* requireFullPermission */, false /* checkShell */, "get activity info");
4604        synchronized (mPackages) {
4605            PackageParser.Activity a = mActivities.mActivities.get(component);
4606
4607            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4608            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4609                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4610                if (ps == null) return null;
4611                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4612                    return null;
4613                }
4614                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4615            }
4616            if (mResolveComponentName.equals(component)) {
4617                return generateActivityInfo(mResolveActivity, flags, new PackageUserState(),
4618                        userId);
4619            }
4620        }
4621        return null;
4622    }
4623
4624    @Override
4625    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4626            String resolvedType) {
4627        synchronized (mPackages) {
4628            if (component.equals(mResolveComponentName)) {
4629                // The resolver supports EVERYTHING!
4630                return true;
4631            }
4632            final int callingUid = Binder.getCallingUid();
4633            final int callingUserId = UserHandle.getUserId(callingUid);
4634            PackageParser.Activity a = mActivities.mActivities.get(component);
4635            if (a == null) {
4636                return false;
4637            }
4638            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4639            if (ps == null) {
4640                return false;
4641            }
4642            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4643                return false;
4644            }
4645            for (int i=0; i<a.intents.size(); i++) {
4646                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4647                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4648                    return true;
4649                }
4650            }
4651            return false;
4652        }
4653    }
4654
4655    @Override
4656    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4657        if (!sUserManager.exists(userId)) return null;
4658        final int callingUid = Binder.getCallingUid();
4659        flags = updateFlagsForComponent(flags, userId, component);
4660        enforceCrossUserPermission(callingUid, userId,
4661                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4662        synchronized (mPackages) {
4663            PackageParser.Activity a = mReceivers.mActivities.get(component);
4664            if (DEBUG_PACKAGE_INFO) Log.v(
4665                TAG, "getReceiverInfo " + component + ": " + a);
4666            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4667                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4668                if (ps == null) return null;
4669                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4670                    return null;
4671                }
4672                return generateActivityInfo(a, flags, ps.readUserState(userId), userId);
4673            }
4674        }
4675        return null;
4676    }
4677
4678    @Override
4679    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4680            int flags, int userId) {
4681        if (!sUserManager.exists(userId)) return null;
4682        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4683        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4684            return null;
4685        }
4686
4687        flags = updateFlagsForPackage(flags, userId, null);
4688
4689        final boolean canSeeStaticLibraries =
4690                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4691                        == PERMISSION_GRANTED
4692                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4693                        == PERMISSION_GRANTED
4694                || canRequestPackageInstallsInternal(packageName,
4695                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4696                        false  /* throwIfPermNotDeclared*/)
4697                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4698                        == PERMISSION_GRANTED;
4699
4700        synchronized (mPackages) {
4701            List<SharedLibraryInfo> result = null;
4702
4703            final int libCount = mSharedLibraries.size();
4704            for (int i = 0; i < libCount; i++) {
4705                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4706                if (versionedLib == null) {
4707                    continue;
4708                }
4709
4710                final int versionCount = versionedLib.size();
4711                for (int j = 0; j < versionCount; j++) {
4712                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4713                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4714                        break;
4715                    }
4716                    final long identity = Binder.clearCallingIdentity();
4717                    try {
4718                        PackageInfo packageInfo = getPackageInfoVersioned(
4719                                libInfo.getDeclaringPackage(), flags
4720                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4721                        if (packageInfo == null) {
4722                            continue;
4723                        }
4724                    } finally {
4725                        Binder.restoreCallingIdentity(identity);
4726                    }
4727
4728                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
4729                            libInfo.getVersion(), libInfo.getType(),
4730                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
4731                            flags, userId));
4732
4733                    if (result == null) {
4734                        result = new ArrayList<>();
4735                    }
4736                    result.add(resLibInfo);
4737                }
4738            }
4739
4740            return result != null ? new ParceledListSlice<>(result) : null;
4741        }
4742    }
4743
4744    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
4745            SharedLibraryInfo libInfo, int flags, int userId) {
4746        List<VersionedPackage> versionedPackages = null;
4747        final int packageCount = mSettings.mPackages.size();
4748        for (int i = 0; i < packageCount; i++) {
4749            PackageSetting ps = mSettings.mPackages.valueAt(i);
4750
4751            if (ps == null) {
4752                continue;
4753            }
4754
4755            if (!ps.getUserState().get(userId).isAvailable(flags)) {
4756                continue;
4757            }
4758
4759            final String libName = libInfo.getName();
4760            if (libInfo.isStatic()) {
4761                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
4762                if (libIdx < 0) {
4763                    continue;
4764                }
4765                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) {
4766                    continue;
4767                }
4768                if (versionedPackages == null) {
4769                    versionedPackages = new ArrayList<>();
4770                }
4771                // If the dependent is a static shared lib, use the public package name
4772                String dependentPackageName = ps.name;
4773                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4774                    dependentPackageName = ps.pkg.manifestPackageName;
4775                }
4776                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
4777            } else if (ps.pkg != null) {
4778                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
4779                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
4780                    if (versionedPackages == null) {
4781                        versionedPackages = new ArrayList<>();
4782                    }
4783                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
4784                }
4785            }
4786        }
4787
4788        return versionedPackages;
4789    }
4790
4791    @Override
4792    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
4793        if (!sUserManager.exists(userId)) return null;
4794        final int callingUid = Binder.getCallingUid();
4795        flags = updateFlagsForComponent(flags, userId, component);
4796        enforceCrossUserPermission(callingUid, userId,
4797                false /* requireFullPermission */, false /* checkShell */, "get service info");
4798        synchronized (mPackages) {
4799            PackageParser.Service s = mServices.mServices.get(component);
4800            if (DEBUG_PACKAGE_INFO) Log.v(
4801                TAG, "getServiceInfo " + component + ": " + s);
4802            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
4803                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4804                if (ps == null) return null;
4805                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
4806                    return null;
4807                }
4808                ServiceInfo si = PackageParser.generateServiceInfo(s, flags,
4809                        ps.readUserState(userId), userId);
4810                if (si != null) {
4811                    rebaseEnabledOverlays(si.applicationInfo, userId);
4812                }
4813                return si;
4814            }
4815        }
4816        return null;
4817    }
4818
4819    @Override
4820    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
4821        if (!sUserManager.exists(userId)) return null;
4822        final int callingUid = Binder.getCallingUid();
4823        flags = updateFlagsForComponent(flags, userId, component);
4824        enforceCrossUserPermission(callingUid, userId,
4825                false /* requireFullPermission */, false /* checkShell */, "get provider info");
4826        synchronized (mPackages) {
4827            PackageParser.Provider p = mProviders.mProviders.get(component);
4828            if (DEBUG_PACKAGE_INFO) Log.v(
4829                TAG, "getProviderInfo " + component + ": " + p);
4830            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
4831                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4832                if (ps == null) return null;
4833                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
4834                    return null;
4835                }
4836                ProviderInfo pi = PackageParser.generateProviderInfo(p, flags,
4837                        ps.readUserState(userId), userId);
4838                if (pi != null) {
4839                    rebaseEnabledOverlays(pi.applicationInfo, userId);
4840                }
4841                return pi;
4842            }
4843        }
4844        return null;
4845    }
4846
4847    @Override
4848    public String[] getSystemSharedLibraryNames() {
4849        // allow instant applications
4850        synchronized (mPackages) {
4851            Set<String> libs = null;
4852            final int libCount = mSharedLibraries.size();
4853            for (int i = 0; i < libCount; i++) {
4854                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4855                if (versionedLib == null) {
4856                    continue;
4857                }
4858                final int versionCount = versionedLib.size();
4859                for (int j = 0; j < versionCount; j++) {
4860                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
4861                    if (!libEntry.info.isStatic()) {
4862                        if (libs == null) {
4863                            libs = new ArraySet<>();
4864                        }
4865                        libs.add(libEntry.info.getName());
4866                        break;
4867                    }
4868                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
4869                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
4870                            UserHandle.getUserId(Binder.getCallingUid()),
4871                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
4872                        if (libs == null) {
4873                            libs = new ArraySet<>();
4874                        }
4875                        libs.add(libEntry.info.getName());
4876                        break;
4877                    }
4878                }
4879            }
4880
4881            if (libs != null) {
4882                String[] libsArray = new String[libs.size()];
4883                libs.toArray(libsArray);
4884                return libsArray;
4885            }
4886
4887            return null;
4888        }
4889    }
4890
4891    @Override
4892    public @NonNull String getServicesSystemSharedLibraryPackageName() {
4893        // allow instant applications
4894        synchronized (mPackages) {
4895            return mServicesSystemSharedLibraryPackageName;
4896        }
4897    }
4898
4899    @Override
4900    public @NonNull String getSharedSystemSharedLibraryPackageName() {
4901        // allow instant applications
4902        synchronized (mPackages) {
4903            return mSharedSystemSharedLibraryPackageName;
4904        }
4905    }
4906
4907    private void updateSequenceNumberLP(String packageName, int[] userList) {
4908        for (int i = userList.length - 1; i >= 0; --i) {
4909            final int userId = userList[i];
4910            SparseArray<String> changedPackages = mChangedPackages.get(userId);
4911            if (changedPackages == null) {
4912                changedPackages = new SparseArray<>();
4913                mChangedPackages.put(userId, changedPackages);
4914            }
4915            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
4916            if (sequenceNumbers == null) {
4917                sequenceNumbers = new HashMap<>();
4918                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
4919            }
4920            final Integer sequenceNumber = sequenceNumbers.get(packageName);
4921            if (sequenceNumber != null) {
4922                changedPackages.remove(sequenceNumber);
4923            }
4924            changedPackages.put(mChangedPackagesSequenceNumber, packageName);
4925            sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber);
4926        }
4927        mChangedPackagesSequenceNumber++;
4928    }
4929
4930    @Override
4931    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
4932        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4933            return null;
4934        }
4935        synchronized (mPackages) {
4936            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
4937                return null;
4938            }
4939            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
4940            if (changedPackages == null) {
4941                return null;
4942            }
4943            final List<String> packageNames =
4944                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
4945            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
4946                final String packageName = changedPackages.get(i);
4947                if (packageName != null) {
4948                    packageNames.add(packageName);
4949                }
4950            }
4951            return packageNames.isEmpty()
4952                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
4953        }
4954    }
4955
4956    @Override
4957    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
4958        // allow instant applications
4959        ArrayList<FeatureInfo> res;
4960        synchronized (mAvailableFeatures) {
4961            res = new ArrayList<>(mAvailableFeatures.size() + 1);
4962            res.addAll(mAvailableFeatures.values());
4963        }
4964        final FeatureInfo fi = new FeatureInfo();
4965        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
4966                FeatureInfo.GL_ES_VERSION_UNDEFINED);
4967        res.add(fi);
4968
4969        return new ParceledListSlice<>(res);
4970    }
4971
4972    @Override
4973    public boolean hasSystemFeature(String name, int version) {
4974        // allow instant applications
4975        synchronized (mAvailableFeatures) {
4976            final FeatureInfo feat = mAvailableFeatures.get(name);
4977            if (feat == null) {
4978                return false;
4979            } else {
4980                return feat.version >= version;
4981            }
4982        }
4983    }
4984
4985    @Override
4986    public int checkPermission(String permName, String pkgName, int userId) {
4987        if (!sUserManager.exists(userId)) {
4988            return PackageManager.PERMISSION_DENIED;
4989        }
4990        final int callingUid = Binder.getCallingUid();
4991
4992        synchronized (mPackages) {
4993            final PackageParser.Package p = mPackages.get(pkgName);
4994            if (p != null && p.mExtras != null) {
4995                final PackageSetting ps = (PackageSetting) p.mExtras;
4996                if (filterAppAccessLPr(ps, callingUid, userId)) {
4997                    return PackageManager.PERMISSION_DENIED;
4998                }
4999                final boolean instantApp = ps.getInstantApp(userId);
5000                final PermissionsState permissionsState = ps.getPermissionsState();
5001                if (permissionsState.hasPermission(permName, userId)) {
5002                    if (instantApp) {
5003                        BasePermission bp = mSettings.mPermissions.get(permName);
5004                        if (bp != null && bp.isInstant()) {
5005                            return PackageManager.PERMISSION_GRANTED;
5006                        }
5007                    } else {
5008                        return PackageManager.PERMISSION_GRANTED;
5009                    }
5010                }
5011                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5012                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5013                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5014                    return PackageManager.PERMISSION_GRANTED;
5015                }
5016            }
5017        }
5018
5019        return PackageManager.PERMISSION_DENIED;
5020    }
5021
5022    @Override
5023    public int checkUidPermission(String permName, int uid) {
5024        final int callingUid = Binder.getCallingUid();
5025        final int callingUserId = UserHandle.getUserId(callingUid);
5026        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5027        final boolean isUidInstantApp = getInstantAppPackageName(uid) != null;
5028        final int userId = UserHandle.getUserId(uid);
5029        if (!sUserManager.exists(userId)) {
5030            return PackageManager.PERMISSION_DENIED;
5031        }
5032
5033        synchronized (mPackages) {
5034            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5035            if (obj != null) {
5036                if (obj instanceof SharedUserSetting) {
5037                    if (isCallerInstantApp) {
5038                        return PackageManager.PERMISSION_DENIED;
5039                    }
5040                } else if (obj instanceof PackageSetting) {
5041                    final PackageSetting ps = (PackageSetting) obj;
5042                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5043                        return PackageManager.PERMISSION_DENIED;
5044                    }
5045                }
5046                final SettingBase settingBase = (SettingBase) obj;
5047                final PermissionsState permissionsState = settingBase.getPermissionsState();
5048                if (permissionsState.hasPermission(permName, userId)) {
5049                    if (isUidInstantApp) {
5050                        BasePermission bp = mSettings.mPermissions.get(permName);
5051                        if (bp != null && bp.isInstant()) {
5052                            return PackageManager.PERMISSION_GRANTED;
5053                        }
5054                    } else {
5055                        return PackageManager.PERMISSION_GRANTED;
5056                    }
5057                }
5058                // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION
5059                if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
5060                        .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
5061                    return PackageManager.PERMISSION_GRANTED;
5062                }
5063            } else {
5064                ArraySet<String> perms = mSystemPermissions.get(uid);
5065                if (perms != null) {
5066                    if (perms.contains(permName)) {
5067                        return PackageManager.PERMISSION_GRANTED;
5068                    }
5069                    if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms
5070                            .contains(Manifest.permission.ACCESS_FINE_LOCATION)) {
5071                        return PackageManager.PERMISSION_GRANTED;
5072                    }
5073                }
5074            }
5075        }
5076
5077        return PackageManager.PERMISSION_DENIED;
5078    }
5079
5080    @Override
5081    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5082        if (UserHandle.getCallingUserId() != userId) {
5083            mContext.enforceCallingPermission(
5084                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5085                    "isPermissionRevokedByPolicy for user " + userId);
5086        }
5087
5088        if (checkPermission(permission, packageName, userId)
5089                == PackageManager.PERMISSION_GRANTED) {
5090            return false;
5091        }
5092
5093        final int callingUid = Binder.getCallingUid();
5094        if (getInstantAppPackageName(callingUid) != null) {
5095            if (!isCallerSameApp(packageName, callingUid)) {
5096                return false;
5097            }
5098        } else {
5099            if (isInstantApp(packageName, userId)) {
5100                return false;
5101            }
5102        }
5103
5104        final long identity = Binder.clearCallingIdentity();
5105        try {
5106            final int flags = getPermissionFlags(permission, packageName, userId);
5107            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5108        } finally {
5109            Binder.restoreCallingIdentity(identity);
5110        }
5111    }
5112
5113    @Override
5114    public String getPermissionControllerPackageName() {
5115        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5116            throw new SecurityException("Instant applications don't have access to this method");
5117        }
5118        synchronized (mPackages) {
5119            return mRequiredInstallerPackage;
5120        }
5121    }
5122
5123    /**
5124     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
5125     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
5126     * @param checkShell whether to prevent shell from access if there's a debugging restriction
5127     * @param message the message to log on security exception
5128     */
5129    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
5130            boolean checkShell, String message) {
5131        if (userId < 0) {
5132            throw new IllegalArgumentException("Invalid userId " + userId);
5133        }
5134        if (checkShell) {
5135            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
5136        }
5137        if (userId == UserHandle.getUserId(callingUid)) return;
5138        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5139            if (requireFullPermission) {
5140                mContext.enforceCallingOrSelfPermission(
5141                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5142            } else {
5143                try {
5144                    mContext.enforceCallingOrSelfPermission(
5145                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
5146                } catch (SecurityException se) {
5147                    mContext.enforceCallingOrSelfPermission(
5148                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
5149                }
5150            }
5151        }
5152    }
5153
5154    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
5155        if (callingUid == Process.SHELL_UID) {
5156            if (userHandle >= 0
5157                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
5158                throw new SecurityException("Shell does not have permission to access user "
5159                        + userHandle);
5160            } else if (userHandle < 0) {
5161                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
5162                        + Debug.getCallers(3));
5163            }
5164        }
5165    }
5166
5167    private BasePermission findPermissionTreeLP(String permName) {
5168        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
5169            if (permName.startsWith(bp.name) &&
5170                    permName.length() > bp.name.length() &&
5171                    permName.charAt(bp.name.length()) == '.') {
5172                return bp;
5173            }
5174        }
5175        return null;
5176    }
5177
5178    private BasePermission checkPermissionTreeLP(String permName) {
5179        if (permName != null) {
5180            BasePermission bp = findPermissionTreeLP(permName);
5181            if (bp != null) {
5182                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
5183                    return bp;
5184                }
5185                throw new SecurityException("Calling uid "
5186                        + Binder.getCallingUid()
5187                        + " is not allowed to add to permission tree "
5188                        + bp.name + " owned by uid " + bp.uid);
5189            }
5190        }
5191        throw new SecurityException("No permission tree found for " + permName);
5192    }
5193
5194    static boolean compareStrings(CharSequence s1, CharSequence s2) {
5195        if (s1 == null) {
5196            return s2 == null;
5197        }
5198        if (s2 == null) {
5199            return false;
5200        }
5201        if (s1.getClass() != s2.getClass()) {
5202            return false;
5203        }
5204        return s1.equals(s2);
5205    }
5206
5207    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
5208        if (pi1.icon != pi2.icon) return false;
5209        if (pi1.logo != pi2.logo) return false;
5210        if (pi1.protectionLevel != pi2.protectionLevel) return false;
5211        if (!compareStrings(pi1.name, pi2.name)) return false;
5212        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
5213        // We'll take care of setting this one.
5214        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
5215        // These are not currently stored in settings.
5216        //if (!compareStrings(pi1.group, pi2.group)) return false;
5217        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
5218        //if (pi1.labelRes != pi2.labelRes) return false;
5219        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
5220        return true;
5221    }
5222
5223    int permissionInfoFootprint(PermissionInfo info) {
5224        int size = info.name.length();
5225        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
5226        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
5227        return size;
5228    }
5229
5230    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
5231        int size = 0;
5232        for (BasePermission perm : mSettings.mPermissions.values()) {
5233            if (perm.uid == tree.uid) {
5234                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
5235            }
5236        }
5237        return size;
5238    }
5239
5240    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
5241        // We calculate the max size of permissions defined by this uid and throw
5242        // if that plus the size of 'info' would exceed our stated maximum.
5243        if (tree.uid != Process.SYSTEM_UID) {
5244            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
5245            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
5246                throw new SecurityException("Permission tree size cap exceeded");
5247            }
5248        }
5249    }
5250
5251    boolean addPermissionLocked(PermissionInfo info, boolean async) {
5252        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5253            throw new SecurityException("Instant apps can't add permissions");
5254        }
5255        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
5256            throw new SecurityException("Label must be specified in permission");
5257        }
5258        BasePermission tree = checkPermissionTreeLP(info.name);
5259        BasePermission bp = mSettings.mPermissions.get(info.name);
5260        boolean added = bp == null;
5261        boolean changed = true;
5262        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
5263        if (added) {
5264            enforcePermissionCapLocked(info, tree);
5265            bp = new BasePermission(info.name, tree.sourcePackage,
5266                    BasePermission.TYPE_DYNAMIC);
5267        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
5268            throw new SecurityException(
5269                    "Not allowed to modify non-dynamic permission "
5270                    + info.name);
5271        } else {
5272            if (bp.protectionLevel == fixedLevel
5273                    && bp.perm.owner.equals(tree.perm.owner)
5274                    && bp.uid == tree.uid
5275                    && comparePermissionInfos(bp.perm.info, info)) {
5276                changed = false;
5277            }
5278        }
5279        bp.protectionLevel = fixedLevel;
5280        info = new PermissionInfo(info);
5281        info.protectionLevel = fixedLevel;
5282        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
5283        bp.perm.info.packageName = tree.perm.info.packageName;
5284        bp.uid = tree.uid;
5285        if (added) {
5286            mSettings.mPermissions.put(info.name, bp);
5287        }
5288        if (changed) {
5289            if (!async) {
5290                mSettings.writeLPr();
5291            } else {
5292                scheduleWriteSettingsLocked();
5293            }
5294        }
5295        return added;
5296    }
5297
5298    @Override
5299    public boolean addPermission(PermissionInfo info) {
5300        synchronized (mPackages) {
5301            return addPermissionLocked(info, false);
5302        }
5303    }
5304
5305    @Override
5306    public boolean addPermissionAsync(PermissionInfo info) {
5307        synchronized (mPackages) {
5308            return addPermissionLocked(info, true);
5309        }
5310    }
5311
5312    @Override
5313    public void removePermission(String name) {
5314        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5315            throw new SecurityException("Instant applications don't have access to this method");
5316        }
5317        synchronized (mPackages) {
5318            checkPermissionTreeLP(name);
5319            BasePermission bp = mSettings.mPermissions.get(name);
5320            if (bp != null) {
5321                if (bp.type != BasePermission.TYPE_DYNAMIC) {
5322                    throw new SecurityException(
5323                            "Not allowed to modify non-dynamic permission "
5324                            + name);
5325                }
5326                mSettings.mPermissions.remove(name);
5327                mSettings.writeLPr();
5328            }
5329        }
5330    }
5331
5332    private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(
5333            PackageParser.Package pkg, BasePermission bp) {
5334        int index = pkg.requestedPermissions.indexOf(bp.name);
5335        if (index == -1) {
5336            throw new SecurityException("Package " + pkg.packageName
5337                    + " has not requested permission " + bp.name);
5338        }
5339        if (!bp.isRuntime() && !bp.isDevelopment()) {
5340            throw new SecurityException("Permission " + bp.name
5341                    + " is not a changeable permission type");
5342        }
5343    }
5344
5345    @Override
5346    public void grantRuntimePermission(String packageName, String name, final int userId) {
5347        grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5348    }
5349
5350    private void grantRuntimePermission(String packageName, String name, final int userId,
5351            boolean overridePolicy) {
5352        if (!sUserManager.exists(userId)) {
5353            Log.e(TAG, "No such user:" + userId);
5354            return;
5355        }
5356        final int callingUid = Binder.getCallingUid();
5357
5358        mContext.enforceCallingOrSelfPermission(
5359                android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
5360                "grantRuntimePermission");
5361
5362        enforceCrossUserPermission(callingUid, userId,
5363                true /* requireFullPermission */, true /* checkShell */,
5364                "grantRuntimePermission");
5365
5366        final int uid;
5367        final SettingBase sb;
5368
5369        synchronized (mPackages) {
5370            final PackageParser.Package pkg = mPackages.get(packageName);
5371            if (pkg == null) {
5372                throw new IllegalArgumentException("Unknown package: " + packageName);
5373            }
5374            final BasePermission bp = mSettings.mPermissions.get(name);
5375            if (bp == null) {
5376                throw new IllegalArgumentException("Unknown permission: " + name);
5377            }
5378            sb = (SettingBase) pkg.mExtras;
5379            if (sb == null) {
5380                throw new IllegalArgumentException("Unknown package: " + packageName);
5381            }
5382            if (sb instanceof PackageSetting
5383                    && filterAppAccessLPr((PackageSetting) sb, callingUid, userId)) {
5384                throw new IllegalArgumentException("Unknown package: " + packageName);
5385            }
5386
5387            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5388
5389            // If a permission review is required for legacy apps we represent
5390            // their permissions as always granted runtime ones since we need
5391            // to keep the review required permission flag per user while an
5392            // install permission's state is shared across all users.
5393            if (mPermissionReviewRequired
5394                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5395                    && bp.isRuntime()) {
5396                return;
5397            }
5398
5399            uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
5400
5401            final PermissionsState permissionsState = sb.getPermissionsState();
5402
5403            final int flags = permissionsState.getPermissionFlags(name, userId);
5404            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5405                throw new SecurityException("Cannot grant system fixed permission "
5406                        + name + " for package " + packageName);
5407            }
5408            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5409                throw new SecurityException("Cannot grant policy fixed permission "
5410                        + name + " for package " + packageName);
5411            }
5412
5413            if (bp.isDevelopment()) {
5414                // Development permissions must be handled specially, since they are not
5415                // normal runtime permissions.  For now they apply to all users.
5416                if (permissionsState.grantInstallPermission(bp) !=
5417                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5418                    scheduleWriteSettingsLocked();
5419                }
5420                return;
5421            }
5422
5423            final PackageSetting ps = mSettings.mPackages.get(packageName);
5424            if (ps.getInstantApp(userId) && !bp.isInstant()) {
5425                throw new SecurityException("Cannot grant non-ephemeral permission"
5426                        + name + " for package " + packageName);
5427            }
5428
5429            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
5430                Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
5431                return;
5432            }
5433
5434            final int result = permissionsState.grantRuntimePermission(bp, userId);
5435            switch (result) {
5436                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
5437                    return;
5438                }
5439
5440                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
5441                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5442                    mHandler.post(new Runnable() {
5443                        @Override
5444                        public void run() {
5445                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
5446                        }
5447                    });
5448                }
5449                break;
5450            }
5451
5452            if (bp.isRuntime()) {
5453                logPermissionGranted(mContext, name, packageName);
5454            }
5455
5456            mOnPermissionChangeListeners.onPermissionsChanged(uid);
5457
5458            // Not critical if that is lost - app has to request again.
5459            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5460        }
5461
5462        // Only need to do this if user is initialized. Otherwise it's a new user
5463        // and there are no processes running as the user yet and there's no need
5464        // to make an expensive call to remount processes for the changed permissions.
5465        if (READ_EXTERNAL_STORAGE.equals(name)
5466                || WRITE_EXTERNAL_STORAGE.equals(name)) {
5467            final long token = Binder.clearCallingIdentity();
5468            try {
5469                if (sUserManager.isInitialized(userId)) {
5470                    StorageManagerInternal storageManagerInternal = LocalServices.getService(
5471                            StorageManagerInternal.class);
5472                    storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName);
5473                }
5474            } finally {
5475                Binder.restoreCallingIdentity(token);
5476            }
5477        }
5478    }
5479
5480    @Override
5481    public void revokeRuntimePermission(String packageName, String name, int userId) {
5482        revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */);
5483    }
5484
5485    private void revokeRuntimePermission(String packageName, String name, int userId,
5486            boolean overridePolicy) {
5487        if (!sUserManager.exists(userId)) {
5488            Log.e(TAG, "No such user:" + userId);
5489            return;
5490        }
5491
5492        mContext.enforceCallingOrSelfPermission(
5493                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5494                "revokeRuntimePermission");
5495
5496        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5497                true /* requireFullPermission */, true /* checkShell */,
5498                "revokeRuntimePermission");
5499
5500        final int appId;
5501
5502        synchronized (mPackages) {
5503            final PackageParser.Package pkg = mPackages.get(packageName);
5504            if (pkg == null) {
5505                throw new IllegalArgumentException("Unknown package: " + packageName);
5506            }
5507
5508            final BasePermission bp = mSettings.mPermissions.get(name);
5509            if (bp == null) {
5510                throw new IllegalArgumentException("Unknown permission: " + name);
5511            }
5512
5513            enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
5514
5515            // If a permission review is required for legacy apps we represent
5516            // their permissions as always granted runtime ones since we need
5517            // to keep the review required permission flag per user while an
5518            // install permission's state is shared across all users.
5519            if (mPermissionReviewRequired
5520                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M
5521                    && bp.isRuntime()) {
5522                return;
5523            }
5524
5525            SettingBase sb = (SettingBase) pkg.mExtras;
5526            if (sb == null) {
5527                throw new IllegalArgumentException("Unknown package: " + packageName);
5528            }
5529
5530            final PermissionsState permissionsState = sb.getPermissionsState();
5531
5532            final int flags = permissionsState.getPermissionFlags(name, userId);
5533            if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
5534                throw new SecurityException("Cannot revoke system fixed permission "
5535                        + name + " for package " + packageName);
5536            }
5537            if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) {
5538                throw new SecurityException("Cannot revoke policy fixed permission "
5539                        + name + " for package " + packageName);
5540            }
5541
5542            if (bp.isDevelopment()) {
5543                // Development permissions must be handled specially, since they are not
5544                // normal runtime permissions.  For now they apply to all users.
5545                if (permissionsState.revokeInstallPermission(bp) !=
5546                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
5547                    scheduleWriteSettingsLocked();
5548                }
5549                return;
5550            }
5551
5552            if (permissionsState.revokeRuntimePermission(bp, userId) ==
5553                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
5554                return;
5555            }
5556
5557            if (bp.isRuntime()) {
5558                logPermissionRevoked(mContext, name, packageName);
5559            }
5560
5561            mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid);
5562
5563            // Critical, after this call app should never have the permission.
5564            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
5565
5566            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
5567        }
5568
5569        killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
5570    }
5571
5572    /**
5573     * Get the first event id for the permission.
5574     *
5575     * <p>There are four events for each permission: <ul>
5576     *     <li>Request permission: first id + 0</li>
5577     *     <li>Grant permission: first id + 1</li>
5578     *     <li>Request for permission denied: first id + 2</li>
5579     *     <li>Revoke permission: first id + 3</li>
5580     * </ul></p>
5581     *
5582     * @param name name of the permission
5583     *
5584     * @return The first event id for the permission
5585     */
5586    private static int getBaseEventId(@NonNull String name) {
5587        int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name);
5588
5589        if (eventIdIndex == -1) {
5590            if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE
5591                    || "user".equals(Build.TYPE)) {
5592                Log.i(TAG, "Unknown permission " + name);
5593
5594                return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN;
5595            } else {
5596                // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated.
5597                //
5598                // Also update
5599                // - EventLogger#ALL_DANGEROUS_PERMISSIONS
5600                // - metrics_constants.proto
5601                throw new IllegalStateException("Unknown permission " + name);
5602            }
5603        }
5604
5605        return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4;
5606    }
5607
5608    /**
5609     * Log that a permission was revoked.
5610     *
5611     * @param context Context of the caller
5612     * @param name name of the permission
5613     * @param packageName package permission if for
5614     */
5615    private static void logPermissionRevoked(@NonNull Context context, @NonNull String name,
5616            @NonNull String packageName) {
5617        MetricsLogger.action(context, getBaseEventId(name) + 3, packageName);
5618    }
5619
5620    /**
5621     * Log that a permission request was granted.
5622     *
5623     * @param context Context of the caller
5624     * @param name name of the permission
5625     * @param packageName package permission if for
5626     */
5627    private static void logPermissionGranted(@NonNull Context context, @NonNull String name,
5628            @NonNull String packageName) {
5629        MetricsLogger.action(context, getBaseEventId(name) + 1, packageName);
5630    }
5631
5632    @Override
5633    public void resetRuntimePermissions() {
5634        mContext.enforceCallingOrSelfPermission(
5635                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5636                "revokeRuntimePermission");
5637
5638        int callingUid = Binder.getCallingUid();
5639        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5640            mContext.enforceCallingOrSelfPermission(
5641                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5642                    "resetRuntimePermissions");
5643        }
5644
5645        synchronized (mPackages) {
5646            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
5647            for (int userId : UserManagerService.getInstance().getUserIds()) {
5648                final int packageCount = mPackages.size();
5649                for (int i = 0; i < packageCount; i++) {
5650                    PackageParser.Package pkg = mPackages.valueAt(i);
5651                    if (!(pkg.mExtras instanceof PackageSetting)) {
5652                        continue;
5653                    }
5654                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5655                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5656                }
5657            }
5658        }
5659    }
5660
5661    @Override
5662    public int getPermissionFlags(String name, String packageName, int userId) {
5663        if (!sUserManager.exists(userId)) {
5664            return 0;
5665        }
5666
5667        enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags");
5668
5669        final int callingUid = Binder.getCallingUid();
5670        enforceCrossUserPermission(callingUid, userId,
5671                true /* requireFullPermission */, false /* checkShell */,
5672                "getPermissionFlags");
5673
5674        synchronized (mPackages) {
5675            final PackageParser.Package pkg = mPackages.get(packageName);
5676            if (pkg == null) {
5677                return 0;
5678            }
5679            final BasePermission bp = mSettings.mPermissions.get(name);
5680            if (bp == null) {
5681                return 0;
5682            }
5683            final SettingBase sb = (SettingBase) pkg.mExtras;
5684            if (sb == null) {
5685                return 0;
5686            }
5687            if (sb instanceof PackageSetting
5688                    && filterAppAccessLPr((PackageSetting) sb, callingUid, userId)) {
5689                return 0;
5690            }
5691            PermissionsState permissionsState = sb.getPermissionsState();
5692            return permissionsState.getPermissionFlags(name, userId);
5693        }
5694    }
5695
5696    @Override
5697    public void updatePermissionFlags(String name, String packageName, int flagMask,
5698            int flagValues, int userId) {
5699        if (!sUserManager.exists(userId)) {
5700            return;
5701        }
5702
5703        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags");
5704
5705        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5706                true /* requireFullPermission */, true /* checkShell */,
5707                "updatePermissionFlags");
5708
5709        // Only the system can change these flags and nothing else.
5710        if (getCallingUid() != Process.SYSTEM_UID) {
5711            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5712            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5713            flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5714            flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
5715            flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
5716        }
5717
5718        synchronized (mPackages) {
5719            final PackageParser.Package pkg = mPackages.get(packageName);
5720            if (pkg == null) {
5721                throw new IllegalArgumentException("Unknown package: " + packageName);
5722            }
5723
5724            final BasePermission bp = mSettings.mPermissions.get(name);
5725            if (bp == null) {
5726                throw new IllegalArgumentException("Unknown permission: " + name);
5727            }
5728
5729            SettingBase sb = (SettingBase) pkg.mExtras;
5730            if (sb == null) {
5731                throw new IllegalArgumentException("Unknown package: " + packageName);
5732            }
5733
5734            PermissionsState permissionsState = sb.getPermissionsState();
5735
5736            boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null;
5737
5738            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
5739                // Install and runtime permissions are stored in different places,
5740                // so figure out what permission changed and persist the change.
5741                if (permissionsState.getInstallPermissionState(name) != null) {
5742                    scheduleWriteSettingsLocked();
5743                } else if (permissionsState.getRuntimePermissionState(name, userId) != null
5744                        || hadState) {
5745                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5746                }
5747            }
5748        }
5749    }
5750
5751    /**
5752     * Update the permission flags for all packages and runtime permissions of a user in order
5753     * to allow device or profile owner to remove POLICY_FIXED.
5754     */
5755    @Override
5756    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5757        if (!sUserManager.exists(userId)) {
5758            return;
5759        }
5760
5761        enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps");
5762
5763        enforceCrossUserPermission(Binder.getCallingUid(), userId,
5764                true /* requireFullPermission */, true /* checkShell */,
5765                "updatePermissionFlagsForAllApps");
5766
5767        // Only the system can change system fixed flags.
5768        if (getCallingUid() != Process.SYSTEM_UID) {
5769            flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5770            flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
5771        }
5772
5773        synchronized (mPackages) {
5774            boolean changed = false;
5775            final int packageCount = mPackages.size();
5776            for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) {
5777                final PackageParser.Package pkg = mPackages.valueAt(pkgIndex);
5778                SettingBase sb = (SettingBase) pkg.mExtras;
5779                if (sb == null) {
5780                    continue;
5781                }
5782                PermissionsState permissionsState = sb.getPermissionsState();
5783                changed |= permissionsState.updatePermissionFlagsForAllPermissions(
5784                        userId, flagMask, flagValues);
5785            }
5786            if (changed) {
5787                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5788            }
5789        }
5790    }
5791
5792    private void enforceGrantRevokeRuntimePermissionPermissions(String message) {
5793        if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS)
5794                != PackageManager.PERMISSION_GRANTED
5795            && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS)
5796                != PackageManager.PERMISSION_GRANTED) {
5797            throw new SecurityException(message + " requires "
5798                    + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or "
5799                    + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS);
5800        }
5801    }
5802
5803    @Override
5804    public boolean shouldShowRequestPermissionRationale(String permissionName,
5805            String packageName, int userId) {
5806        if (UserHandle.getCallingUserId() != userId) {
5807            mContext.enforceCallingPermission(
5808                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5809                    "canShowRequestPermissionRationale for user " + userId);
5810        }
5811
5812        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5813        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5814            return false;
5815        }
5816
5817        if (checkPermission(permissionName, packageName, userId)
5818                == PackageManager.PERMISSION_GRANTED) {
5819            return false;
5820        }
5821
5822        final int flags;
5823
5824        final long identity = Binder.clearCallingIdentity();
5825        try {
5826            flags = getPermissionFlags(permissionName,
5827                    packageName, userId);
5828        } finally {
5829            Binder.restoreCallingIdentity(identity);
5830        }
5831
5832        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5833                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5834                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5835
5836        if ((flags & fixedFlags) != 0) {
5837            return false;
5838        }
5839
5840        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5841    }
5842
5843    @Override
5844    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5845        mContext.enforceCallingOrSelfPermission(
5846                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5847                "addOnPermissionsChangeListener");
5848
5849        synchronized (mPackages) {
5850            mOnPermissionChangeListeners.addListenerLocked(listener);
5851        }
5852    }
5853
5854    @Override
5855    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5856        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5857            throw new SecurityException("Instant applications don't have access to this method");
5858        }
5859        synchronized (mPackages) {
5860            mOnPermissionChangeListeners.removeListenerLocked(listener);
5861        }
5862    }
5863
5864    @Override
5865    public boolean isProtectedBroadcast(String actionName) {
5866        // allow instant applications
5867        synchronized (mPackages) {
5868            if (mProtectedBroadcasts.contains(actionName)) {
5869                return true;
5870            } else if (actionName != null) {
5871                // TODO: remove these terrible hacks
5872                if (actionName.startsWith("android.net.netmon.lingerExpired")
5873                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5874                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5875                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5876                    return true;
5877                }
5878            }
5879        }
5880        return false;
5881    }
5882
5883    @Override
5884    public int checkSignatures(String pkg1, String pkg2) {
5885        synchronized (mPackages) {
5886            final PackageParser.Package p1 = mPackages.get(pkg1);
5887            final PackageParser.Package p2 = mPackages.get(pkg2);
5888            if (p1 == null || p1.mExtras == null
5889                    || p2 == null || p2.mExtras == null) {
5890                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5891            }
5892            final int callingUid = Binder.getCallingUid();
5893            final int callingUserId = UserHandle.getUserId(callingUid);
5894            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5895            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5896            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5897                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5898                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5899            }
5900            return compareSignatures(p1.mSignatures, p2.mSignatures);
5901        }
5902    }
5903
5904    @Override
5905    public int checkUidSignatures(int uid1, int uid2) {
5906        final int callingUid = Binder.getCallingUid();
5907        final int callingUserId = UserHandle.getUserId(callingUid);
5908        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5909        // Map to base uids.
5910        uid1 = UserHandle.getAppId(uid1);
5911        uid2 = UserHandle.getAppId(uid2);
5912        // reader
5913        synchronized (mPackages) {
5914            Signature[] s1;
5915            Signature[] s2;
5916            Object obj = mSettings.getUserIdLPr(uid1);
5917            if (obj != null) {
5918                if (obj instanceof SharedUserSetting) {
5919                    if (isCallerInstantApp) {
5920                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5921                    }
5922                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
5923                } else if (obj instanceof PackageSetting) {
5924                    final PackageSetting ps = (PackageSetting) obj;
5925                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5926                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5927                    }
5928                    s1 = ps.signatures.mSignatures;
5929                } else {
5930                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5931                }
5932            } else {
5933                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5934            }
5935            obj = mSettings.getUserIdLPr(uid2);
5936            if (obj != null) {
5937                if (obj instanceof SharedUserSetting) {
5938                    if (isCallerInstantApp) {
5939                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5940                    }
5941                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
5942                } else if (obj instanceof PackageSetting) {
5943                    final PackageSetting ps = (PackageSetting) obj;
5944                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5945                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5946                    }
5947                    s2 = ps.signatures.mSignatures;
5948                } else {
5949                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5950                }
5951            } else {
5952                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5953            }
5954            return compareSignatures(s1, s2);
5955        }
5956    }
5957
5958    /**
5959     * This method should typically only be used when granting or revoking
5960     * permissions, since the app may immediately restart after this call.
5961     * <p>
5962     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5963     * guard your work against the app being relaunched.
5964     */
5965    private void killUid(int appId, int userId, String reason) {
5966        final long identity = Binder.clearCallingIdentity();
5967        try {
5968            IActivityManager am = ActivityManager.getService();
5969            if (am != null) {
5970                try {
5971                    am.killUid(appId, userId, reason);
5972                } catch (RemoteException e) {
5973                    /* ignore - same process */
5974                }
5975            }
5976        } finally {
5977            Binder.restoreCallingIdentity(identity);
5978        }
5979    }
5980
5981    /**
5982     * Compares two sets of signatures. Returns:
5983     * <br />
5984     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
5985     * <br />
5986     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
5987     * <br />
5988     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
5989     * <br />
5990     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
5991     * <br />
5992     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
5993     */
5994    static int compareSignatures(Signature[] s1, Signature[] s2) {
5995        if (s1 == null) {
5996            return s2 == null
5997                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
5998                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
5999        }
6000
6001        if (s2 == null) {
6002            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
6003        }
6004
6005        if (s1.length != s2.length) {
6006            return PackageManager.SIGNATURE_NO_MATCH;
6007        }
6008
6009        // Since both signature sets are of size 1, we can compare without HashSets.
6010        if (s1.length == 1) {
6011            return s1[0].equals(s2[0]) ?
6012                    PackageManager.SIGNATURE_MATCH :
6013                    PackageManager.SIGNATURE_NO_MATCH;
6014        }
6015
6016        ArraySet<Signature> set1 = new ArraySet<Signature>();
6017        for (Signature sig : s1) {
6018            set1.add(sig);
6019        }
6020        ArraySet<Signature> set2 = new ArraySet<Signature>();
6021        for (Signature sig : s2) {
6022            set2.add(sig);
6023        }
6024        // Make sure s2 contains all signatures in s1.
6025        if (set1.equals(set2)) {
6026            return PackageManager.SIGNATURE_MATCH;
6027        }
6028        return PackageManager.SIGNATURE_NO_MATCH;
6029    }
6030
6031    /**
6032     * If the database version for this type of package (internal storage or
6033     * external storage) is less than the version where package signatures
6034     * were updated, return true.
6035     */
6036    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6037        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6038        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6039    }
6040
6041    /**
6042     * Used for backward compatibility to make sure any packages with
6043     * certificate chains get upgraded to the new style. {@code existingSigs}
6044     * will be in the old format (since they were stored on disk from before the
6045     * system upgrade) and {@code scannedSigs} will be in the newer format.
6046     */
6047    private int compareSignaturesCompat(PackageSignatures existingSigs,
6048            PackageParser.Package scannedPkg) {
6049        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
6050            return PackageManager.SIGNATURE_NO_MATCH;
6051        }
6052
6053        ArraySet<Signature> existingSet = new ArraySet<Signature>();
6054        for (Signature sig : existingSigs.mSignatures) {
6055            existingSet.add(sig);
6056        }
6057        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
6058        for (Signature sig : scannedPkg.mSignatures) {
6059            try {
6060                Signature[] chainSignatures = sig.getChainSignatures();
6061                for (Signature chainSig : chainSignatures) {
6062                    scannedCompatSet.add(chainSig);
6063                }
6064            } catch (CertificateEncodingException e) {
6065                scannedCompatSet.add(sig);
6066            }
6067        }
6068        /*
6069         * Make sure the expanded scanned set contains all signatures in the
6070         * existing one.
6071         */
6072        if (scannedCompatSet.equals(existingSet)) {
6073            // Migrate the old signatures to the new scheme.
6074            existingSigs.assignSignatures(scannedPkg.mSignatures);
6075            // The new KeySets will be re-added later in the scanning process.
6076            synchronized (mPackages) {
6077                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
6078            }
6079            return PackageManager.SIGNATURE_MATCH;
6080        }
6081        return PackageManager.SIGNATURE_NO_MATCH;
6082    }
6083
6084    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6085        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
6086        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6087    }
6088
6089    private int compareSignaturesRecover(PackageSignatures existingSigs,
6090            PackageParser.Package scannedPkg) {
6091        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
6092            return PackageManager.SIGNATURE_NO_MATCH;
6093        }
6094
6095        String msg = null;
6096        try {
6097            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
6098                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
6099                        + scannedPkg.packageName);
6100                return PackageManager.SIGNATURE_MATCH;
6101            }
6102        } catch (CertificateException e) {
6103            msg = e.getMessage();
6104        }
6105
6106        logCriticalInfo(Log.INFO,
6107                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
6108        return PackageManager.SIGNATURE_NO_MATCH;
6109    }
6110
6111    @Override
6112    public List<String> getAllPackages() {
6113        final int callingUid = Binder.getCallingUid();
6114        final int callingUserId = UserHandle.getUserId(callingUid);
6115        synchronized (mPackages) {
6116            if (canViewInstantApps(callingUid, callingUserId)) {
6117                return new ArrayList<String>(mPackages.keySet());
6118            }
6119            final String instantAppPkgName = getInstantAppPackageName(callingUid);
6120            final List<String> result = new ArrayList<>();
6121            if (instantAppPkgName != null) {
6122                // caller is an instant application; filter unexposed applications
6123                for (PackageParser.Package pkg : mPackages.values()) {
6124                    if (!pkg.visibleToInstantApps) {
6125                        continue;
6126                    }
6127                    result.add(pkg.packageName);
6128                }
6129            } else {
6130                // caller is a normal application; filter instant applications
6131                for (PackageParser.Package pkg : mPackages.values()) {
6132                    final PackageSetting ps =
6133                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6134                    if (ps != null
6135                            && ps.getInstantApp(callingUserId)
6136                            && !mInstantAppRegistry.isInstantAccessGranted(
6137                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6138                        continue;
6139                    }
6140                    result.add(pkg.packageName);
6141                }
6142            }
6143            return result;
6144        }
6145    }
6146
6147    @Override
6148    public String[] getPackagesForUid(int uid) {
6149        final int callingUid = Binder.getCallingUid();
6150        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6151        final int userId = UserHandle.getUserId(uid);
6152        uid = UserHandle.getAppId(uid);
6153        // reader
6154        synchronized (mPackages) {
6155            Object obj = mSettings.getUserIdLPr(uid);
6156            if (obj instanceof SharedUserSetting) {
6157                if (isCallerInstantApp) {
6158                    return null;
6159                }
6160                final SharedUserSetting sus = (SharedUserSetting) obj;
6161                final int N = sus.packages.size();
6162                String[] res = new String[N];
6163                final Iterator<PackageSetting> it = sus.packages.iterator();
6164                int i = 0;
6165                while (it.hasNext()) {
6166                    PackageSetting ps = it.next();
6167                    if (ps.getInstalled(userId)) {
6168                        res[i++] = ps.name;
6169                    } else {
6170                        res = ArrayUtils.removeElement(String.class, res, res[i]);
6171                    }
6172                }
6173                return res;
6174            } else if (obj instanceof PackageSetting) {
6175                final PackageSetting ps = (PackageSetting) obj;
6176                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6177                    return new String[]{ps.name};
6178                }
6179            }
6180        }
6181        return null;
6182    }
6183
6184    @Override
6185    public String getNameForUid(int uid) {
6186        final int callingUid = Binder.getCallingUid();
6187        if (getInstantAppPackageName(callingUid) != null) {
6188            return null;
6189        }
6190        synchronized (mPackages) {
6191            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6192            if (obj instanceof SharedUserSetting) {
6193                final SharedUserSetting sus = (SharedUserSetting) obj;
6194                return sus.name + ":" + sus.userId;
6195            } else if (obj instanceof PackageSetting) {
6196                final PackageSetting ps = (PackageSetting) obj;
6197                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6198                    return null;
6199                }
6200                return ps.name;
6201            }
6202        }
6203        return null;
6204    }
6205
6206    @Override
6207    public int getUidForSharedUser(String sharedUserName) {
6208        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6209            return -1;
6210        }
6211        if (sharedUserName == null) {
6212            return -1;
6213        }
6214        // reader
6215        synchronized (mPackages) {
6216            SharedUserSetting suid;
6217            try {
6218                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6219                if (suid != null) {
6220                    return suid.userId;
6221                }
6222            } catch (PackageManagerException ignore) {
6223                // can't happen, but, still need to catch it
6224            }
6225            return -1;
6226        }
6227    }
6228
6229    @Override
6230    public int getFlagsForUid(int uid) {
6231        final int callingUid = Binder.getCallingUid();
6232        if (getInstantAppPackageName(callingUid) != null) {
6233            return 0;
6234        }
6235        synchronized (mPackages) {
6236            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6237            if (obj instanceof SharedUserSetting) {
6238                final SharedUserSetting sus = (SharedUserSetting) obj;
6239                return sus.pkgFlags;
6240            } else if (obj instanceof PackageSetting) {
6241                final PackageSetting ps = (PackageSetting) obj;
6242                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6243                    return 0;
6244                }
6245                return ps.pkgFlags;
6246            }
6247        }
6248        return 0;
6249    }
6250
6251    @Override
6252    public int getPrivateFlagsForUid(int uid) {
6253        final int callingUid = Binder.getCallingUid();
6254        if (getInstantAppPackageName(callingUid) != null) {
6255            return 0;
6256        }
6257        synchronized (mPackages) {
6258            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
6259            if (obj instanceof SharedUserSetting) {
6260                final SharedUserSetting sus = (SharedUserSetting) obj;
6261                return sus.pkgPrivateFlags;
6262            } else if (obj instanceof PackageSetting) {
6263                final PackageSetting ps = (PackageSetting) obj;
6264                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6265                    return 0;
6266                }
6267                return ps.pkgPrivateFlags;
6268            }
6269        }
6270        return 0;
6271    }
6272
6273    @Override
6274    public boolean isUidPrivileged(int uid) {
6275        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6276            return false;
6277        }
6278        uid = UserHandle.getAppId(uid);
6279        // reader
6280        synchronized (mPackages) {
6281            Object obj = mSettings.getUserIdLPr(uid);
6282            if (obj instanceof SharedUserSetting) {
6283                final SharedUserSetting sus = (SharedUserSetting) obj;
6284                final Iterator<PackageSetting> it = sus.packages.iterator();
6285                while (it.hasNext()) {
6286                    if (it.next().isPrivileged()) {
6287                        return true;
6288                    }
6289                }
6290            } else if (obj instanceof PackageSetting) {
6291                final PackageSetting ps = (PackageSetting) obj;
6292                return ps.isPrivileged();
6293            }
6294        }
6295        return false;
6296    }
6297
6298    @Override
6299    public String[] getAppOpPermissionPackages(String permissionName) {
6300        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6301            return null;
6302        }
6303        synchronized (mPackages) {
6304            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
6305            if (pkgs == null) {
6306                return null;
6307            }
6308            return pkgs.toArray(new String[pkgs.size()]);
6309        }
6310    }
6311
6312    @Override
6313    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6314            int flags, int userId) {
6315        return resolveIntentInternal(
6316                intent, resolvedType, flags, userId, false /*includeInstantApps*/);
6317    }
6318
6319    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6320            int flags, int userId, boolean resolveForStart) {
6321        try {
6322            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6323
6324            if (!sUserManager.exists(userId)) return null;
6325            final int callingUid = Binder.getCallingUid();
6326            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
6327            enforceCrossUserPermission(callingUid, userId,
6328                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6329
6330            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6331            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6332                    flags, callingUid, userId, resolveForStart);
6333            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6334
6335            final ResolveInfo bestChoice =
6336                    chooseBestActivity(intent, resolvedType, flags, query, userId);
6337            return bestChoice;
6338        } finally {
6339            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6340        }
6341    }
6342
6343    @Override
6344    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6345        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6346            throw new SecurityException(
6347                    "findPersistentPreferredActivity can only be run by the system");
6348        }
6349        if (!sUserManager.exists(userId)) {
6350            return null;
6351        }
6352        final int callingUid = Binder.getCallingUid();
6353        intent = updateIntentForResolve(intent);
6354        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6355        final int flags = updateFlagsForResolve(
6356                0, userId, intent, callingUid, false /*includeInstantApps*/);
6357        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6358                userId);
6359        synchronized (mPackages) {
6360            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6361                    userId);
6362        }
6363    }
6364
6365    @Override
6366    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6367            IntentFilter filter, int match, ComponentName activity) {
6368        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6369            return;
6370        }
6371        final int userId = UserHandle.getCallingUserId();
6372        if (DEBUG_PREFERRED) {
6373            Log.v(TAG, "setLastChosenActivity intent=" + intent
6374                + " resolvedType=" + resolvedType
6375                + " flags=" + flags
6376                + " filter=" + filter
6377                + " match=" + match
6378                + " activity=" + activity);
6379            filter.dump(new PrintStreamPrinter(System.out), "    ");
6380        }
6381        intent.setComponent(null);
6382        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6383                userId);
6384        // Find any earlier preferred or last chosen entries and nuke them
6385        findPreferredActivity(intent, resolvedType,
6386                flags, query, 0, false, true, false, userId);
6387        // Add the new activity as the last chosen for this filter
6388        addPreferredActivityInternal(filter, match, null, activity, false, userId,
6389                "Setting last chosen");
6390    }
6391
6392    @Override
6393    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6394        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6395            return null;
6396        }
6397        final int userId = UserHandle.getCallingUserId();
6398        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6399        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6400                userId);
6401        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6402                false, false, false, userId);
6403    }
6404
6405    /**
6406     * Returns whether or not instant apps have been disabled remotely.
6407     */
6408    private boolean isEphemeralDisabled() {
6409        return mEphemeralAppsDisabled;
6410    }
6411
6412    private boolean isInstantAppAllowed(
6413            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6414            boolean skipPackageCheck) {
6415        if (mInstantAppResolverConnection == null) {
6416            return false;
6417        }
6418        if (mInstantAppInstallerActivity == null) {
6419            return false;
6420        }
6421        if (intent.getComponent() != null) {
6422            return false;
6423        }
6424        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6425            return false;
6426        }
6427        if (!skipPackageCheck && intent.getPackage() != null) {
6428            return false;
6429        }
6430        final boolean isWebUri = hasWebURI(intent);
6431        if (!isWebUri || intent.getData().getHost() == null) {
6432            return false;
6433        }
6434        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6435        // Or if there's already an ephemeral app installed that handles the action
6436        synchronized (mPackages) {
6437            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6438            for (int n = 0; n < count; n++) {
6439                final ResolveInfo info = resolvedActivities.get(n);
6440                final String packageName = info.activityInfo.packageName;
6441                final PackageSetting ps = mSettings.mPackages.get(packageName);
6442                if (ps != null) {
6443                    // only check domain verification status if the app is not a browser
6444                    if (!info.handleAllWebDataURI) {
6445                        // Try to get the status from User settings first
6446                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6447                        final int status = (int) (packedStatus >> 32);
6448                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6449                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6450                            if (DEBUG_EPHEMERAL) {
6451                                Slog.v(TAG, "DENY instant app;"
6452                                    + " pkg: " + packageName + ", status: " + status);
6453                            }
6454                            return false;
6455                        }
6456                    }
6457                    if (ps.getInstantApp(userId)) {
6458                        if (DEBUG_EPHEMERAL) {
6459                            Slog.v(TAG, "DENY instant app installed;"
6460                                    + " pkg: " + packageName);
6461                        }
6462                        return false;
6463                    }
6464                }
6465            }
6466        }
6467        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6468        return true;
6469    }
6470
6471    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6472            Intent origIntent, String resolvedType, String callingPackage,
6473            Bundle verificationBundle, int userId) {
6474        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6475                new InstantAppRequest(responseObj, origIntent, resolvedType,
6476                        callingPackage, userId, verificationBundle));
6477        mHandler.sendMessage(msg);
6478    }
6479
6480    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6481            int flags, List<ResolveInfo> query, int userId) {
6482        if (query != null) {
6483            final int N = query.size();
6484            if (N == 1) {
6485                return query.get(0);
6486            } else if (N > 1) {
6487                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6488                // If there is more than one activity with the same priority,
6489                // then let the user decide between them.
6490                ResolveInfo r0 = query.get(0);
6491                ResolveInfo r1 = query.get(1);
6492                if (DEBUG_INTENT_MATCHING || debug) {
6493                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6494                            + r1.activityInfo.name + "=" + r1.priority);
6495                }
6496                // If the first activity has a higher priority, or a different
6497                // default, then it is always desirable to pick it.
6498                if (r0.priority != r1.priority
6499                        || r0.preferredOrder != r1.preferredOrder
6500                        || r0.isDefault != r1.isDefault) {
6501                    return query.get(0);
6502                }
6503                // If we have saved a preference for a preferred activity for
6504                // this Intent, use that.
6505                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6506                        flags, query, r0.priority, true, false, debug, userId);
6507                if (ri != null) {
6508                    return ri;
6509                }
6510                // If we have an ephemeral app, use it
6511                for (int i = 0; i < N; i++) {
6512                    ri = query.get(i);
6513                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6514                        final String packageName = ri.activityInfo.packageName;
6515                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6516                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6517                        final int status = (int)(packedStatus >> 32);
6518                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6519                            return ri;
6520                        }
6521                    }
6522                }
6523                ri = new ResolveInfo(mResolveInfo);
6524                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6525                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6526                // If all of the options come from the same package, show the application's
6527                // label and icon instead of the generic resolver's.
6528                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6529                // and then throw away the ResolveInfo itself, meaning that the caller loses
6530                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6531                // a fallback for this case; we only set the target package's resources on
6532                // the ResolveInfo, not the ActivityInfo.
6533                final String intentPackage = intent.getPackage();
6534                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6535                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6536                    ri.resolvePackageName = intentPackage;
6537                    if (userNeedsBadging(userId)) {
6538                        ri.noResourceId = true;
6539                    } else {
6540                        ri.icon = appi.icon;
6541                    }
6542                    ri.iconResourceId = appi.icon;
6543                    ri.labelRes = appi.labelRes;
6544                }
6545                ri.activityInfo.applicationInfo = new ApplicationInfo(
6546                        ri.activityInfo.applicationInfo);
6547                if (userId != 0) {
6548                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6549                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6550                }
6551                // Make sure that the resolver is displayable in car mode
6552                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6553                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6554                return ri;
6555            }
6556        }
6557        return null;
6558    }
6559
6560    /**
6561     * Return true if the given list is not empty and all of its contents have
6562     * an activityInfo with the given package name.
6563     */
6564    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6565        if (ArrayUtils.isEmpty(list)) {
6566            return false;
6567        }
6568        for (int i = 0, N = list.size(); i < N; i++) {
6569            final ResolveInfo ri = list.get(i);
6570            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6571            if (ai == null || !packageName.equals(ai.packageName)) {
6572                return false;
6573            }
6574        }
6575        return true;
6576    }
6577
6578    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6579            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6580        final int N = query.size();
6581        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6582                .get(userId);
6583        // Get the list of persistent preferred activities that handle the intent
6584        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6585        List<PersistentPreferredActivity> pprefs = ppir != null
6586                ? ppir.queryIntent(intent, resolvedType,
6587                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6588                        userId)
6589                : null;
6590        if (pprefs != null && pprefs.size() > 0) {
6591            final int M = pprefs.size();
6592            for (int i=0; i<M; i++) {
6593                final PersistentPreferredActivity ppa = pprefs.get(i);
6594                if (DEBUG_PREFERRED || debug) {
6595                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6596                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6597                            + "\n  component=" + ppa.mComponent);
6598                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6599                }
6600                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6601                        flags | MATCH_DISABLED_COMPONENTS, userId);
6602                if (DEBUG_PREFERRED || debug) {
6603                    Slog.v(TAG, "Found persistent preferred activity:");
6604                    if (ai != null) {
6605                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6606                    } else {
6607                        Slog.v(TAG, "  null");
6608                    }
6609                }
6610                if (ai == null) {
6611                    // This previously registered persistent preferred activity
6612                    // component is no longer known. Ignore it and do NOT remove it.
6613                    continue;
6614                }
6615                for (int j=0; j<N; j++) {
6616                    final ResolveInfo ri = query.get(j);
6617                    if (!ri.activityInfo.applicationInfo.packageName
6618                            .equals(ai.applicationInfo.packageName)) {
6619                        continue;
6620                    }
6621                    if (!ri.activityInfo.name.equals(ai.name)) {
6622                        continue;
6623                    }
6624                    //  Found a persistent preference that can handle the intent.
6625                    if (DEBUG_PREFERRED || debug) {
6626                        Slog.v(TAG, "Returning persistent preferred activity: " +
6627                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6628                    }
6629                    return ri;
6630                }
6631            }
6632        }
6633        return null;
6634    }
6635
6636    // TODO: handle preferred activities missing while user has amnesia
6637    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6638            List<ResolveInfo> query, int priority, boolean always,
6639            boolean removeMatches, boolean debug, int userId) {
6640        if (!sUserManager.exists(userId)) return null;
6641        final int callingUid = Binder.getCallingUid();
6642        flags = updateFlagsForResolve(
6643                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6644        intent = updateIntentForResolve(intent);
6645        // writer
6646        synchronized (mPackages) {
6647            // Try to find a matching persistent preferred activity.
6648            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6649                    debug, userId);
6650
6651            // If a persistent preferred activity matched, use it.
6652            if (pri != null) {
6653                return pri;
6654            }
6655
6656            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6657            // Get the list of preferred activities that handle the intent
6658            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6659            List<PreferredActivity> prefs = pir != null
6660                    ? pir.queryIntent(intent, resolvedType,
6661                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6662                            userId)
6663                    : null;
6664            if (prefs != null && prefs.size() > 0) {
6665                boolean changed = false;
6666                try {
6667                    // First figure out how good the original match set is.
6668                    // We will only allow preferred activities that came
6669                    // from the same match quality.
6670                    int match = 0;
6671
6672                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6673
6674                    final int N = query.size();
6675                    for (int j=0; j<N; j++) {
6676                        final ResolveInfo ri = query.get(j);
6677                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6678                                + ": 0x" + Integer.toHexString(match));
6679                        if (ri.match > match) {
6680                            match = ri.match;
6681                        }
6682                    }
6683
6684                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6685                            + Integer.toHexString(match));
6686
6687                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6688                    final int M = prefs.size();
6689                    for (int i=0; i<M; i++) {
6690                        final PreferredActivity pa = prefs.get(i);
6691                        if (DEBUG_PREFERRED || debug) {
6692                            Slog.v(TAG, "Checking PreferredActivity ds="
6693                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6694                                    + "\n  component=" + pa.mPref.mComponent);
6695                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6696                        }
6697                        if (pa.mPref.mMatch != match) {
6698                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6699                                    + Integer.toHexString(pa.mPref.mMatch));
6700                            continue;
6701                        }
6702                        // If it's not an "always" type preferred activity and that's what we're
6703                        // looking for, skip it.
6704                        if (always && !pa.mPref.mAlways) {
6705                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6706                            continue;
6707                        }
6708                        final ActivityInfo ai = getActivityInfo(
6709                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6710                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6711                                userId);
6712                        if (DEBUG_PREFERRED || debug) {
6713                            Slog.v(TAG, "Found preferred activity:");
6714                            if (ai != null) {
6715                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6716                            } else {
6717                                Slog.v(TAG, "  null");
6718                            }
6719                        }
6720                        if (ai == null) {
6721                            // This previously registered preferred activity
6722                            // component is no longer known.  Most likely an update
6723                            // to the app was installed and in the new version this
6724                            // component no longer exists.  Clean it up by removing
6725                            // it from the preferred activities list, and skip it.
6726                            Slog.w(TAG, "Removing dangling preferred activity: "
6727                                    + pa.mPref.mComponent);
6728                            pir.removeFilter(pa);
6729                            changed = true;
6730                            continue;
6731                        }
6732                        for (int j=0; j<N; j++) {
6733                            final ResolveInfo ri = query.get(j);
6734                            if (!ri.activityInfo.applicationInfo.packageName
6735                                    .equals(ai.applicationInfo.packageName)) {
6736                                continue;
6737                            }
6738                            if (!ri.activityInfo.name.equals(ai.name)) {
6739                                continue;
6740                            }
6741
6742                            if (removeMatches) {
6743                                pir.removeFilter(pa);
6744                                changed = true;
6745                                if (DEBUG_PREFERRED) {
6746                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6747                                }
6748                                break;
6749                            }
6750
6751                            // Okay we found a previously set preferred or last chosen app.
6752                            // If the result set is different from when this
6753                            // was created, we need to clear it and re-ask the
6754                            // user their preference, if we're looking for an "always" type entry.
6755                            if (always && !pa.mPref.sameSet(query)) {
6756                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
6757                                        + intent + " type " + resolvedType);
6758                                if (DEBUG_PREFERRED) {
6759                                    Slog.v(TAG, "Removing preferred activity since set changed "
6760                                            + pa.mPref.mComponent);
6761                                }
6762                                pir.removeFilter(pa);
6763                                // Re-add the filter as a "last chosen" entry (!always)
6764                                PreferredActivity lastChosen = new PreferredActivity(
6765                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6766                                pir.addFilter(lastChosen);
6767                                changed = true;
6768                                return null;
6769                            }
6770
6771                            // Yay! Either the set matched or we're looking for the last chosen
6772                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6773                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6774                            return ri;
6775                        }
6776                    }
6777                } finally {
6778                    if (changed) {
6779                        if (DEBUG_PREFERRED) {
6780                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6781                        }
6782                        scheduleWritePackageRestrictionsLocked(userId);
6783                    }
6784                }
6785            }
6786        }
6787        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6788        return null;
6789    }
6790
6791    /*
6792     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6793     */
6794    @Override
6795    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6796            int targetUserId) {
6797        mContext.enforceCallingOrSelfPermission(
6798                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6799        List<CrossProfileIntentFilter> matches =
6800                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6801        if (matches != null) {
6802            int size = matches.size();
6803            for (int i = 0; i < size; i++) {
6804                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6805            }
6806        }
6807        if (hasWebURI(intent)) {
6808            // cross-profile app linking works only towards the parent.
6809            final int callingUid = Binder.getCallingUid();
6810            final UserInfo parent = getProfileParent(sourceUserId);
6811            synchronized(mPackages) {
6812                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6813                        false /*includeInstantApps*/);
6814                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6815                        intent, resolvedType, flags, sourceUserId, parent.id);
6816                return xpDomainInfo != null;
6817            }
6818        }
6819        return false;
6820    }
6821
6822    private UserInfo getProfileParent(int userId) {
6823        final long identity = Binder.clearCallingIdentity();
6824        try {
6825            return sUserManager.getProfileParent(userId);
6826        } finally {
6827            Binder.restoreCallingIdentity(identity);
6828        }
6829    }
6830
6831    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6832            String resolvedType, int userId) {
6833        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6834        if (resolver != null) {
6835            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6836        }
6837        return null;
6838    }
6839
6840    @Override
6841    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6842            String resolvedType, int flags, int userId) {
6843        try {
6844            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6845
6846            return new ParceledListSlice<>(
6847                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6848        } finally {
6849            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6850        }
6851    }
6852
6853    /**
6854     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6855     * instant, returns {@code null}.
6856     */
6857    private String getInstantAppPackageName(int callingUid) {
6858        synchronized (mPackages) {
6859            // If the caller is an isolated app use the owner's uid for the lookup.
6860            if (Process.isIsolated(callingUid)) {
6861                callingUid = mIsolatedOwners.get(callingUid);
6862            }
6863            final int appId = UserHandle.getAppId(callingUid);
6864            final Object obj = mSettings.getUserIdLPr(appId);
6865            if (obj instanceof PackageSetting) {
6866                final PackageSetting ps = (PackageSetting) obj;
6867                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6868                return isInstantApp ? ps.pkg.packageName : null;
6869            }
6870        }
6871        return null;
6872    }
6873
6874    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6875            String resolvedType, int flags, int userId) {
6876        return queryIntentActivitiesInternal(
6877                intent, resolvedType, flags, Binder.getCallingUid(), userId, false);
6878    }
6879
6880    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6881            String resolvedType, int flags, int filterCallingUid, int userId,
6882            boolean resolveForStart) {
6883        if (!sUserManager.exists(userId)) return Collections.emptyList();
6884        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6885        enforceCrossUserPermission(Binder.getCallingUid(), userId,
6886                false /* requireFullPermission */, false /* checkShell */,
6887                "query intent activities");
6888        final String pkgName = intent.getPackage();
6889        ComponentName comp = intent.getComponent();
6890        if (comp == null) {
6891            if (intent.getSelector() != null) {
6892                intent = intent.getSelector();
6893                comp = intent.getComponent();
6894            }
6895        }
6896
6897        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6898                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6899        if (comp != null) {
6900            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6901            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6902            if (ai != null) {
6903                // When specifying an explicit component, we prevent the activity from being
6904                // used when either 1) the calling package is normal and the activity is within
6905                // an ephemeral application or 2) the calling package is ephemeral and the
6906                // activity is not visible to ephemeral applications.
6907                final boolean matchInstantApp =
6908                        (flags & PackageManager.MATCH_INSTANT) != 0;
6909                final boolean matchVisibleToInstantAppOnly =
6910                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6911                final boolean matchExplicitlyVisibleOnly =
6912                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6913                final boolean isCallerInstantApp =
6914                        instantAppPkgName != null;
6915                final boolean isTargetSameInstantApp =
6916                        comp.getPackageName().equals(instantAppPkgName);
6917                final boolean isTargetInstantApp =
6918                        (ai.applicationInfo.privateFlags
6919                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6920                final boolean isTargetVisibleToInstantApp =
6921                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6922                final boolean isTargetExplicitlyVisibleToInstantApp =
6923                        isTargetVisibleToInstantApp
6924                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6925                final boolean isTargetHiddenFromInstantApp =
6926                        !isTargetVisibleToInstantApp
6927                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6928                final boolean blockResolution =
6929                        !isTargetSameInstantApp
6930                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6931                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6932                                        && isTargetHiddenFromInstantApp));
6933                if (!blockResolution) {
6934                    final ResolveInfo ri = new ResolveInfo();
6935                    ri.activityInfo = ai;
6936                    list.add(ri);
6937                }
6938            }
6939            return applyPostResolutionFilter(list, instantAppPkgName);
6940        }
6941
6942        // reader
6943        boolean sortResult = false;
6944        boolean addEphemeral = false;
6945        List<ResolveInfo> result;
6946        final boolean ephemeralDisabled = isEphemeralDisabled();
6947        synchronized (mPackages) {
6948            if (pkgName == null) {
6949                List<CrossProfileIntentFilter> matchingFilters =
6950                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6951                // Check for results that need to skip the current profile.
6952                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6953                        resolvedType, flags, userId);
6954                if (xpResolveInfo != null) {
6955                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6956                    xpResult.add(xpResolveInfo);
6957                    return applyPostResolutionFilter(
6958                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName);
6959                }
6960
6961                // Check for results in the current profile.
6962                result = filterIfNotSystemUser(mActivities.queryIntent(
6963                        intent, resolvedType, flags, userId), userId);
6964                addEphemeral = !ephemeralDisabled
6965                        && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/);
6966                // Check for cross profile results.
6967                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6968                xpResolveInfo = queryCrossProfileIntents(
6969                        matchingFilters, intent, resolvedType, flags, userId,
6970                        hasNonNegativePriorityResult);
6971                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6972                    boolean isVisibleToUser = filterIfNotSystemUser(
6973                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6974                    if (isVisibleToUser) {
6975                        result.add(xpResolveInfo);
6976                        sortResult = true;
6977                    }
6978                }
6979                if (hasWebURI(intent)) {
6980                    CrossProfileDomainInfo xpDomainInfo = null;
6981                    final UserInfo parent = getProfileParent(userId);
6982                    if (parent != null) {
6983                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6984                                flags, userId, parent.id);
6985                    }
6986                    if (xpDomainInfo != null) {
6987                        if (xpResolveInfo != null) {
6988                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6989                            // in the result.
6990                            result.remove(xpResolveInfo);
6991                        }
6992                        if (result.size() == 0 && !addEphemeral) {
6993                            // No result in current profile, but found candidate in parent user.
6994                            // And we are not going to add emphemeral app, so we can return the
6995                            // result straight away.
6996                            result.add(xpDomainInfo.resolveInfo);
6997                            return applyPostResolutionFilter(result, instantAppPkgName);
6998                        }
6999                    } else if (result.size() <= 1 && !addEphemeral) {
7000                        // No result in parent user and <= 1 result in current profile, and we
7001                        // are not going to add emphemeral app, so we can return the result without
7002                        // further processing.
7003                        return applyPostResolutionFilter(result, instantAppPkgName);
7004                    }
7005                    // We have more than one candidate (combining results from current and parent
7006                    // profile), so we need filtering and sorting.
7007                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
7008                            intent, flags, result, xpDomainInfo, userId);
7009                    sortResult = true;
7010                }
7011            } else {
7012                final PackageParser.Package pkg = mPackages.get(pkgName);
7013                result = null;
7014                if (pkg != null) {
7015                    result = filterIfNotSystemUser(
7016                            mActivities.queryIntentForPackage(
7017                                    intent, resolvedType, flags, pkg.activities, userId),
7018                            userId);
7019                }
7020                if (result == null || result.size() == 0) {
7021                    // the caller wants to resolve for a particular package; however, there
7022                    // were no installed results, so, try to find an ephemeral result
7023                    addEphemeral = !ephemeralDisabled
7024                            && isInstantAppAllowed(
7025                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
7026                    if (result == null) {
7027                        result = new ArrayList<>();
7028                    }
7029                }
7030            }
7031        }
7032        if (addEphemeral) {
7033            result = maybeAddInstantAppInstaller(result, intent, resolvedType, flags, userId);
7034        }
7035        if (sortResult) {
7036            Collections.sort(result, mResolvePrioritySorter);
7037        }
7038        return applyPostResolutionFilter(result, instantAppPkgName);
7039    }
7040
7041    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7042            String resolvedType, int flags, int userId) {
7043        // first, check to see if we've got an instant app already installed
7044        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7045        ResolveInfo localInstantApp = null;
7046        boolean blockResolution = false;
7047        if (!alreadyResolvedLocally) {
7048            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
7049                    flags
7050                        | PackageManager.GET_RESOLVED_FILTER
7051                        | PackageManager.MATCH_INSTANT
7052                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7053                    userId);
7054            for (int i = instantApps.size() - 1; i >= 0; --i) {
7055                final ResolveInfo info = instantApps.get(i);
7056                final String packageName = info.activityInfo.packageName;
7057                final PackageSetting ps = mSettings.mPackages.get(packageName);
7058                if (ps.getInstantApp(userId)) {
7059                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7060                    final int status = (int)(packedStatus >> 32);
7061                    final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7062                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7063                        // there's a local instant application installed, but, the user has
7064                        // chosen to never use it; skip resolution and don't acknowledge
7065                        // an instant application is even available
7066                        if (DEBUG_EPHEMERAL) {
7067                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7068                        }
7069                        blockResolution = true;
7070                        break;
7071                    } else {
7072                        // we have a locally installed instant application; skip resolution
7073                        // but acknowledge there's an instant application available
7074                        if (DEBUG_EPHEMERAL) {
7075                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7076                        }
7077                        localInstantApp = info;
7078                        break;
7079                    }
7080                }
7081            }
7082        }
7083        // no app installed, let's see if one's available
7084        AuxiliaryResolveInfo auxiliaryResponse = null;
7085        if (!blockResolution) {
7086            if (localInstantApp == null) {
7087                // we don't have an instant app locally, resolve externally
7088                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7089                final InstantAppRequest requestObject = new InstantAppRequest(
7090                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
7091                        null /*callingPackage*/, userId, null /*verificationBundle*/);
7092                auxiliaryResponse =
7093                        InstantAppResolver.doInstantAppResolutionPhaseOne(
7094                                mContext, mInstantAppResolverConnection, requestObject);
7095                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7096            } else {
7097                // we have an instant application locally, but, we can't admit that since
7098                // callers shouldn't be able to determine prior browsing. create a dummy
7099                // auxiliary response so the downstream code behaves as if there's an
7100                // instant application available externally. when it comes time to start
7101                // the instant application, we'll do the right thing.
7102                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7103                auxiliaryResponse = new AuxiliaryResolveInfo(
7104                        ai.packageName, null /*splitName*/, ai.versionCode, null /*failureIntent*/);
7105            }
7106        }
7107        if (auxiliaryResponse != null) {
7108            if (DEBUG_EPHEMERAL) {
7109                Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7110            }
7111            final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7112            final PackageSetting ps =
7113                    mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7114            if (ps != null) {
7115                ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7116                        mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7117                ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token;
7118                ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7119                // make sure this resolver is the default
7120                ephemeralInstaller.isDefault = true;
7121                ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7122                        | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7123                // add a non-generic filter
7124                ephemeralInstaller.filter = new IntentFilter(intent.getAction());
7125                ephemeralInstaller.filter.addDataPath(
7126                        intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7127                ephemeralInstaller.isInstantAppAvailable = true;
7128                result.add(ephemeralInstaller);
7129            }
7130        }
7131        return result;
7132    }
7133
7134    private static class CrossProfileDomainInfo {
7135        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7136        ResolveInfo resolveInfo;
7137        /* Best domain verification status of the activities found in the other profile */
7138        int bestDomainVerificationStatus;
7139    }
7140
7141    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7142            String resolvedType, int flags, int sourceUserId, int parentUserId) {
7143        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7144                sourceUserId)) {
7145            return null;
7146        }
7147        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7148                resolvedType, flags, parentUserId);
7149
7150        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7151            return null;
7152        }
7153        CrossProfileDomainInfo result = null;
7154        int size = resultTargetUser.size();
7155        for (int i = 0; i < size; i++) {
7156            ResolveInfo riTargetUser = resultTargetUser.get(i);
7157            // Intent filter verification is only for filters that specify a host. So don't return
7158            // those that handle all web uris.
7159            if (riTargetUser.handleAllWebDataURI) {
7160                continue;
7161            }
7162            String packageName = riTargetUser.activityInfo.packageName;
7163            PackageSetting ps = mSettings.mPackages.get(packageName);
7164            if (ps == null) {
7165                continue;
7166            }
7167            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7168            int status = (int)(verificationState >> 32);
7169            if (result == null) {
7170                result = new CrossProfileDomainInfo();
7171                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7172                        sourceUserId, parentUserId);
7173                result.bestDomainVerificationStatus = status;
7174            } else {
7175                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7176                        result.bestDomainVerificationStatus);
7177            }
7178        }
7179        // Don't consider matches with status NEVER across profiles.
7180        if (result != null && result.bestDomainVerificationStatus
7181                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7182            return null;
7183        }
7184        return result;
7185    }
7186
7187    /**
7188     * Verification statuses are ordered from the worse to the best, except for
7189     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7190     */
7191    private int bestDomainVerificationStatus(int status1, int status2) {
7192        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7193            return status2;
7194        }
7195        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7196            return status1;
7197        }
7198        return (int) MathUtils.max(status1, status2);
7199    }
7200
7201    private boolean isUserEnabled(int userId) {
7202        long callingId = Binder.clearCallingIdentity();
7203        try {
7204            UserInfo userInfo = sUserManager.getUserInfo(userId);
7205            return userInfo != null && userInfo.isEnabled();
7206        } finally {
7207            Binder.restoreCallingIdentity(callingId);
7208        }
7209    }
7210
7211    /**
7212     * Filter out activities with systemUserOnly flag set, when current user is not System.
7213     *
7214     * @return filtered list
7215     */
7216    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7217        if (userId == UserHandle.USER_SYSTEM) {
7218            return resolveInfos;
7219        }
7220        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7221            ResolveInfo info = resolveInfos.get(i);
7222            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7223                resolveInfos.remove(i);
7224            }
7225        }
7226        return resolveInfos;
7227    }
7228
7229    /**
7230     * Filters out ephemeral activities.
7231     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7232     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7233     *
7234     * @param resolveInfos The pre-filtered list of resolved activities
7235     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7236     *          is performed.
7237     * @return A filtered list of resolved activities.
7238     */
7239    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7240            String ephemeralPkgName) {
7241        // TODO: When adding on-demand split support for non-instant apps, remove this check
7242        // and always apply post filtering
7243        if (ephemeralPkgName == null) {
7244            return resolveInfos;
7245        }
7246        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7247            final ResolveInfo info = resolveInfos.get(i);
7248            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7249            // allow activities that are defined in the provided package
7250            if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) {
7251                if (info.activityInfo.splitName != null
7252                        && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7253                                info.activityInfo.splitName)) {
7254                    // requested activity is defined in a split that hasn't been installed yet.
7255                    // add the installer to the resolve list
7256                    if (DEBUG_EPHEMERAL) {
7257                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7258                    }
7259                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7260                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7261                            info.activityInfo.packageName, info.activityInfo.splitName,
7262                            info.activityInfo.applicationInfo.versionCode, null /*failureIntent*/);
7263                    // make sure this resolver is the default
7264                    installerInfo.isDefault = true;
7265                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7266                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7267                    // add a non-generic filter
7268                    installerInfo.filter = new IntentFilter();
7269                    // load resources from the correct package
7270                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7271                    resolveInfos.set(i, installerInfo);
7272                }
7273                continue;
7274            }
7275            // allow activities that have been explicitly exposed to ephemeral apps
7276            if (!isEphemeralApp
7277                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7278                continue;
7279            }
7280            resolveInfos.remove(i);
7281        }
7282        return resolveInfos;
7283    }
7284
7285    /**
7286     * @param resolveInfos list of resolve infos in descending priority order
7287     * @return if the list contains a resolve info with non-negative priority
7288     */
7289    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7290        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7291    }
7292
7293    private static boolean hasWebURI(Intent intent) {
7294        if (intent.getData() == null) {
7295            return false;
7296        }
7297        final String scheme = intent.getScheme();
7298        if (TextUtils.isEmpty(scheme)) {
7299            return false;
7300        }
7301        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
7302    }
7303
7304    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7305            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7306            int userId) {
7307        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7308
7309        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7310            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7311                    candidates.size());
7312        }
7313
7314        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7315        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7316        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7317        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7318        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7319        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7320
7321        synchronized (mPackages) {
7322            final int count = candidates.size();
7323            // First, try to use linked apps. Partition the candidates into four lists:
7324            // one for the final results, one for the "do not use ever", one for "undefined status"
7325            // and finally one for "browser app type".
7326            for (int n=0; n<count; n++) {
7327                ResolveInfo info = candidates.get(n);
7328                String packageName = info.activityInfo.packageName;
7329                PackageSetting ps = mSettings.mPackages.get(packageName);
7330                if (ps != null) {
7331                    // Add to the special match all list (Browser use case)
7332                    if (info.handleAllWebDataURI) {
7333                        matchAllList.add(info);
7334                        continue;
7335                    }
7336                    // Try to get the status from User settings first
7337                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7338                    int status = (int)(packedStatus >> 32);
7339                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7340                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7341                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7342                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7343                                    + " : linkgen=" + linkGeneration);
7344                        }
7345                        // Use link-enabled generation as preferredOrder, i.e.
7346                        // prefer newly-enabled over earlier-enabled.
7347                        info.preferredOrder = linkGeneration;
7348                        alwaysList.add(info);
7349                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7350                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7351                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7352                        }
7353                        neverList.add(info);
7354                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7355                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7356                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7357                        }
7358                        alwaysAskList.add(info);
7359                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7360                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7361                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7362                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7363                        }
7364                        undefinedList.add(info);
7365                    }
7366                }
7367            }
7368
7369            // We'll want to include browser possibilities in a few cases
7370            boolean includeBrowser = false;
7371
7372            // First try to add the "always" resolution(s) for the current user, if any
7373            if (alwaysList.size() > 0) {
7374                result.addAll(alwaysList);
7375            } else {
7376                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7377                result.addAll(undefinedList);
7378                // Maybe add one for the other profile.
7379                if (xpDomainInfo != null && (
7380                        xpDomainInfo.bestDomainVerificationStatus
7381                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7382                    result.add(xpDomainInfo.resolveInfo);
7383                }
7384                includeBrowser = true;
7385            }
7386
7387            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7388            // If there were 'always' entries their preferred order has been set, so we also
7389            // back that off to make the alternatives equivalent
7390            if (alwaysAskList.size() > 0) {
7391                for (ResolveInfo i : result) {
7392                    i.preferredOrder = 0;
7393                }
7394                result.addAll(alwaysAskList);
7395                includeBrowser = true;
7396            }
7397
7398            if (includeBrowser) {
7399                // Also add browsers (all of them or only the default one)
7400                if (DEBUG_DOMAIN_VERIFICATION) {
7401                    Slog.v(TAG, "   ...including browsers in candidate set");
7402                }
7403                if ((matchFlags & MATCH_ALL) != 0) {
7404                    result.addAll(matchAllList);
7405                } else {
7406                    // Browser/generic handling case.  If there's a default browser, go straight
7407                    // to that (but only if there is no other higher-priority match).
7408                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7409                    int maxMatchPrio = 0;
7410                    ResolveInfo defaultBrowserMatch = null;
7411                    final int numCandidates = matchAllList.size();
7412                    for (int n = 0; n < numCandidates; n++) {
7413                        ResolveInfo info = matchAllList.get(n);
7414                        // track the highest overall match priority...
7415                        if (info.priority > maxMatchPrio) {
7416                            maxMatchPrio = info.priority;
7417                        }
7418                        // ...and the highest-priority default browser match
7419                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7420                            if (defaultBrowserMatch == null
7421                                    || (defaultBrowserMatch.priority < info.priority)) {
7422                                if (debug) {
7423                                    Slog.v(TAG, "Considering default browser match " + info);
7424                                }
7425                                defaultBrowserMatch = info;
7426                            }
7427                        }
7428                    }
7429                    if (defaultBrowserMatch != null
7430                            && defaultBrowserMatch.priority >= maxMatchPrio
7431                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7432                    {
7433                        if (debug) {
7434                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7435                        }
7436                        result.add(defaultBrowserMatch);
7437                    } else {
7438                        result.addAll(matchAllList);
7439                    }
7440                }
7441
7442                // If there is nothing selected, add all candidates and remove the ones that the user
7443                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7444                if (result.size() == 0) {
7445                    result.addAll(candidates);
7446                    result.removeAll(neverList);
7447                }
7448            }
7449        }
7450        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7451            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7452                    result.size());
7453            for (ResolveInfo info : result) {
7454                Slog.v(TAG, "  + " + info.activityInfo);
7455            }
7456        }
7457        return result;
7458    }
7459
7460    // Returns a packed value as a long:
7461    //
7462    // high 'int'-sized word: link status: undefined/ask/never/always.
7463    // low 'int'-sized word: relative priority among 'always' results.
7464    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7465        long result = ps.getDomainVerificationStatusForUser(userId);
7466        // if none available, get the master status
7467        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7468            if (ps.getIntentFilterVerificationInfo() != null) {
7469                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7470            }
7471        }
7472        return result;
7473    }
7474
7475    private ResolveInfo querySkipCurrentProfileIntents(
7476            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7477            int flags, int sourceUserId) {
7478        if (matchingFilters != null) {
7479            int size = matchingFilters.size();
7480            for (int i = 0; i < size; i ++) {
7481                CrossProfileIntentFilter filter = matchingFilters.get(i);
7482                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7483                    // Checking if there are activities in the target user that can handle the
7484                    // intent.
7485                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7486                            resolvedType, flags, sourceUserId);
7487                    if (resolveInfo != null) {
7488                        return resolveInfo;
7489                    }
7490                }
7491            }
7492        }
7493        return null;
7494    }
7495
7496    // Return matching ResolveInfo in target user if any.
7497    private ResolveInfo queryCrossProfileIntents(
7498            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7499            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7500        if (matchingFilters != null) {
7501            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7502            // match the same intent. For performance reasons, it is better not to
7503            // run queryIntent twice for the same userId
7504            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7505            int size = matchingFilters.size();
7506            for (int i = 0; i < size; i++) {
7507                CrossProfileIntentFilter filter = matchingFilters.get(i);
7508                int targetUserId = filter.getTargetUserId();
7509                boolean skipCurrentProfile =
7510                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7511                boolean skipCurrentProfileIfNoMatchFound =
7512                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7513                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7514                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7515                    // Checking if there are activities in the target user that can handle the
7516                    // intent.
7517                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7518                            resolvedType, flags, sourceUserId);
7519                    if (resolveInfo != null) return resolveInfo;
7520                    alreadyTriedUserIds.put(targetUserId, true);
7521                }
7522            }
7523        }
7524        return null;
7525    }
7526
7527    /**
7528     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7529     * will forward the intent to the filter's target user.
7530     * Otherwise, returns null.
7531     */
7532    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7533            String resolvedType, int flags, int sourceUserId) {
7534        int targetUserId = filter.getTargetUserId();
7535        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7536                resolvedType, flags, targetUserId);
7537        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7538            // If all the matches in the target profile are suspended, return null.
7539            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7540                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7541                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7542                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7543                            targetUserId);
7544                }
7545            }
7546        }
7547        return null;
7548    }
7549
7550    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7551            int sourceUserId, int targetUserId) {
7552        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7553        long ident = Binder.clearCallingIdentity();
7554        boolean targetIsProfile;
7555        try {
7556            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7557        } finally {
7558            Binder.restoreCallingIdentity(ident);
7559        }
7560        String className;
7561        if (targetIsProfile) {
7562            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7563        } else {
7564            className = FORWARD_INTENT_TO_PARENT;
7565        }
7566        ComponentName forwardingActivityComponentName = new ComponentName(
7567                mAndroidApplication.packageName, className);
7568        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7569                sourceUserId);
7570        if (!targetIsProfile) {
7571            forwardingActivityInfo.showUserIcon = targetUserId;
7572            forwardingResolveInfo.noResourceId = true;
7573        }
7574        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7575        forwardingResolveInfo.priority = 0;
7576        forwardingResolveInfo.preferredOrder = 0;
7577        forwardingResolveInfo.match = 0;
7578        forwardingResolveInfo.isDefault = true;
7579        forwardingResolveInfo.filter = filter;
7580        forwardingResolveInfo.targetUserId = targetUserId;
7581        return forwardingResolveInfo;
7582    }
7583
7584    @Override
7585    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7586            Intent[] specifics, String[] specificTypes, Intent intent,
7587            String resolvedType, int flags, int userId) {
7588        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7589                specificTypes, intent, resolvedType, flags, userId));
7590    }
7591
7592    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7593            Intent[] specifics, String[] specificTypes, Intent intent,
7594            String resolvedType, int flags, int userId) {
7595        if (!sUserManager.exists(userId)) return Collections.emptyList();
7596        final int callingUid = Binder.getCallingUid();
7597        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7598                false /*includeInstantApps*/);
7599        enforceCrossUserPermission(callingUid, userId,
7600                false /*requireFullPermission*/, false /*checkShell*/,
7601                "query intent activity options");
7602        final String resultsAction = intent.getAction();
7603
7604        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7605                | PackageManager.GET_RESOLVED_FILTER, userId);
7606
7607        if (DEBUG_INTENT_MATCHING) {
7608            Log.v(TAG, "Query " + intent + ": " + results);
7609        }
7610
7611        int specificsPos = 0;
7612        int N;
7613
7614        // todo: note that the algorithm used here is O(N^2).  This
7615        // isn't a problem in our current environment, but if we start running
7616        // into situations where we have more than 5 or 10 matches then this
7617        // should probably be changed to something smarter...
7618
7619        // First we go through and resolve each of the specific items
7620        // that were supplied, taking care of removing any corresponding
7621        // duplicate items in the generic resolve list.
7622        if (specifics != null) {
7623            for (int i=0; i<specifics.length; i++) {
7624                final Intent sintent = specifics[i];
7625                if (sintent == null) {
7626                    continue;
7627                }
7628
7629                if (DEBUG_INTENT_MATCHING) {
7630                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7631                }
7632
7633                String action = sintent.getAction();
7634                if (resultsAction != null && resultsAction.equals(action)) {
7635                    // If this action was explicitly requested, then don't
7636                    // remove things that have it.
7637                    action = null;
7638                }
7639
7640                ResolveInfo ri = null;
7641                ActivityInfo ai = null;
7642
7643                ComponentName comp = sintent.getComponent();
7644                if (comp == null) {
7645                    ri = resolveIntent(
7646                        sintent,
7647                        specificTypes != null ? specificTypes[i] : null,
7648                            flags, userId);
7649                    if (ri == null) {
7650                        continue;
7651                    }
7652                    if (ri == mResolveInfo) {
7653                        // ACK!  Must do something better with this.
7654                    }
7655                    ai = ri.activityInfo;
7656                    comp = new ComponentName(ai.applicationInfo.packageName,
7657                            ai.name);
7658                } else {
7659                    ai = getActivityInfo(comp, flags, userId);
7660                    if (ai == null) {
7661                        continue;
7662                    }
7663                }
7664
7665                // Look for any generic query activities that are duplicates
7666                // of this specific one, and remove them from the results.
7667                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7668                N = results.size();
7669                int j;
7670                for (j=specificsPos; j<N; j++) {
7671                    ResolveInfo sri = results.get(j);
7672                    if ((sri.activityInfo.name.equals(comp.getClassName())
7673                            && sri.activityInfo.applicationInfo.packageName.equals(
7674                                    comp.getPackageName()))
7675                        || (action != null && sri.filter.matchAction(action))) {
7676                        results.remove(j);
7677                        if (DEBUG_INTENT_MATCHING) Log.v(
7678                            TAG, "Removing duplicate item from " + j
7679                            + " due to specific " + specificsPos);
7680                        if (ri == null) {
7681                            ri = sri;
7682                        }
7683                        j--;
7684                        N--;
7685                    }
7686                }
7687
7688                // Add this specific item to its proper place.
7689                if (ri == null) {
7690                    ri = new ResolveInfo();
7691                    ri.activityInfo = ai;
7692                }
7693                results.add(specificsPos, ri);
7694                ri.specificIndex = i;
7695                specificsPos++;
7696            }
7697        }
7698
7699        // Now we go through the remaining generic results and remove any
7700        // duplicate actions that are found here.
7701        N = results.size();
7702        for (int i=specificsPos; i<N-1; i++) {
7703            final ResolveInfo rii = results.get(i);
7704            if (rii.filter == null) {
7705                continue;
7706            }
7707
7708            // Iterate over all of the actions of this result's intent
7709            // filter...  typically this should be just one.
7710            final Iterator<String> it = rii.filter.actionsIterator();
7711            if (it == null) {
7712                continue;
7713            }
7714            while (it.hasNext()) {
7715                final String action = it.next();
7716                if (resultsAction != null && resultsAction.equals(action)) {
7717                    // If this action was explicitly requested, then don't
7718                    // remove things that have it.
7719                    continue;
7720                }
7721                for (int j=i+1; j<N; j++) {
7722                    final ResolveInfo rij = results.get(j);
7723                    if (rij.filter != null && rij.filter.hasAction(action)) {
7724                        results.remove(j);
7725                        if (DEBUG_INTENT_MATCHING) Log.v(
7726                            TAG, "Removing duplicate item from " + j
7727                            + " due to action " + action + " at " + i);
7728                        j--;
7729                        N--;
7730                    }
7731                }
7732            }
7733
7734            // If the caller didn't request filter information, drop it now
7735            // so we don't have to marshall/unmarshall it.
7736            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7737                rii.filter = null;
7738            }
7739        }
7740
7741        // Filter out the caller activity if so requested.
7742        if (caller != null) {
7743            N = results.size();
7744            for (int i=0; i<N; i++) {
7745                ActivityInfo ainfo = results.get(i).activityInfo;
7746                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7747                        && caller.getClassName().equals(ainfo.name)) {
7748                    results.remove(i);
7749                    break;
7750                }
7751            }
7752        }
7753
7754        // If the caller didn't request filter information,
7755        // drop them now so we don't have to
7756        // marshall/unmarshall it.
7757        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7758            N = results.size();
7759            for (int i=0; i<N; i++) {
7760                results.get(i).filter = null;
7761            }
7762        }
7763
7764        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7765        return results;
7766    }
7767
7768    @Override
7769    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7770            String resolvedType, int flags, int userId) {
7771        return new ParceledListSlice<>(
7772                queryIntentReceiversInternal(intent, resolvedType, flags, userId));
7773    }
7774
7775    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7776            String resolvedType, int flags, int userId) {
7777        if (!sUserManager.exists(userId)) return Collections.emptyList();
7778        final int callingUid = Binder.getCallingUid();
7779        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7780        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7781                false /*includeInstantApps*/);
7782        ComponentName comp = intent.getComponent();
7783        if (comp == null) {
7784            if (intent.getSelector() != null) {
7785                intent = intent.getSelector();
7786                comp = intent.getComponent();
7787            }
7788        }
7789        if (comp != null) {
7790            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7791            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7792            if (ai != null) {
7793                // When specifying an explicit component, we prevent the activity from being
7794                // used when either 1) the calling package is normal and the activity is within
7795                // an instant application or 2) the calling package is ephemeral and the
7796                // activity is not visible to instant applications.
7797                final boolean matchInstantApp =
7798                        (flags & PackageManager.MATCH_INSTANT) != 0;
7799                final boolean matchVisibleToInstantAppOnly =
7800                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7801                final boolean matchExplicitlyVisibleOnly =
7802                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7803                final boolean isCallerInstantApp =
7804                        instantAppPkgName != null;
7805                final boolean isTargetSameInstantApp =
7806                        comp.getPackageName().equals(instantAppPkgName);
7807                final boolean isTargetInstantApp =
7808                        (ai.applicationInfo.privateFlags
7809                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7810                final boolean isTargetVisibleToInstantApp =
7811                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7812                final boolean isTargetExplicitlyVisibleToInstantApp =
7813                        isTargetVisibleToInstantApp
7814                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7815                final boolean isTargetHiddenFromInstantApp =
7816                        !isTargetVisibleToInstantApp
7817                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7818                final boolean blockResolution =
7819                        !isTargetSameInstantApp
7820                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7821                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7822                                        && isTargetHiddenFromInstantApp));
7823                if (!blockResolution) {
7824                    ResolveInfo ri = new ResolveInfo();
7825                    ri.activityInfo = ai;
7826                    list.add(ri);
7827                }
7828            }
7829            return applyPostResolutionFilter(list, instantAppPkgName);
7830        }
7831
7832        // reader
7833        synchronized (mPackages) {
7834            String pkgName = intent.getPackage();
7835            if (pkgName == null) {
7836                final List<ResolveInfo> result =
7837                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7838                return applyPostResolutionFilter(result, instantAppPkgName);
7839            }
7840            final PackageParser.Package pkg = mPackages.get(pkgName);
7841            if (pkg != null) {
7842                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7843                        intent, resolvedType, flags, pkg.receivers, userId);
7844                return applyPostResolutionFilter(result, instantAppPkgName);
7845            }
7846            return Collections.emptyList();
7847        }
7848    }
7849
7850    @Override
7851    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7852        final int callingUid = Binder.getCallingUid();
7853        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7854    }
7855
7856    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7857            int userId, int callingUid) {
7858        if (!sUserManager.exists(userId)) return null;
7859        flags = updateFlagsForResolve(
7860                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7861        List<ResolveInfo> query = queryIntentServicesInternal(
7862                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7863        if (query != null) {
7864            if (query.size() >= 1) {
7865                // If there is more than one service with the same priority,
7866                // just arbitrarily pick the first one.
7867                return query.get(0);
7868            }
7869        }
7870        return null;
7871    }
7872
7873    @Override
7874    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7875            String resolvedType, int flags, int userId) {
7876        final int callingUid = Binder.getCallingUid();
7877        return new ParceledListSlice<>(queryIntentServicesInternal(
7878                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7879    }
7880
7881    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7882            String resolvedType, int flags, int userId, int callingUid,
7883            boolean includeInstantApps) {
7884        if (!sUserManager.exists(userId)) return Collections.emptyList();
7885        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7886        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7887        ComponentName comp = intent.getComponent();
7888        if (comp == null) {
7889            if (intent.getSelector() != null) {
7890                intent = intent.getSelector();
7891                comp = intent.getComponent();
7892            }
7893        }
7894        if (comp != null) {
7895            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7896            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7897            if (si != null) {
7898                // When specifying an explicit component, we prevent the service from being
7899                // used when either 1) the service is in an instant application and the
7900                // caller is not the same instant application or 2) the calling package is
7901                // ephemeral and the activity is not visible to ephemeral applications.
7902                final boolean matchInstantApp =
7903                        (flags & PackageManager.MATCH_INSTANT) != 0;
7904                final boolean matchVisibleToInstantAppOnly =
7905                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7906                final boolean isCallerInstantApp =
7907                        instantAppPkgName != null;
7908                final boolean isTargetSameInstantApp =
7909                        comp.getPackageName().equals(instantAppPkgName);
7910                final boolean isTargetInstantApp =
7911                        (si.applicationInfo.privateFlags
7912                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7913                final boolean isTargetHiddenFromInstantApp =
7914                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7915                final boolean blockResolution =
7916                        !isTargetSameInstantApp
7917                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7918                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7919                                        && isTargetHiddenFromInstantApp));
7920                if (!blockResolution) {
7921                    final ResolveInfo ri = new ResolveInfo();
7922                    ri.serviceInfo = si;
7923                    list.add(ri);
7924                }
7925            }
7926            return list;
7927        }
7928
7929        // reader
7930        synchronized (mPackages) {
7931            String pkgName = intent.getPackage();
7932            if (pkgName == null) {
7933                return applyPostServiceResolutionFilter(
7934                        mServices.queryIntent(intent, resolvedType, flags, userId),
7935                        instantAppPkgName);
7936            }
7937            final PackageParser.Package pkg = mPackages.get(pkgName);
7938            if (pkg != null) {
7939                return applyPostServiceResolutionFilter(
7940                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7941                                userId),
7942                        instantAppPkgName);
7943            }
7944            return Collections.emptyList();
7945        }
7946    }
7947
7948    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7949            String instantAppPkgName) {
7950        // TODO: When adding on-demand split support for non-instant apps, remove this check
7951        // and always apply post filtering
7952        if (instantAppPkgName == null) {
7953            return resolveInfos;
7954        }
7955        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7956            final ResolveInfo info = resolveInfos.get(i);
7957            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7958            // allow services that are defined in the provided package
7959            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7960                if (info.serviceInfo.splitName != null
7961                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7962                                info.serviceInfo.splitName)) {
7963                    // requested service is defined in a split that hasn't been installed yet.
7964                    // add the installer to the resolve list
7965                    if (DEBUG_EPHEMERAL) {
7966                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7967                    }
7968                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
7969                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7970                            info.serviceInfo.packageName, info.serviceInfo.splitName,
7971                            info.serviceInfo.applicationInfo.versionCode, null /*failureIntent*/);
7972                    // make sure this resolver is the default
7973                    installerInfo.isDefault = true;
7974                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7975                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7976                    // add a non-generic filter
7977                    installerInfo.filter = new IntentFilter();
7978                    // load resources from the correct package
7979                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7980                    resolveInfos.set(i, installerInfo);
7981                }
7982                continue;
7983            }
7984            // allow services that have been explicitly exposed to ephemeral apps
7985            if (!isEphemeralApp
7986                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7987                continue;
7988            }
7989            resolveInfos.remove(i);
7990        }
7991        return resolveInfos;
7992    }
7993
7994    @Override
7995    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7996            String resolvedType, int flags, int userId) {
7997        return new ParceledListSlice<>(
7998                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7999    }
8000
8001    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8002            Intent intent, String resolvedType, int flags, int userId) {
8003        if (!sUserManager.exists(userId)) return Collections.emptyList();
8004        final int callingUid = Binder.getCallingUid();
8005        final String instantAppPkgName = getInstantAppPackageName(callingUid);
8006        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8007                false /*includeInstantApps*/);
8008        ComponentName comp = intent.getComponent();
8009        if (comp == null) {
8010            if (intent.getSelector() != null) {
8011                intent = intent.getSelector();
8012                comp = intent.getComponent();
8013            }
8014        }
8015        if (comp != null) {
8016            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
8017            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8018            if (pi != null) {
8019                // When specifying an explicit component, we prevent the provider from being
8020                // used when either 1) the provider is in an instant application and the
8021                // caller is not the same instant application or 2) the calling package is an
8022                // instant application and the provider is not visible to instant applications.
8023                final boolean matchInstantApp =
8024                        (flags & PackageManager.MATCH_INSTANT) != 0;
8025                final boolean matchVisibleToInstantAppOnly =
8026                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8027                final boolean isCallerInstantApp =
8028                        instantAppPkgName != null;
8029                final boolean isTargetSameInstantApp =
8030                        comp.getPackageName().equals(instantAppPkgName);
8031                final boolean isTargetInstantApp =
8032                        (pi.applicationInfo.privateFlags
8033                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8034                final boolean isTargetHiddenFromInstantApp =
8035                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8036                final boolean blockResolution =
8037                        !isTargetSameInstantApp
8038                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8039                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
8040                                        && isTargetHiddenFromInstantApp));
8041                if (!blockResolution) {
8042                    final ResolveInfo ri = new ResolveInfo();
8043                    ri.providerInfo = pi;
8044                    list.add(ri);
8045                }
8046            }
8047            return list;
8048        }
8049
8050        // reader
8051        synchronized (mPackages) {
8052            String pkgName = intent.getPackage();
8053            if (pkgName == null) {
8054                return applyPostContentProviderResolutionFilter(
8055                        mProviders.queryIntent(intent, resolvedType, flags, userId),
8056                        instantAppPkgName);
8057            }
8058            final PackageParser.Package pkg = mPackages.get(pkgName);
8059            if (pkg != null) {
8060                return applyPostContentProviderResolutionFilter(
8061                        mProviders.queryIntentForPackage(
8062                        intent, resolvedType, flags, pkg.providers, userId),
8063                        instantAppPkgName);
8064            }
8065            return Collections.emptyList();
8066        }
8067    }
8068
8069    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8070            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8071        // TODO: When adding on-demand split support for non-instant applications, remove
8072        // this check and always apply post filtering
8073        if (instantAppPkgName == null) {
8074            return resolveInfos;
8075        }
8076        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8077            final ResolveInfo info = resolveInfos.get(i);
8078            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8079            // allow providers that are defined in the provided package
8080            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8081                if (info.providerInfo.splitName != null
8082                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8083                                info.providerInfo.splitName)) {
8084                    // requested provider is defined in a split that hasn't been installed yet.
8085                    // add the installer to the resolve list
8086                    if (DEBUG_EPHEMERAL) {
8087                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8088                    }
8089                    final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo);
8090                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8091                            info.providerInfo.packageName, info.providerInfo.splitName,
8092                            info.providerInfo.applicationInfo.versionCode, null /*failureIntent*/);
8093                    // make sure this resolver is the default
8094                    installerInfo.isDefault = true;
8095                    installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
8096                            | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
8097                    // add a non-generic filter
8098                    installerInfo.filter = new IntentFilter();
8099                    // load resources from the correct package
8100                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8101                    resolveInfos.set(i, installerInfo);
8102                }
8103                continue;
8104            }
8105            // allow providers that have been explicitly exposed to instant applications
8106            if (!isEphemeralApp
8107                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8108                continue;
8109            }
8110            resolveInfos.remove(i);
8111        }
8112        return resolveInfos;
8113    }
8114
8115    @Override
8116    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8117        final int callingUid = Binder.getCallingUid();
8118        if (getInstantAppPackageName(callingUid) != null) {
8119            return ParceledListSlice.emptyList();
8120        }
8121        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8122        flags = updateFlagsForPackage(flags, userId, null);
8123        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8124        enforceCrossUserPermission(callingUid, userId,
8125                true /* requireFullPermission */, false /* checkShell */,
8126                "get installed packages");
8127
8128        // writer
8129        synchronized (mPackages) {
8130            ArrayList<PackageInfo> list;
8131            if (listUninstalled) {
8132                list = new ArrayList<>(mSettings.mPackages.size());
8133                for (PackageSetting ps : mSettings.mPackages.values()) {
8134                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8135                        continue;
8136                    }
8137                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8138                        return null;
8139                    }
8140                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8141                    if (pi != null) {
8142                        list.add(pi);
8143                    }
8144                }
8145            } else {
8146                list = new ArrayList<>(mPackages.size());
8147                for (PackageParser.Package p : mPackages.values()) {
8148                    final PackageSetting ps = (PackageSetting) p.mExtras;
8149                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8150                        continue;
8151                    }
8152                    if (filterAppAccessLPr(ps, callingUid, userId)) {
8153                        return null;
8154                    }
8155                    final PackageInfo pi = generatePackageInfo((PackageSetting)
8156                            p.mExtras, flags, userId);
8157                    if (pi != null) {
8158                        list.add(pi);
8159                    }
8160                }
8161            }
8162
8163            return new ParceledListSlice<>(list);
8164        }
8165    }
8166
8167    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8168            String[] permissions, boolean[] tmp, int flags, int userId) {
8169        int numMatch = 0;
8170        final PermissionsState permissionsState = ps.getPermissionsState();
8171        for (int i=0; i<permissions.length; i++) {
8172            final String permission = permissions[i];
8173            if (permissionsState.hasPermission(permission, userId)) {
8174                tmp[i] = true;
8175                numMatch++;
8176            } else {
8177                tmp[i] = false;
8178            }
8179        }
8180        if (numMatch == 0) {
8181            return;
8182        }
8183        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8184
8185        // The above might return null in cases of uninstalled apps or install-state
8186        // skew across users/profiles.
8187        if (pi != null) {
8188            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8189                if (numMatch == permissions.length) {
8190                    pi.requestedPermissions = permissions;
8191                } else {
8192                    pi.requestedPermissions = new String[numMatch];
8193                    numMatch = 0;
8194                    for (int i=0; i<permissions.length; i++) {
8195                        if (tmp[i]) {
8196                            pi.requestedPermissions[numMatch] = permissions[i];
8197                            numMatch++;
8198                        }
8199                    }
8200                }
8201            }
8202            list.add(pi);
8203        }
8204    }
8205
8206    @Override
8207    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8208            String[] permissions, int flags, int userId) {
8209        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8210        flags = updateFlagsForPackage(flags, userId, permissions);
8211        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8212                true /* requireFullPermission */, false /* checkShell */,
8213                "get packages holding permissions");
8214        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8215
8216        // writer
8217        synchronized (mPackages) {
8218            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
8219            boolean[] tmpBools = new boolean[permissions.length];
8220            if (listUninstalled) {
8221                for (PackageSetting ps : mSettings.mPackages.values()) {
8222                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8223                            userId);
8224                }
8225            } else {
8226                for (PackageParser.Package pkg : mPackages.values()) {
8227                    PackageSetting ps = (PackageSetting)pkg.mExtras;
8228                    if (ps != null) {
8229                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8230                                userId);
8231                    }
8232                }
8233            }
8234
8235            return new ParceledListSlice<PackageInfo>(list);
8236        }
8237    }
8238
8239    @Override
8240    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8241        final int callingUid = Binder.getCallingUid();
8242        if (getInstantAppPackageName(callingUid) != null) {
8243            return ParceledListSlice.emptyList();
8244        }
8245        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8246        flags = updateFlagsForApplication(flags, userId, null);
8247        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8248
8249        // writer
8250        synchronized (mPackages) {
8251            ArrayList<ApplicationInfo> list;
8252            if (listUninstalled) {
8253                list = new ArrayList<>(mSettings.mPackages.size());
8254                for (PackageSetting ps : mSettings.mPackages.values()) {
8255                    ApplicationInfo ai;
8256                    int effectiveFlags = flags;
8257                    if (ps.isSystem()) {
8258                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
8259                    }
8260                    if (ps.pkg != null) {
8261                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8262                            continue;
8263                        }
8264                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8265                            return null;
8266                        }
8267                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8268                                ps.readUserState(userId), userId);
8269                        if (ai != null) {
8270                            rebaseEnabledOverlays(ai, userId);
8271                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8272                        }
8273                    } else {
8274                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8275                        // and already converts to externally visible package name
8276                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
8277                                callingUid, effectiveFlags, userId);
8278                    }
8279                    if (ai != null) {
8280                        list.add(ai);
8281                    }
8282                }
8283            } else {
8284                list = new ArrayList<>(mPackages.size());
8285                for (PackageParser.Package p : mPackages.values()) {
8286                    if (p.mExtras != null) {
8287                        PackageSetting ps = (PackageSetting) p.mExtras;
8288                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8289                            continue;
8290                        }
8291                        if (filterAppAccessLPr(ps, callingUid, userId)) {
8292                            return null;
8293                        }
8294                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8295                                ps.readUserState(userId), userId);
8296                        if (ai != null) {
8297                            rebaseEnabledOverlays(ai, userId);
8298                            ai.packageName = resolveExternalPackageNameLPr(p);
8299                            list.add(ai);
8300                        }
8301                    }
8302                }
8303            }
8304
8305            return new ParceledListSlice<>(list);
8306        }
8307    }
8308
8309    @Override
8310    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8311        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8312            return null;
8313        }
8314        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8315                "getEphemeralApplications");
8316        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8317                true /* requireFullPermission */, false /* checkShell */,
8318                "getEphemeralApplications");
8319        synchronized (mPackages) {
8320            List<InstantAppInfo> instantApps = mInstantAppRegistry
8321                    .getInstantAppsLPr(userId);
8322            if (instantApps != null) {
8323                return new ParceledListSlice<>(instantApps);
8324            }
8325        }
8326        return null;
8327    }
8328
8329    @Override
8330    public boolean isInstantApp(String packageName, int userId) {
8331        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8332                true /* requireFullPermission */, false /* checkShell */,
8333                "isInstantApp");
8334        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8335            return false;
8336        }
8337        int callingUid = Binder.getCallingUid();
8338        if (Process.isIsolated(callingUid)) {
8339            callingUid = mIsolatedOwners.get(callingUid);
8340        }
8341
8342        synchronized (mPackages) {
8343            final PackageSetting ps = mSettings.mPackages.get(packageName);
8344            PackageParser.Package pkg = mPackages.get(packageName);
8345            final boolean returnAllowed =
8346                    ps != null
8347                    && (isCallerSameApp(packageName, callingUid)
8348                            || canViewInstantApps(callingUid, userId)
8349                            || mInstantAppRegistry.isInstantAccessGranted(
8350                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8351            if (returnAllowed) {
8352                return ps.getInstantApp(userId);
8353            }
8354        }
8355        return false;
8356    }
8357
8358    @Override
8359    public byte[] getInstantAppCookie(String packageName, int userId) {
8360        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8361            return null;
8362        }
8363
8364        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8365                true /* requireFullPermission */, false /* checkShell */,
8366                "getInstantAppCookie");
8367        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8368            return null;
8369        }
8370        synchronized (mPackages) {
8371            return mInstantAppRegistry.getInstantAppCookieLPw(
8372                    packageName, userId);
8373        }
8374    }
8375
8376    @Override
8377    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8378        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8379            return true;
8380        }
8381
8382        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8383                true /* requireFullPermission */, true /* checkShell */,
8384                "setInstantAppCookie");
8385        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8386            return false;
8387        }
8388        synchronized (mPackages) {
8389            return mInstantAppRegistry.setInstantAppCookieLPw(
8390                    packageName, cookie, userId);
8391        }
8392    }
8393
8394    @Override
8395    public Bitmap getInstantAppIcon(String packageName, int userId) {
8396        if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) {
8397            return null;
8398        }
8399
8400        mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8401                "getInstantAppIcon");
8402
8403        enforceCrossUserPermission(Binder.getCallingUid(), userId,
8404                true /* requireFullPermission */, false /* checkShell */,
8405                "getInstantAppIcon");
8406
8407        synchronized (mPackages) {
8408            return mInstantAppRegistry.getInstantAppIconLPw(
8409                    packageName, userId);
8410        }
8411    }
8412
8413    private boolean isCallerSameApp(String packageName, int uid) {
8414        PackageParser.Package pkg = mPackages.get(packageName);
8415        return pkg != null
8416                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8417    }
8418
8419    @Override
8420    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8421        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8422            return ParceledListSlice.emptyList();
8423        }
8424        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8425    }
8426
8427    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8428        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8429
8430        // reader
8431        synchronized (mPackages) {
8432            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8433            final int userId = UserHandle.getCallingUserId();
8434            while (i.hasNext()) {
8435                final PackageParser.Package p = i.next();
8436                if (p.applicationInfo == null) continue;
8437
8438                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8439                        && !p.applicationInfo.isDirectBootAware();
8440                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8441                        && p.applicationInfo.isDirectBootAware();
8442
8443                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8444                        && (!mSafeMode || isSystemApp(p))
8445                        && (matchesUnaware || matchesAware)) {
8446                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8447                    if (ps != null) {
8448                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8449                                ps.readUserState(userId), userId);
8450                        if (ai != null) {
8451                            rebaseEnabledOverlays(ai, userId);
8452                            finalList.add(ai);
8453                        }
8454                    }
8455                }
8456            }
8457        }
8458
8459        return finalList;
8460    }
8461
8462    @Override
8463    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8464        if (!sUserManager.exists(userId)) return null;
8465        flags = updateFlagsForComponent(flags, userId, name);
8466        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8467        // reader
8468        synchronized (mPackages) {
8469            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8470            PackageSetting ps = provider != null
8471                    ? mSettings.mPackages.get(provider.owner.packageName)
8472                    : null;
8473            if (ps != null) {
8474                final boolean isInstantApp = ps.getInstantApp(userId);
8475                // normal application; filter out instant application provider
8476                if (instantAppPkgName == null && isInstantApp) {
8477                    return null;
8478                }
8479                // instant application; filter out other instant applications
8480                if (instantAppPkgName != null
8481                        && isInstantApp
8482                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8483                    return null;
8484                }
8485                // instant application; filter out non-exposed provider
8486                if (instantAppPkgName != null
8487                        && !isInstantApp
8488                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8489                    return null;
8490                }
8491                // provider not enabled
8492                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8493                    return null;
8494                }
8495                return PackageParser.generateProviderInfo(
8496                        provider, flags, ps.readUserState(userId), userId);
8497            }
8498            return null;
8499        }
8500    }
8501
8502    /**
8503     * @deprecated
8504     */
8505    @Deprecated
8506    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8507        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8508            return;
8509        }
8510        // reader
8511        synchronized (mPackages) {
8512            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8513                    .entrySet().iterator();
8514            final int userId = UserHandle.getCallingUserId();
8515            while (i.hasNext()) {
8516                Map.Entry<String, PackageParser.Provider> entry = i.next();
8517                PackageParser.Provider p = entry.getValue();
8518                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8519
8520                if (ps != null && p.syncable
8521                        && (!mSafeMode || (p.info.applicationInfo.flags
8522                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8523                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8524                            ps.readUserState(userId), userId);
8525                    if (info != null) {
8526                        outNames.add(entry.getKey());
8527                        outInfo.add(info);
8528                    }
8529                }
8530            }
8531        }
8532    }
8533
8534    @Override
8535    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8536            int uid, int flags, String metaDataKey) {
8537        final int callingUid = Binder.getCallingUid();
8538        final int userId = processName != null ? UserHandle.getUserId(uid)
8539                : UserHandle.getCallingUserId();
8540        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8541        flags = updateFlagsForComponent(flags, userId, processName);
8542        ArrayList<ProviderInfo> finalList = null;
8543        // reader
8544        synchronized (mPackages) {
8545            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8546            while (i.hasNext()) {
8547                final PackageParser.Provider p = i.next();
8548                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8549                if (ps != null && p.info.authority != null
8550                        && (processName == null
8551                                || (p.info.processName.equals(processName)
8552                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8553                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8554
8555                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8556                    // parameter.
8557                    if (metaDataKey != null
8558                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8559                        continue;
8560                    }
8561                    final ComponentName component =
8562                            new ComponentName(p.info.packageName, p.info.name);
8563                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8564                        continue;
8565                    }
8566                    if (finalList == null) {
8567                        finalList = new ArrayList<ProviderInfo>(3);
8568                    }
8569                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8570                            ps.readUserState(userId), userId);
8571                    if (info != null) {
8572                        finalList.add(info);
8573                    }
8574                }
8575            }
8576        }
8577
8578        if (finalList != null) {
8579            Collections.sort(finalList, mProviderInitOrderSorter);
8580            return new ParceledListSlice<ProviderInfo>(finalList);
8581        }
8582
8583        return ParceledListSlice.emptyList();
8584    }
8585
8586    @Override
8587    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8588        // reader
8589        synchronized (mPackages) {
8590            final int callingUid = Binder.getCallingUid();
8591            final int callingUserId = UserHandle.getUserId(callingUid);
8592            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8593            if (ps == null) return null;
8594            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8595                return null;
8596            }
8597            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8598            return PackageParser.generateInstrumentationInfo(i, flags);
8599        }
8600    }
8601
8602    @Override
8603    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8604            String targetPackage, int flags) {
8605        final int callingUid = Binder.getCallingUid();
8606        final int callingUserId = UserHandle.getUserId(callingUid);
8607        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8608        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8609            return ParceledListSlice.emptyList();
8610        }
8611        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8612    }
8613
8614    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8615            int flags) {
8616        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8617
8618        // reader
8619        synchronized (mPackages) {
8620            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8621            while (i.hasNext()) {
8622                final PackageParser.Instrumentation p = i.next();
8623                if (targetPackage == null
8624                        || targetPackage.equals(p.info.targetPackage)) {
8625                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8626                            flags);
8627                    if (ii != null) {
8628                        finalList.add(ii);
8629                    }
8630                }
8631            }
8632        }
8633
8634        return finalList;
8635    }
8636
8637    private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) {
8638        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]");
8639        try {
8640            scanDirLI(dir, parseFlags, scanFlags, currentTime);
8641        } finally {
8642            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8643        }
8644    }
8645
8646    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
8647        final File[] files = dir.listFiles();
8648        if (ArrayUtils.isEmpty(files)) {
8649            Log.d(TAG, "No files in app dir " + dir);
8650            return;
8651        }
8652
8653        if (DEBUG_PACKAGE_SCANNING) {
8654            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
8655                    + " flags=0x" + Integer.toHexString(parseFlags));
8656        }
8657        ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8658                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8659                mParallelPackageParserCallback);
8660
8661        // Submit files for parsing in parallel
8662        int fileCount = 0;
8663        for (File file : files) {
8664            final boolean isPackage = (isApkFile(file) || file.isDirectory())
8665                    && !PackageInstallerService.isStageName(file.getName());
8666            if (!isPackage) {
8667                // Ignore entries which are not packages
8668                continue;
8669            }
8670            parallelPackageParser.submit(file, parseFlags);
8671            fileCount++;
8672        }
8673
8674        // Process results one by one
8675        for (; fileCount > 0; fileCount--) {
8676            ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8677            Throwable throwable = parseResult.throwable;
8678            int errorCode = PackageManager.INSTALL_SUCCEEDED;
8679
8680            if (throwable == null) {
8681                // Static shared libraries have synthetic package names
8682                if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8683                    renameStaticSharedLibraryPackage(parseResult.pkg);
8684                }
8685                try {
8686                    if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8687                        scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags,
8688                                currentTime, null);
8689                    }
8690                } catch (PackageManagerException e) {
8691                    errorCode = e.error;
8692                    Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8693                }
8694            } else if (throwable instanceof PackageParser.PackageParserException) {
8695                PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8696                        throwable;
8697                errorCode = e.error;
8698                Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8699            } else {
8700                throw new IllegalStateException("Unexpected exception occurred while parsing "
8701                        + parseResult.scanFile, throwable);
8702            }
8703
8704            // Delete invalid userdata apps
8705            if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
8706                    errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8707                logCriticalInfo(Log.WARN,
8708                        "Deleting invalid package at " + parseResult.scanFile);
8709                removeCodePathLI(parseResult.scanFile);
8710            }
8711        }
8712        parallelPackageParser.close();
8713    }
8714
8715    private static File getSettingsProblemFile() {
8716        File dataDir = Environment.getDataDirectory();
8717        File systemDir = new File(dataDir, "system");
8718        File fname = new File(systemDir, "uiderrors.txt");
8719        return fname;
8720    }
8721
8722    static void reportSettingsProblem(int priority, String msg) {
8723        logCriticalInfo(priority, msg);
8724    }
8725
8726    public static void logCriticalInfo(int priority, String msg) {
8727        Slog.println(priority, TAG, msg);
8728        EventLogTags.writePmCriticalInfo(msg);
8729        try {
8730            File fname = getSettingsProblemFile();
8731            FileOutputStream out = new FileOutputStream(fname, true);
8732            PrintWriter pw = new FastPrintWriter(out);
8733            SimpleDateFormat formatter = new SimpleDateFormat();
8734            String dateString = formatter.format(new Date(System.currentTimeMillis()));
8735            pw.println(dateString + ": " + msg);
8736            pw.close();
8737            FileUtils.setPermissions(
8738                    fname.toString(),
8739                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
8740                    -1, -1);
8741        } catch (java.io.IOException e) {
8742        }
8743    }
8744
8745    private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) {
8746        if (srcFile.isDirectory()) {
8747            final File baseFile = new File(pkg.baseCodePath);
8748            long maxModifiedTime = baseFile.lastModified();
8749            if (pkg.splitCodePaths != null) {
8750                for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) {
8751                    final File splitFile = new File(pkg.splitCodePaths[i]);
8752                    maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified());
8753                }
8754            }
8755            return maxModifiedTime;
8756        }
8757        return srcFile.lastModified();
8758    }
8759
8760    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile,
8761            final int policyFlags) throws PackageManagerException {
8762        // When upgrading from pre-N MR1, verify the package time stamp using the package
8763        // directory and not the APK file.
8764        final long lastModifiedTime = mIsPreNMR1Upgrade
8765                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile);
8766        if (ps != null
8767                && ps.codePath.equals(srcFile)
8768                && ps.timeStamp == lastModifiedTime
8769                && !isCompatSignatureUpdateNeeded(pkg)
8770                && !isRecoverSignatureUpdateNeeded(pkg)) {
8771            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
8772            KeySetManagerService ksms = mSettings.mKeySetManagerService;
8773            ArraySet<PublicKey> signingKs;
8774            synchronized (mPackages) {
8775                signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
8776            }
8777            if (ps.signatures.mSignatures != null
8778                    && ps.signatures.mSignatures.length != 0
8779                    && signingKs != null) {
8780                // Optimization: reuse the existing cached certificates
8781                // if the package appears to be unchanged.
8782                pkg.mSignatures = ps.signatures.mSignatures;
8783                pkg.mSigningKeys = signingKs;
8784                return;
8785            }
8786
8787            Slog.w(TAG, "PackageSetting for " + ps.name
8788                    + " is missing signatures.  Collecting certs again to recover them.");
8789        } else {
8790            Slog.i(TAG, srcFile.toString() + " changed; collecting certs");
8791        }
8792
8793        try {
8794            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8795            PackageParser.collectCertificates(pkg, policyFlags);
8796        } catch (PackageParserException e) {
8797            throw PackageManagerException.from(e);
8798        } finally {
8799            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8800        }
8801    }
8802
8803    /**
8804     *  Traces a package scan.
8805     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8806     */
8807    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8808            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8809        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8810        try {
8811            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8812        } finally {
8813            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8814        }
8815    }
8816
8817    /**
8818     *  Scans a package and returns the newly parsed package.
8819     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8820     */
8821    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8822            long currentTime, UserHandle user) throws PackageManagerException {
8823        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8824        PackageParser pp = new PackageParser();
8825        pp.setSeparateProcesses(mSeparateProcesses);
8826        pp.setOnlyCoreApps(mOnlyCore);
8827        pp.setDisplayMetrics(mMetrics);
8828        pp.setCallback(mPackageParserCallback);
8829
8830        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
8831            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
8832        }
8833
8834        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8835        final PackageParser.Package pkg;
8836        try {
8837            pkg = pp.parsePackage(scanFile, parseFlags);
8838        } catch (PackageParserException e) {
8839            throw PackageManagerException.from(e);
8840        } finally {
8841            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8842        }
8843
8844        // Static shared libraries have synthetic package names
8845        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8846            renameStaticSharedLibraryPackage(pkg);
8847        }
8848
8849        return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user);
8850    }
8851
8852    /**
8853     *  Scans a package and returns the newly parsed package.
8854     *  @throws PackageManagerException on a parse error.
8855     */
8856    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile,
8857            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8858            throws PackageManagerException {
8859        // If the package has children and this is the first dive in the function
8860        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8861        // packages (parent and children) would be successfully scanned before the
8862        // actual scan since scanning mutates internal state and we want to atomically
8863        // install the package and its children.
8864        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8865            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8866                scanFlags |= SCAN_CHECK_ONLY;
8867            }
8868        } else {
8869            scanFlags &= ~SCAN_CHECK_ONLY;
8870        }
8871
8872        // Scan the parent
8873        PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags,
8874                scanFlags, currentTime, user);
8875
8876        // Scan the children
8877        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8878        for (int i = 0; i < childCount; i++) {
8879            PackageParser.Package childPackage = pkg.childPackages.get(i);
8880            scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags,
8881                    currentTime, user);
8882        }
8883
8884
8885        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8886            return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user);
8887        }
8888
8889        return scannedPkg;
8890    }
8891
8892    /**
8893     *  Scans a package and returns the newly parsed package.
8894     *  @throws PackageManagerException on a parse error.
8895     */
8896    private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile,
8897            int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
8898            throws PackageManagerException {
8899        PackageSetting ps = null;
8900        PackageSetting updatedPkg;
8901        // reader
8902        synchronized (mPackages) {
8903            // Look to see if we already know about this package.
8904            String oldName = mSettings.getRenamedPackageLPr(pkg.packageName);
8905            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
8906                // This package has been renamed to its original name.  Let's
8907                // use that.
8908                ps = mSettings.getPackageLPr(oldName);
8909            }
8910            // If there was no original package, see one for the real package name.
8911            if (ps == null) {
8912                ps = mSettings.getPackageLPr(pkg.packageName);
8913            }
8914            // Check to see if this package could be hiding/updating a system
8915            // package.  Must look for it either under the original or real
8916            // package name depending on our state.
8917            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
8918            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
8919
8920            // If this is a package we don't know about on the system partition, we
8921            // may need to remove disabled child packages on the system partition
8922            // or may need to not add child packages if the parent apk is updated
8923            // on the data partition and no longer defines this child package.
8924            if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8925                // If this is a parent package for an updated system app and this system
8926                // app got an OTA update which no longer defines some of the child packages
8927                // we have to prune them from the disabled system packages.
8928                PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8929                if (disabledPs != null) {
8930                    final int scannedChildCount = (pkg.childPackages != null)
8931                            ? pkg.childPackages.size() : 0;
8932                    final int disabledChildCount = disabledPs.childPackageNames != null
8933                            ? disabledPs.childPackageNames.size() : 0;
8934                    for (int i = 0; i < disabledChildCount; i++) {
8935                        String disabledChildPackageName = disabledPs.childPackageNames.get(i);
8936                        boolean disabledPackageAvailable = false;
8937                        for (int j = 0; j < scannedChildCount; j++) {
8938                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8939                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8940                                disabledPackageAvailable = true;
8941                                break;
8942                            }
8943                         }
8944                         if (!disabledPackageAvailable) {
8945                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8946                         }
8947                    }
8948                }
8949            }
8950        }
8951
8952        boolean updatedPkgBetter = false;
8953        // First check if this is a system package that may involve an update
8954        if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) {
8955            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
8956            // it needs to drop FLAG_PRIVILEGED.
8957            if (locationIsPrivileged(scanFile)) {
8958                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8959            } else {
8960                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
8961            }
8962
8963            if (ps != null && !ps.codePath.equals(scanFile)) {
8964                // The path has changed from what was last scanned...  check the
8965                // version of the new path against what we have stored to determine
8966                // what to do.
8967                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
8968                if (pkg.mVersionCode <= ps.versionCode) {
8969                    // The system package has been updated and the code path does not match
8970                    // Ignore entry. Skip it.
8971                    if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile
8972                            + " ignored: updated version " + ps.versionCode
8973                            + " better than this " + pkg.mVersionCode);
8974                    if (!updatedPkg.codePath.equals(scanFile)) {
8975                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg "
8976                                + ps.name + " changing from " + updatedPkg.codePathString
8977                                + " to " + scanFile);
8978                        updatedPkg.codePath = scanFile;
8979                        updatedPkg.codePathString = scanFile.toString();
8980                        updatedPkg.resourcePath = scanFile;
8981                        updatedPkg.resourcePathString = scanFile.toString();
8982                    }
8983                    updatedPkg.pkg = pkg;
8984                    updatedPkg.versionCode = pkg.mVersionCode;
8985
8986                    // Update the disabled system child packages to point to the package too.
8987                    final int childCount = updatedPkg.childPackageNames != null
8988                            ? updatedPkg.childPackageNames.size() : 0;
8989                    for (int i = 0; i < childCount; i++) {
8990                        String childPackageName = updatedPkg.childPackageNames.get(i);
8991                        PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr(
8992                                childPackageName);
8993                        if (updatedChildPkg != null) {
8994                            updatedChildPkg.pkg = pkg;
8995                            updatedChildPkg.versionCode = pkg.mVersionCode;
8996                        }
8997                    }
8998
8999                    throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at "
9000                            + scanFile + " ignored: updated version " + ps.versionCode
9001                            + " better than this " + pkg.mVersionCode);
9002                } else {
9003                    // The current app on the system partition is better than
9004                    // what we have updated to on the data partition; switch
9005                    // back to the system partition version.
9006                    // At this point, its safely assumed that package installation for
9007                    // apps in system partition will go through. If not there won't be a working
9008                    // version of the app
9009                    // writer
9010                    synchronized (mPackages) {
9011                        // Just remove the loaded entries from package lists.
9012                        mPackages.remove(ps.name);
9013                    }
9014
9015                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9016                            + " reverting from " + ps.codePathString
9017                            + ": new version " + pkg.mVersionCode
9018                            + " better than installed " + ps.versionCode);
9019
9020                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9021                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9022                    synchronized (mInstallLock) {
9023                        args.cleanUpResourcesLI();
9024                    }
9025                    synchronized (mPackages) {
9026                        mSettings.enableSystemPackageLPw(ps.name);
9027                    }
9028                    updatedPkgBetter = true;
9029                }
9030            }
9031        }
9032
9033        if (updatedPkg != null) {
9034            // An updated system app will not have the PARSE_IS_SYSTEM flag set
9035            // initially
9036            policyFlags |= PackageParser.PARSE_IS_SYSTEM;
9037
9038            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
9039            // flag set initially
9040            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9041                policyFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9042            }
9043        }
9044
9045        // Verify certificates against what was last scanned
9046        collectCertificatesLI(ps, pkg, scanFile, policyFlags);
9047
9048        /*
9049         * A new system app appeared, but we already had a non-system one of the
9050         * same name installed earlier.
9051         */
9052        boolean shouldHideSystemApp = false;
9053        if (updatedPkg == null && ps != null
9054                && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
9055            /*
9056             * Check to make sure the signatures match first. If they don't,
9057             * wipe the installed application and its data.
9058             */
9059            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
9060                    != PackageManager.SIGNATURE_MATCH) {
9061                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
9062                        + " signatures don't match existing userdata copy; removing");
9063                try (PackageFreezer freezer = freezePackage(pkg.packageName,
9064                        "scanPackageInternalLI")) {
9065                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9066                }
9067                ps = null;
9068            } else {
9069                /*
9070                 * If the newly-added system app is an older version than the
9071                 * already installed version, hide it. It will be scanned later
9072                 * and re-added like an update.
9073                 */
9074                if (pkg.mVersionCode <= ps.versionCode) {
9075                    shouldHideSystemApp = true;
9076                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
9077                            + " but new version " + pkg.mVersionCode + " better than installed "
9078                            + ps.versionCode + "; hiding system");
9079                } else {
9080                    /*
9081                     * The newly found system app is a newer version that the
9082                     * one previously installed. Simply remove the
9083                     * already-installed application and replace it with our own
9084                     * while keeping the application data.
9085                     */
9086                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
9087                            + " reverting from " + ps.codePathString + ": new version "
9088                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
9089                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
9090                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
9091                    synchronized (mInstallLock) {
9092                        args.cleanUpResourcesLI();
9093                    }
9094                }
9095            }
9096        }
9097
9098        // The apk is forward locked (not public) if its code and resources
9099        // are kept in different files. (except for app in either system or
9100        // vendor path).
9101        // TODO grab this value from PackageSettings
9102        if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
9103            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
9104                policyFlags |= PackageParser.PARSE_FORWARD_LOCK;
9105            }
9106        }
9107
9108        // TODO: extend to support forward-locked splits
9109        String resourcePath = null;
9110        String baseResourcePath = null;
9111        if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
9112            if (ps != null && ps.resourcePathString != null) {
9113                resourcePath = ps.resourcePathString;
9114                baseResourcePath = ps.resourcePathString;
9115            } else {
9116                // Should not happen at all. Just log an error.
9117                Slog.e(TAG, "Resource path not set for package " + pkg.packageName);
9118            }
9119        } else {
9120            resourcePath = pkg.codePath;
9121            baseResourcePath = pkg.baseCodePath;
9122        }
9123
9124        // Set application objects path explicitly.
9125        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9126        pkg.setApplicationInfoCodePath(pkg.codePath);
9127        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9128        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9129        pkg.setApplicationInfoResourcePath(resourcePath);
9130        pkg.setApplicationInfoBaseResourcePath(baseResourcePath);
9131        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9132
9133        final int userId = ((user == null) ? 0 : user.getIdentifier());
9134        if (ps != null && ps.getInstantApp(userId)) {
9135            scanFlags |= SCAN_AS_INSTANT_APP;
9136        }
9137
9138        // Note that we invoke the following method only if we are about to unpack an application
9139        PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags
9140                | SCAN_UPDATE_SIGNATURE, currentTime, user);
9141
9142        /*
9143         * If the system app should be overridden by a previously installed
9144         * data, hide the system app now and let the /data/app scan pick it up
9145         * again.
9146         */
9147        if (shouldHideSystemApp) {
9148            synchronized (mPackages) {
9149                mSettings.disableSystemPackageLPw(pkg.packageName, true);
9150            }
9151        }
9152
9153        return scannedPkg;
9154    }
9155
9156    private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9157        // Derive the new package synthetic package name
9158        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9159                + pkg.staticSharedLibVersion);
9160    }
9161
9162    private static String fixProcessName(String defProcessName,
9163            String processName) {
9164        if (processName == null) {
9165            return defProcessName;
9166        }
9167        return processName;
9168    }
9169
9170    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
9171            throws PackageManagerException {
9172        if (pkgSetting.signatures.mSignatures != null) {
9173            // Already existing package. Make sure signatures match
9174            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
9175                    == PackageManager.SIGNATURE_MATCH;
9176            if (!match) {
9177                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
9178                        == PackageManager.SIGNATURE_MATCH;
9179            }
9180            if (!match) {
9181                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
9182                        == PackageManager.SIGNATURE_MATCH;
9183            }
9184            if (!match) {
9185                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
9186                        + pkg.packageName + " signatures do not match the "
9187                        + "previously installed version; ignoring!");
9188            }
9189        }
9190
9191        // Check for shared user signatures
9192        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
9193            // Already existing package. Make sure signatures match
9194            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
9195                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
9196            if (!match) {
9197                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
9198                        == PackageManager.SIGNATURE_MATCH;
9199            }
9200            if (!match) {
9201                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
9202                        == PackageManager.SIGNATURE_MATCH;
9203            }
9204            if (!match) {
9205                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
9206                        "Package " + pkg.packageName
9207                        + " has no signatures that match those in shared user "
9208                        + pkgSetting.sharedUser.name + "; ignoring!");
9209            }
9210        }
9211    }
9212
9213    /**
9214     * Enforces that only the system UID or root's UID can call a method exposed
9215     * via Binder.
9216     *
9217     * @param message used as message if SecurityException is thrown
9218     * @throws SecurityException if the caller is not system or root
9219     */
9220    private static final void enforceSystemOrRoot(String message) {
9221        final int uid = Binder.getCallingUid();
9222        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9223            throw new SecurityException(message);
9224        }
9225    }
9226
9227    @Override
9228    public void performFstrimIfNeeded() {
9229        enforceSystemOrRoot("Only the system can request fstrim");
9230
9231        // Before everything else, see whether we need to fstrim.
9232        try {
9233            IStorageManager sm = PackageHelper.getStorageManager();
9234            if (sm != null) {
9235                boolean doTrim = false;
9236                final long interval = android.provider.Settings.Global.getLong(
9237                        mContext.getContentResolver(),
9238                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9239                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9240                if (interval > 0) {
9241                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9242                    if (timeSinceLast > interval) {
9243                        doTrim = true;
9244                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9245                                + "; running immediately");
9246                    }
9247                }
9248                if (doTrim) {
9249                    final boolean dexOptDialogShown;
9250                    synchronized (mPackages) {
9251                        dexOptDialogShown = mDexOptDialogShown;
9252                    }
9253                    if (!isFirstBoot() && dexOptDialogShown) {
9254                        try {
9255                            ActivityManager.getService().showBootMessage(
9256                                    mContext.getResources().getString(
9257                                            R.string.android_upgrading_fstrim), true);
9258                        } catch (RemoteException e) {
9259                        }
9260                    }
9261                    sm.runMaintenance();
9262                }
9263            } else {
9264                Slog.e(TAG, "storageManager service unavailable!");
9265            }
9266        } catch (RemoteException e) {
9267            // Can't happen; StorageManagerService is local
9268        }
9269    }
9270
9271    @Override
9272    public void updatePackagesIfNeeded() {
9273        enforceSystemOrRoot("Only the system can request package update");
9274
9275        // We need to re-extract after an OTA.
9276        boolean causeUpgrade = isUpgrade();
9277
9278        // First boot or factory reset.
9279        // Note: we also handle devices that are upgrading to N right now as if it is their
9280        //       first boot, as they do not have profile data.
9281        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9282
9283        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9284        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9285
9286        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9287            return;
9288        }
9289
9290        List<PackageParser.Package> pkgs;
9291        synchronized (mPackages) {
9292            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9293        }
9294
9295        final long startTime = System.nanoTime();
9296        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9297                    getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT));
9298
9299        final int elapsedTimeSeconds =
9300                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9301
9302        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9303        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9304        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9305        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9306        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9307    }
9308
9309    /**
9310     * Performs dexopt on the set of packages in {@code packages} and returns an int array
9311     * containing statistics about the invocation. The array consists of three elements,
9312     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9313     * and {@code numberOfPackagesFailed}.
9314     */
9315    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9316            String compilerFilter) {
9317
9318        int numberOfPackagesVisited = 0;
9319        int numberOfPackagesOptimized = 0;
9320        int numberOfPackagesSkipped = 0;
9321        int numberOfPackagesFailed = 0;
9322        final int numberOfPackagesToDexopt = pkgs.size();
9323
9324        for (PackageParser.Package pkg : pkgs) {
9325            numberOfPackagesVisited++;
9326
9327            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9328                if (DEBUG_DEXOPT) {
9329                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9330                }
9331                numberOfPackagesSkipped++;
9332                continue;
9333            }
9334
9335            if (DEBUG_DEXOPT) {
9336                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9337                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9338            }
9339
9340            if (showDialog) {
9341                try {
9342                    ActivityManager.getService().showBootMessage(
9343                            mContext.getResources().getString(R.string.android_upgrading_apk,
9344                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9345                } catch (RemoteException e) {
9346                }
9347                synchronized (mPackages) {
9348                    mDexOptDialogShown = true;
9349                }
9350            }
9351
9352            // If the OTA updates a system app which was previously preopted to a non-preopted state
9353            // the app might end up being verified at runtime. That's because by default the apps
9354            // are verify-profile but for preopted apps there's no profile.
9355            // Do a hacky check to ensure that if we have no profiles (a reasonable indication
9356            // that before the OTA the app was preopted) the app gets compiled with a non-profile
9357            // filter (by default 'quicken').
9358            // Note that at this stage unused apps are already filtered.
9359            if (isSystemApp(pkg) &&
9360                    DexFile.isProfileGuidedCompilerFilter(compilerFilter) &&
9361                    !Environment.getReferenceProfile(pkg.packageName).exists()) {
9362                compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter);
9363            }
9364
9365            // checkProfiles is false to avoid merging profiles during boot which
9366            // might interfere with background compilation (b/28612421).
9367            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9368            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9369            // trade-off worth doing to save boot time work.
9370            int dexOptStatus = performDexOptTraced(pkg.packageName,
9371                    false /* checkProfiles */,
9372                    compilerFilter,
9373                    false /* force */);
9374            switch (dexOptStatus) {
9375                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9376                    numberOfPackagesOptimized++;
9377                    break;
9378                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9379                    numberOfPackagesSkipped++;
9380                    break;
9381                case PackageDexOptimizer.DEX_OPT_FAILED:
9382                    numberOfPackagesFailed++;
9383                    break;
9384                default:
9385                    Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus);
9386                    break;
9387            }
9388        }
9389
9390        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9391                numberOfPackagesFailed };
9392    }
9393
9394    @Override
9395    public void notifyPackageUse(String packageName, int reason) {
9396        synchronized (mPackages) {
9397            final int callingUid = Binder.getCallingUid();
9398            final int callingUserId = UserHandle.getUserId(callingUid);
9399            if (getInstantAppPackageName(callingUid) != null) {
9400                if (!isCallerSameApp(packageName, callingUid)) {
9401                    return;
9402                }
9403            } else {
9404                if (isInstantApp(packageName, callingUserId)) {
9405                    return;
9406                }
9407            }
9408            final PackageParser.Package p = mPackages.get(packageName);
9409            if (p == null) {
9410                return;
9411            }
9412            p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9413        }
9414    }
9415
9416    @Override
9417    public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) {
9418        int userId = UserHandle.getCallingUserId();
9419        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9420        if (ai == null) {
9421            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9422                + loadingPackageName + ", user=" + userId);
9423            return;
9424        }
9425        mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId);
9426    }
9427
9428    @Override
9429    public boolean performDexOpt(String packageName,
9430            boolean checkProfiles, int compileReason, boolean force) {
9431        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9432            return false;
9433        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9434            return false;
9435        }
9436        return performDexOptWithStatus(packageName, checkProfiles, compileReason, force) !=
9437                PackageDexOptimizer.DEX_OPT_FAILED;
9438    }
9439
9440    /**
9441     * Perform dexopt on the given package and return one of following result:
9442     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9443     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9444     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9445     */
9446    /* package */ int performDexOptWithStatus(String packageName,
9447            boolean checkProfiles, int compileReason, boolean force) {
9448        return performDexOptTraced(packageName, checkProfiles,
9449                getCompilerFilterForReason(compileReason), force);
9450    }
9451
9452    @Override
9453    public boolean performDexOptMode(String packageName,
9454            boolean checkProfiles, String targetCompilerFilter, boolean force) {
9455        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9456            return false;
9457        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9458            return false;
9459        }
9460        int dexOptStatus = performDexOptTraced(packageName, checkProfiles,
9461                targetCompilerFilter, force);
9462        return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9463    }
9464
9465    private int performDexOptTraced(String packageName,
9466                boolean checkProfiles, String targetCompilerFilter, boolean force) {
9467        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9468        try {
9469            return performDexOptInternal(packageName, checkProfiles,
9470                    targetCompilerFilter, force);
9471        } finally {
9472            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9473        }
9474    }
9475
9476    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9477    // if the package can now be considered up to date for the given filter.
9478    private int performDexOptInternal(String packageName,
9479                boolean checkProfiles, String targetCompilerFilter, boolean force) {
9480        PackageParser.Package p;
9481        synchronized (mPackages) {
9482            p = mPackages.get(packageName);
9483            if (p == null) {
9484                // Package could not be found. Report failure.
9485                return PackageDexOptimizer.DEX_OPT_FAILED;
9486            }
9487            mPackageUsage.maybeWriteAsync(mPackages);
9488            mCompilerStats.maybeWriteAsync();
9489        }
9490        long callingId = Binder.clearCallingIdentity();
9491        try {
9492            synchronized (mInstallLock) {
9493                return performDexOptInternalWithDependenciesLI(p, checkProfiles,
9494                        targetCompilerFilter, force);
9495            }
9496        } finally {
9497            Binder.restoreCallingIdentity(callingId);
9498        }
9499    }
9500
9501    public ArraySet<String> getOptimizablePackages() {
9502        ArraySet<String> pkgs = new ArraySet<String>();
9503        synchronized (mPackages) {
9504            for (PackageParser.Package p : mPackages.values()) {
9505                if (PackageDexOptimizer.canOptimizePackage(p)) {
9506                    pkgs.add(p.packageName);
9507                }
9508            }
9509        }
9510        return pkgs;
9511    }
9512
9513    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9514            boolean checkProfiles, String targetCompilerFilter,
9515            boolean force) {
9516        // Select the dex optimizer based on the force parameter.
9517        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9518        //       allocate an object here.
9519        PackageDexOptimizer pdo = force
9520                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9521                : mPackageDexOptimizer;
9522
9523        // Dexopt all dependencies first. Note: we ignore the return value and march on
9524        // on errors.
9525        // Note that we are going to call performDexOpt on those libraries as many times as
9526        // they are referenced in packages. When we do a batch of performDexOpt (for example
9527        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9528        // and the first package that uses the library will dexopt it. The
9529        // others will see that the compiled code for the library is up to date.
9530        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9531        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9532        if (!deps.isEmpty()) {
9533            for (PackageParser.Package depPackage : deps) {
9534                // TODO: Analyze and investigate if we (should) profile libraries.
9535                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9536                        false /* checkProfiles */,
9537                        targetCompilerFilter,
9538                        getOrCreateCompilerPackageStats(depPackage),
9539                        true /* isUsedByOtherApps */);
9540            }
9541        }
9542        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles,
9543                targetCompilerFilter, getOrCreateCompilerPackageStats(p),
9544                mDexManager.isUsedByOtherApps(p.packageName));
9545    }
9546
9547    // Performs dexopt on the used secondary dex files belonging to the given package.
9548    // Returns true if all dex files were process successfully (which could mean either dexopt or
9549    // skip). Returns false if any of the files caused errors.
9550    @Override
9551    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9552            boolean force) {
9553        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9554            return false;
9555        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9556            return false;
9557        }
9558        mDexManager.reconcileSecondaryDexFiles(packageName);
9559        return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force);
9560    }
9561
9562    public boolean performDexOptSecondary(String packageName, int compileReason,
9563            boolean force) {
9564        return mDexManager.dexoptSecondaryDex(packageName, compileReason, force);
9565    }
9566
9567    /**
9568     * Reconcile the information we have about the secondary dex files belonging to
9569     * {@code packagName} and the actual dex files. For all dex files that were
9570     * deleted, update the internal records and delete the generated oat files.
9571     */
9572    @Override
9573    public void reconcileSecondaryDexFiles(String packageName) {
9574        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9575            return;
9576        }
9577        mDexManager.reconcileSecondaryDexFiles(packageName);
9578    }
9579
9580    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9581    // a reference there.
9582    /*package*/ DexManager getDexManager() {
9583        return mDexManager;
9584    }
9585
9586    /**
9587     * Execute the background dexopt job immediately.
9588     */
9589    @Override
9590    public boolean runBackgroundDexoptJob() {
9591        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9592            return false;
9593        }
9594        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext);
9595    }
9596
9597    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9598        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9599                || p.usesStaticLibraries != null) {
9600            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9601            Set<String> collectedNames = new HashSet<>();
9602            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9603
9604            retValue.remove(p);
9605
9606            return retValue;
9607        } else {
9608            return Collections.emptyList();
9609        }
9610    }
9611
9612    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9613            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9614        if (!collectedNames.contains(p.packageName)) {
9615            collectedNames.add(p.packageName);
9616            collected.add(p);
9617
9618            if (p.usesLibraries != null) {
9619                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9620                        null, collected, collectedNames);
9621            }
9622            if (p.usesOptionalLibraries != null) {
9623                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9624                        null, collected, collectedNames);
9625            }
9626            if (p.usesStaticLibraries != null) {
9627                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9628                        p.usesStaticLibrariesVersions, collected, collectedNames);
9629            }
9630        }
9631    }
9632
9633    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions,
9634            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9635        final int libNameCount = libs.size();
9636        for (int i = 0; i < libNameCount; i++) {
9637            String libName = libs.get(i);
9638            int version = (versions != null && versions.length == libNameCount)
9639                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9640            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9641            if (libPkg != null) {
9642                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9643            }
9644        }
9645    }
9646
9647    private PackageParser.Package findSharedNonSystemLibrary(String name, int version) {
9648        synchronized (mPackages) {
9649            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9650            if (libEntry != null) {
9651                return mPackages.get(libEntry.apk);
9652            }
9653            return null;
9654        }
9655    }
9656
9657    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) {
9658        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9659        if (versionedLib == null) {
9660            return null;
9661        }
9662        return versionedLib.get(version);
9663    }
9664
9665    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9666        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9667                pkg.staticSharedLibName);
9668        if (versionedLib == null) {
9669            return null;
9670        }
9671        int previousLibVersion = -1;
9672        final int versionCount = versionedLib.size();
9673        for (int i = 0; i < versionCount; i++) {
9674            final int libVersion = versionedLib.keyAt(i);
9675            if (libVersion < pkg.staticSharedLibVersion) {
9676                previousLibVersion = Math.max(previousLibVersion, libVersion);
9677            }
9678        }
9679        if (previousLibVersion >= 0) {
9680            return versionedLib.get(previousLibVersion);
9681        }
9682        return null;
9683    }
9684
9685    public void shutdown() {
9686        mPackageUsage.writeNow(mPackages);
9687        mCompilerStats.writeNow();
9688    }
9689
9690    @Override
9691    public void dumpProfiles(String packageName) {
9692        PackageParser.Package pkg;
9693        synchronized (mPackages) {
9694            pkg = mPackages.get(packageName);
9695            if (pkg == null) {
9696                throw new IllegalArgumentException("Unknown package: " + packageName);
9697            }
9698        }
9699        /* Only the shell, root, or the app user should be able to dump profiles. */
9700        int callingUid = Binder.getCallingUid();
9701        if (callingUid != Process.SHELL_UID &&
9702            callingUid != Process.ROOT_UID &&
9703            callingUid != pkg.applicationInfo.uid) {
9704            throw new SecurityException("dumpProfiles");
9705        }
9706
9707        synchronized (mInstallLock) {
9708            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9709            final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
9710            try {
9711                List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly();
9712                String codePaths = TextUtils.join(";", allCodePaths);
9713                mInstaller.dumpProfiles(sharedGid, packageName, codePaths);
9714            } catch (InstallerException e) {
9715                Slog.w(TAG, "Failed to dump profiles", e);
9716            }
9717            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9718        }
9719    }
9720
9721    @Override
9722    public void forceDexOpt(String packageName) {
9723        enforceSystemOrRoot("forceDexOpt");
9724
9725        PackageParser.Package pkg;
9726        synchronized (mPackages) {
9727            pkg = mPackages.get(packageName);
9728            if (pkg == null) {
9729                throw new IllegalArgumentException("Unknown package: " + packageName);
9730            }
9731        }
9732
9733        synchronized (mInstallLock) {
9734            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9735
9736            // Whoever is calling forceDexOpt wants a compiled package.
9737            // Don't use profiles since that may cause compilation to be skipped.
9738            final int res = performDexOptInternalWithDependenciesLI(pkg,
9739                    false /* checkProfiles */, getDefaultCompilerFilter(),
9740                    true /* force */);
9741
9742            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9743            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9744                throw new IllegalStateException("Failed to dexopt: " + res);
9745            }
9746        }
9747    }
9748
9749    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9750        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9751            Slog.w(TAG, "Unable to update from " + oldPkg.name
9752                    + " to " + newPkg.packageName
9753                    + ": old package not in system partition");
9754            return false;
9755        } else if (mPackages.get(oldPkg.name) != null) {
9756            Slog.w(TAG, "Unable to update from " + oldPkg.name
9757                    + " to " + newPkg.packageName
9758                    + ": old package still exists");
9759            return false;
9760        }
9761        return true;
9762    }
9763
9764    void removeCodePathLI(File codePath) {
9765        if (codePath.isDirectory()) {
9766            try {
9767                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9768            } catch (InstallerException e) {
9769                Slog.w(TAG, "Failed to remove code path", e);
9770            }
9771        } else {
9772            codePath.delete();
9773        }
9774    }
9775
9776    private int[] resolveUserIds(int userId) {
9777        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9778    }
9779
9780    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9781        if (pkg == null) {
9782            Slog.wtf(TAG, "Package was null!", new Throwable());
9783            return;
9784        }
9785        clearAppDataLeafLIF(pkg, userId, flags);
9786        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9787        for (int i = 0; i < childCount; i++) {
9788            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9789        }
9790    }
9791
9792    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9793        final PackageSetting ps;
9794        synchronized (mPackages) {
9795            ps = mSettings.mPackages.get(pkg.packageName);
9796        }
9797        for (int realUserId : resolveUserIds(userId)) {
9798            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9799            try {
9800                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9801                        ceDataInode);
9802            } catch (InstallerException e) {
9803                Slog.w(TAG, String.valueOf(e));
9804            }
9805        }
9806    }
9807
9808    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9809        if (pkg == null) {
9810            Slog.wtf(TAG, "Package was null!", new Throwable());
9811            return;
9812        }
9813        destroyAppDataLeafLIF(pkg, userId, flags);
9814        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9815        for (int i = 0; i < childCount; i++) {
9816            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9817        }
9818    }
9819
9820    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9821        final PackageSetting ps;
9822        synchronized (mPackages) {
9823            ps = mSettings.mPackages.get(pkg.packageName);
9824        }
9825        for (int realUserId : resolveUserIds(userId)) {
9826            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9827            try {
9828                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9829                        ceDataInode);
9830            } catch (InstallerException e) {
9831                Slog.w(TAG, String.valueOf(e));
9832            }
9833            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9834        }
9835    }
9836
9837    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9838        if (pkg == null) {
9839            Slog.wtf(TAG, "Package was null!", new Throwable());
9840            return;
9841        }
9842        destroyAppProfilesLeafLIF(pkg);
9843        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9844        for (int i = 0; i < childCount; i++) {
9845            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9846        }
9847    }
9848
9849    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9850        try {
9851            mInstaller.destroyAppProfiles(pkg.packageName);
9852        } catch (InstallerException e) {
9853            Slog.w(TAG, String.valueOf(e));
9854        }
9855    }
9856
9857    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9858        if (pkg == null) {
9859            Slog.wtf(TAG, "Package was null!", new Throwable());
9860            return;
9861        }
9862        clearAppProfilesLeafLIF(pkg);
9863        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9864        for (int i = 0; i < childCount; i++) {
9865            clearAppProfilesLeafLIF(pkg.childPackages.get(i));
9866        }
9867    }
9868
9869    private void clearAppProfilesLeafLIF(PackageParser.Package pkg) {
9870        try {
9871            mInstaller.clearAppProfiles(pkg.packageName);
9872        } catch (InstallerException e) {
9873            Slog.w(TAG, String.valueOf(e));
9874        }
9875    }
9876
9877    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9878            long lastUpdateTime) {
9879        // Set parent install/update time
9880        PackageSetting ps = (PackageSetting) pkg.mExtras;
9881        if (ps != null) {
9882            ps.firstInstallTime = firstInstallTime;
9883            ps.lastUpdateTime = lastUpdateTime;
9884        }
9885        // Set children install/update time
9886        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9887        for (int i = 0; i < childCount; i++) {
9888            PackageParser.Package childPkg = pkg.childPackages.get(i);
9889            ps = (PackageSetting) childPkg.mExtras;
9890            if (ps != null) {
9891                ps.firstInstallTime = firstInstallTime;
9892                ps.lastUpdateTime = lastUpdateTime;
9893            }
9894        }
9895    }
9896
9897    private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
9898            PackageParser.Package changingLib) {
9899        if (file.path != null) {
9900            usesLibraryFiles.add(file.path);
9901            return;
9902        }
9903        PackageParser.Package p = mPackages.get(file.apk);
9904        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9905            // If we are doing this while in the middle of updating a library apk,
9906            // then we need to make sure to use that new apk for determining the
9907            // dependencies here.  (We haven't yet finished committing the new apk
9908            // to the package manager state.)
9909            if (p == null || p.packageName.equals(changingLib.packageName)) {
9910                p = changingLib;
9911            }
9912        }
9913        if (p != null) {
9914            usesLibraryFiles.addAll(p.getAllCodePaths());
9915            if (p.usesLibraryFiles != null) {
9916                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9917            }
9918        }
9919    }
9920
9921    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9922            PackageParser.Package changingLib) throws PackageManagerException {
9923        if (pkg == null) {
9924            return;
9925        }
9926        ArraySet<String> usesLibraryFiles = null;
9927        if (pkg.usesLibraries != null) {
9928            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9929                    null, null, pkg.packageName, changingLib, true, null);
9930        }
9931        if (pkg.usesStaticLibraries != null) {
9932            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9933                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9934                    pkg.packageName, changingLib, true, usesLibraryFiles);
9935        }
9936        if (pkg.usesOptionalLibraries != null) {
9937            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9938                    null, null, pkg.packageName, changingLib, false, usesLibraryFiles);
9939        }
9940        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9941            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9942        } else {
9943            pkg.usesLibraryFiles = null;
9944        }
9945    }
9946
9947    private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9948            @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests,
9949            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9950            boolean required, @Nullable ArraySet<String> outUsedLibraries)
9951            throws PackageManagerException {
9952        final int libCount = requestedLibraries.size();
9953        for (int i = 0; i < libCount; i++) {
9954            final String libName = requestedLibraries.get(i);
9955            final int libVersion = requiredVersions != null ? requiredVersions[i]
9956                    : SharedLibraryInfo.VERSION_UNDEFINED;
9957            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9958            if (libEntry == null) {
9959                if (required) {
9960                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9961                            "Package " + packageName + " requires unavailable shared library "
9962                                    + libName + "; failing!");
9963                } else if (DEBUG_SHARED_LIBRARIES) {
9964                    Slog.i(TAG, "Package " + packageName
9965                            + " desires unavailable shared library "
9966                            + libName + "; ignoring!");
9967                }
9968            } else {
9969                if (requiredVersions != null && requiredCertDigests != null) {
9970                    if (libEntry.info.getVersion() != requiredVersions[i]) {
9971                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9972                            "Package " + packageName + " requires unavailable static shared"
9973                                    + " library " + libName + " version "
9974                                    + libEntry.info.getVersion() + "; failing!");
9975                    }
9976
9977                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9978                    if (libPkg == null) {
9979                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9980                                "Package " + packageName + " requires unavailable static shared"
9981                                        + " library; failing!");
9982                    }
9983
9984                    String expectedCertDigest = requiredCertDigests[i];
9985                    String libCertDigest = PackageUtils.computeCertSha256Digest(
9986                                libPkg.mSignatures[0]);
9987                    if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) {
9988                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9989                                "Package " + packageName + " requires differently signed" +
9990                                        " static shared library; failing!");
9991                    }
9992                }
9993
9994                if (outUsedLibraries == null) {
9995                    outUsedLibraries = new ArraySet<>();
9996                }
9997                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9998            }
9999        }
10000        return outUsedLibraries;
10001    }
10002
10003    private static boolean hasString(List<String> list, List<String> which) {
10004        if (list == null) {
10005            return false;
10006        }
10007        for (int i=list.size()-1; i>=0; i--) {
10008            for (int j=which.size()-1; j>=0; j--) {
10009                if (which.get(j).equals(list.get(i))) {
10010                    return true;
10011                }
10012            }
10013        }
10014        return false;
10015    }
10016
10017    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
10018            PackageParser.Package changingPkg) {
10019        ArrayList<PackageParser.Package> res = null;
10020        for (PackageParser.Package pkg : mPackages.values()) {
10021            if (changingPkg != null
10022                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10023                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10024                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
10025                            changingPkg.staticSharedLibName)) {
10026                return null;
10027            }
10028            if (res == null) {
10029                res = new ArrayList<>();
10030            }
10031            res.add(pkg);
10032            try {
10033                updateSharedLibrariesLPr(pkg, changingPkg);
10034            } catch (PackageManagerException e) {
10035                // If a system app update or an app and a required lib missing we
10036                // delete the package and for updated system apps keep the data as
10037                // it is better for the user to reinstall than to be in an limbo
10038                // state. Also libs disappearing under an app should never happen
10039                // - just in case.
10040                if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) {
10041                    final int flags = pkg.isUpdatedSystemApp()
10042                            ? PackageManager.DELETE_KEEP_DATA : 0;
10043                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10044                            flags , null, true, null);
10045                }
10046                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10047            }
10048        }
10049        return res;
10050    }
10051
10052    /**
10053     * Derive the value of the {@code cpuAbiOverride} based on the provided
10054     * value and an optional stored value from the package settings.
10055     */
10056    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
10057        String cpuAbiOverride = null;
10058
10059        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
10060            cpuAbiOverride = null;
10061        } else if (abiOverride != null) {
10062            cpuAbiOverride = abiOverride;
10063        } else if (settings != null) {
10064            cpuAbiOverride = settings.cpuAbiOverrideString;
10065        }
10066
10067        return cpuAbiOverride;
10068    }
10069
10070    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
10071            final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user)
10072                    throws PackageManagerException {
10073        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10074        // If the package has children and this is the first dive in the function
10075        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10076        // whether all packages (parent and children) would be successfully scanned
10077        // before the actual scan since scanning mutates internal state and we want
10078        // to atomically install the package and its children.
10079        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10080            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10081                scanFlags |= SCAN_CHECK_ONLY;
10082            }
10083        } else {
10084            scanFlags &= ~SCAN_CHECK_ONLY;
10085        }
10086
10087        final PackageParser.Package scannedPkg;
10088        try {
10089            // Scan the parent
10090            scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user);
10091            // Scan the children
10092            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10093            for (int i = 0; i < childCount; i++) {
10094                PackageParser.Package childPkg = pkg.childPackages.get(i);
10095                scanPackageLI(childPkg, policyFlags,
10096                        scanFlags, currentTime, user);
10097            }
10098        } finally {
10099            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10100        }
10101
10102        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10103            return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user);
10104        }
10105
10106        return scannedPkg;
10107    }
10108
10109    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags,
10110            int scanFlags, long currentTime, @Nullable UserHandle user)
10111                    throws PackageManagerException {
10112        boolean success = false;
10113        try {
10114            final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags,
10115                    currentTime, user);
10116            success = true;
10117            return res;
10118        } finally {
10119            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10120                // DELETE_DATA_ON_FAILURES is only used by frozen paths
10121                destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10122                        StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10123                destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10124            }
10125        }
10126    }
10127
10128    /**
10129     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10130     */
10131    private static boolean apkHasCode(String fileName) {
10132        StrictJarFile jarFile = null;
10133        try {
10134            jarFile = new StrictJarFile(fileName,
10135                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10136            return jarFile.findEntry("classes.dex") != null;
10137        } catch (IOException ignore) {
10138        } finally {
10139            try {
10140                if (jarFile != null) {
10141                    jarFile.close();
10142                }
10143            } catch (IOException ignore) {}
10144        }
10145        return false;
10146    }
10147
10148    /**
10149     * Enforces code policy for the package. This ensures that if an APK has
10150     * declared hasCode="true" in its manifest that the APK actually contains
10151     * code.
10152     *
10153     * @throws PackageManagerException If bytecode could not be found when it should exist
10154     */
10155    private static void assertCodePolicy(PackageParser.Package pkg)
10156            throws PackageManagerException {
10157        final boolean shouldHaveCode =
10158                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10159        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10160            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10161                    "Package " + pkg.baseCodePath + " code is missing");
10162        }
10163
10164        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10165            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10166                final boolean splitShouldHaveCode =
10167                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10168                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10169                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10170                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10171                }
10172            }
10173        }
10174    }
10175
10176    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg,
10177            final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user)
10178                    throws PackageManagerException {
10179        if (DEBUG_PACKAGE_SCANNING) {
10180            if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10181                Log.d(TAG, "Scanning package " + pkg.packageName);
10182        }
10183
10184        applyPolicy(pkg, policyFlags);
10185
10186        assertPackageIsValid(pkg, policyFlags, scanFlags);
10187
10188        // Initialize package source and resource directories
10189        final File scanFile = new File(pkg.codePath);
10190        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10191        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10192
10193        SharedUserSetting suid = null;
10194        PackageSetting pkgSetting = null;
10195
10196        // Getting the package setting may have a side-effect, so if we
10197        // are only checking if scan would succeed, stash a copy of the
10198        // old setting to restore at the end.
10199        PackageSetting nonMutatedPs = null;
10200
10201        // We keep references to the derived CPU Abis from settings in oder to reuse
10202        // them in the case where we're not upgrading or booting for the first time.
10203        String primaryCpuAbiFromSettings = null;
10204        String secondaryCpuAbiFromSettings = null;
10205
10206        // writer
10207        synchronized (mPackages) {
10208            if (pkg.mSharedUserId != null) {
10209                // SIDE EFFECTS; may potentially allocate a new shared user
10210                suid = mSettings.getSharedUserLPw(
10211                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10212                if (DEBUG_PACKAGE_SCANNING) {
10213                    if ((policyFlags & PackageParser.PARSE_CHATTY) != 0)
10214                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
10215                                + "): packages=" + suid.packages);
10216                }
10217            }
10218
10219            // Check if we are renaming from an original package name.
10220            PackageSetting origPackage = null;
10221            String realName = null;
10222            if (pkg.mOriginalPackages != null) {
10223                // This package may need to be renamed to a previously
10224                // installed name.  Let's check on that...
10225                final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10226                if (pkg.mOriginalPackages.contains(renamed)) {
10227                    // This package had originally been installed as the
10228                    // original name, and we have already taken care of
10229                    // transitioning to the new one.  Just update the new
10230                    // one to continue using the old name.
10231                    realName = pkg.mRealPackage;
10232                    if (!pkg.packageName.equals(renamed)) {
10233                        // Callers into this function may have already taken
10234                        // care of renaming the package; only do it here if
10235                        // it is not already done.
10236                        pkg.setPackageName(renamed);
10237                    }
10238                } else {
10239                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
10240                        if ((origPackage = mSettings.getPackageLPr(
10241                                pkg.mOriginalPackages.get(i))) != null) {
10242                            // We do have the package already installed under its
10243                            // original name...  should we use it?
10244                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
10245                                // New package is not compatible with original.
10246                                origPackage = null;
10247                                continue;
10248                            } else if (origPackage.sharedUser != null) {
10249                                // Make sure uid is compatible between packages.
10250                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
10251                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
10252                                            + " to " + pkg.packageName + ": old uid "
10253                                            + origPackage.sharedUser.name
10254                                            + " differs from " + pkg.mSharedUserId);
10255                                    origPackage = null;
10256                                    continue;
10257                                }
10258                                // TODO: Add case when shared user id is added [b/28144775]
10259                            } else {
10260                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10261                                        + pkg.packageName + " to old name " + origPackage.name);
10262                            }
10263                            break;
10264                        }
10265                    }
10266                }
10267            }
10268
10269            if (mTransferedPackages.contains(pkg.packageName)) {
10270                Slog.w(TAG, "Package " + pkg.packageName
10271                        + " was transferred to another, but its .apk remains");
10272            }
10273
10274            // See comments in nonMutatedPs declaration
10275            if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10276                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10277                if (foundPs != null) {
10278                    nonMutatedPs = new PackageSetting(foundPs);
10279                }
10280            }
10281
10282            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) {
10283                PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName);
10284                if (foundPs != null) {
10285                    primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString;
10286                    secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString;
10287                }
10288            }
10289
10290            pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10291            if (pkgSetting != null && pkgSetting.sharedUser != suid) {
10292                PackageManagerService.reportSettingsProblem(Log.WARN,
10293                        "Package " + pkg.packageName + " shared user changed from "
10294                                + (pkgSetting.sharedUser != null
10295                                        ? pkgSetting.sharedUser.name : "<nothing>")
10296                                + " to "
10297                                + (suid != null ? suid.name : "<nothing>")
10298                                + "; replacing with new");
10299                pkgSetting = null;
10300            }
10301            final PackageSetting oldPkgSetting =
10302                    pkgSetting == null ? null : new PackageSetting(pkgSetting);
10303            final PackageSetting disabledPkgSetting =
10304                    mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10305
10306            String[] usesStaticLibraries = null;
10307            if (pkg.usesStaticLibraries != null) {
10308                usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10309                pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10310            }
10311
10312            if (pkgSetting == null) {
10313                final String parentPackageName = (pkg.parentPackage != null)
10314                        ? pkg.parentPackage.packageName : null;
10315                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10316                // REMOVE SharedUserSetting from method; update in a separate call
10317                pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage,
10318                        disabledPkgSetting, realName, suid, destCodeFile, destResourceFile,
10319                        pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi,
10320                        pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode,
10321                        pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user,
10322                        true /*allowInstall*/, instantApp, parentPackageName,
10323                        pkg.getChildPackageNames(), UserManagerService.getInstance(),
10324                        usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10325                // SIDE EFFECTS; updates system state; move elsewhere
10326                if (origPackage != null) {
10327                    mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name);
10328                }
10329                mSettings.addUserToSettingLPw(pkgSetting);
10330            } else {
10331                // REMOVE SharedUserSetting from method; update in a separate call.
10332                //
10333                // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10334                // secondaryCpuAbi are not known at this point so we always update them
10335                // to null here, only to reset them at a later point.
10336                Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile,
10337                        pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi,
10338                        pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags,
10339                        pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(),
10340                        UserManagerService.getInstance(), usesStaticLibraries,
10341                        pkg.usesStaticLibrariesVersions);
10342            }
10343            // SIDE EFFECTS; persists system state to files on disk; move elsewhere
10344            mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10345
10346            // SIDE EFFECTS; modifies system state; move elsewhere
10347            if (pkgSetting.origPackage != null) {
10348                // If we are first transitioning from an original package,
10349                // fix up the new package's name now.  We need to do this after
10350                // looking up the package under its new name, so getPackageLP
10351                // can take care of fiddling things correctly.
10352                pkg.setPackageName(origPackage.name);
10353
10354                // File a report about this.
10355                String msg = "New package " + pkgSetting.realName
10356                        + " renamed to replace old package " + pkgSetting.name;
10357                reportSettingsProblem(Log.WARN, msg);
10358
10359                // Make a note of it.
10360                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10361                    mTransferedPackages.add(origPackage.name);
10362                }
10363
10364                // No longer need to retain this.
10365                pkgSetting.origPackage = null;
10366            }
10367
10368            // SIDE EFFECTS; modifies system state; move elsewhere
10369            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) {
10370                // Make a note of it.
10371                mTransferedPackages.add(pkg.packageName);
10372            }
10373
10374            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
10375                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10376            }
10377
10378            if ((scanFlags & SCAN_BOOTING) == 0
10379                    && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10380                // Check all shared libraries and map to their actual file path.
10381                // We only do this here for apps not on a system dir, because those
10382                // are the only ones that can fail an install due to this.  We
10383                // will take care of the system apps by updating all of their
10384                // library paths after the scan is done. Also during the initial
10385                // scan don't update any libs as we do this wholesale after all
10386                // apps are scanned to avoid dependency based scanning.
10387                updateSharedLibrariesLPr(pkg, null);
10388            }
10389
10390            if (mFoundPolicyFile) {
10391                SELinuxMMAC.assignSeInfoValue(pkg);
10392            }
10393            pkg.applicationInfo.uid = pkgSetting.appId;
10394            pkg.mExtras = pkgSetting;
10395
10396
10397            // Static shared libs have same package with different versions where
10398            // we internally use a synthetic package name to allow multiple versions
10399            // of the same package, therefore we need to compare signatures against
10400            // the package setting for the latest library version.
10401            PackageSetting signatureCheckPs = pkgSetting;
10402            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10403                SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10404                if (libraryEntry != null) {
10405                    signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10406                }
10407            }
10408
10409            if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
10410                if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
10411                    // We just determined the app is signed correctly, so bring
10412                    // over the latest parsed certs.
10413                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10414                } else {
10415                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10416                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10417                                "Package " + pkg.packageName + " upgrade keys do not match the "
10418                                + "previously installed version");
10419                    } else {
10420                        pkgSetting.signatures.mSignatures = pkg.mSignatures;
10421                        String msg = "System package " + pkg.packageName
10422                                + " signature changed; retaining data.";
10423                        reportSettingsProblem(Log.WARN, msg);
10424                    }
10425                }
10426            } else {
10427                try {
10428                    // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService
10429                    verifySignaturesLP(signatureCheckPs, pkg);
10430                    // We just determined the app is signed correctly, so bring
10431                    // over the latest parsed certs.
10432                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10433                } catch (PackageManagerException e) {
10434                    if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10435                        throw e;
10436                    }
10437                    // The signature has changed, but this package is in the system
10438                    // image...  let's recover!
10439                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
10440                    // However...  if this package is part of a shared user, but it
10441                    // doesn't match the signature of the shared user, let's fail.
10442                    // What this means is that you can't change the signatures
10443                    // associated with an overall shared user, which doesn't seem all
10444                    // that unreasonable.
10445                    if (signatureCheckPs.sharedUser != null) {
10446                        if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures,
10447                                pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10448                            throw new PackageManagerException(
10449                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10450                                    "Signature mismatch for shared user: "
10451                                            + pkgSetting.sharedUser);
10452                        }
10453                    }
10454                    // File a report about this.
10455                    String msg = "System package " + pkg.packageName
10456                            + " signature changed; retaining data.";
10457                    reportSettingsProblem(Log.WARN, msg);
10458                }
10459            }
10460
10461            if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10462                // This package wants to adopt ownership of permissions from
10463                // another package.
10464                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10465                    final String origName = pkg.mAdoptPermissions.get(i);
10466                    final PackageSetting orig = mSettings.getPackageLPr(origName);
10467                    if (orig != null) {
10468                        if (verifyPackageUpdateLPr(orig, pkg)) {
10469                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
10470                                    + pkg.packageName);
10471                            // SIDE EFFECTS; updates permissions system state; move elsewhere
10472                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
10473                        }
10474                    }
10475                }
10476            }
10477        }
10478
10479        pkg.applicationInfo.processName = fixProcessName(
10480                pkg.applicationInfo.packageName,
10481                pkg.applicationInfo.processName);
10482
10483        if (pkg != mPlatformPackage) {
10484            // Get all of our default paths setup
10485            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10486        }
10487
10488        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10489
10490        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10491            if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) {
10492                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10493                derivePackageAbi(
10494                        pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir);
10495                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10496
10497                // Some system apps still use directory structure for native libraries
10498                // in which case we might end up not detecting abi solely based on apk
10499                // structure. Try to detect abi based on directory structure.
10500                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10501                        pkg.applicationInfo.primaryCpuAbi == null) {
10502                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10503                    setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10504                }
10505            } else {
10506                // This is not a first boot or an upgrade, don't bother deriving the
10507                // ABI during the scan. Instead, trust the value that was stored in the
10508                // package setting.
10509                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10510                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10511
10512                setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10513
10514                if (DEBUG_ABI_SELECTION) {
10515                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10516                        pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10517                        pkg.applicationInfo.secondaryCpuAbi);
10518                }
10519            }
10520        } else {
10521            if ((scanFlags & SCAN_MOVE) != 0) {
10522                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10523                // but we already have this packages package info in the PackageSetting. We just
10524                // use that and derive the native library path based on the new codepath.
10525                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10526                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10527            }
10528
10529            // Set native library paths again. For moves, the path will be updated based on the
10530            // ABIs we've determined above. For non-moves, the path will be updated based on the
10531            // ABIs we determined during compilation, but the path will depend on the final
10532            // package path (after the rename away from the stage path).
10533            setNativeLibraryPaths(pkg, mAppLib32InstallDir);
10534        }
10535
10536        // This is a special case for the "system" package, where the ABI is
10537        // dictated by the zygote configuration (and init.rc). We should keep track
10538        // of this ABI so that we can deal with "normal" applications that run under
10539        // the same UID correctly.
10540        if (mPlatformPackage == pkg) {
10541            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10542                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10543        }
10544
10545        // If there's a mismatch between the abi-override in the package setting
10546        // and the abiOverride specified for the install. Warn about this because we
10547        // would've already compiled the app without taking the package setting into
10548        // account.
10549        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10550            if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) {
10551                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10552                        " for package " + pkg.packageName);
10553            }
10554        }
10555
10556        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10557        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10558        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10559
10560        // Copy the derived override back to the parsed package, so that we can
10561        // update the package settings accordingly.
10562        pkg.cpuAbiOverride = cpuAbiOverride;
10563
10564        if (DEBUG_ABI_SELECTION) {
10565            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
10566                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10567                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10568        }
10569
10570        // Push the derived path down into PackageSettings so we know what to
10571        // clean up at uninstall time.
10572        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10573
10574        if (DEBUG_ABI_SELECTION) {
10575            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10576                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10577                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10578        }
10579
10580        // SIDE EFFECTS; removes DEX files from disk; move elsewhere
10581        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10582            // We don't do this here during boot because we can do it all
10583            // at once after scanning all existing packages.
10584            //
10585            // We also do this *before* we perform dexopt on this package, so that
10586            // we can avoid redundant dexopts, and also to make sure we've got the
10587            // code and package path correct.
10588            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10589        }
10590
10591        if (mFactoryTest && pkg.requestedPermissions.contains(
10592                android.Manifest.permission.FACTORY_TEST)) {
10593            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10594        }
10595
10596        if (isSystemApp(pkg)) {
10597            pkgSetting.isOrphaned = true;
10598        }
10599
10600        // Take care of first install / last update times.
10601        final long scanFileTime = getLastModifiedTime(pkg, scanFile);
10602        if (currentTime != 0) {
10603            if (pkgSetting.firstInstallTime == 0) {
10604                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10605            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10606                pkgSetting.lastUpdateTime = currentTime;
10607            }
10608        } else if (pkgSetting.firstInstallTime == 0) {
10609            // We need *something*.  Take time time stamp of the file.
10610            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10611        } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10612            if (scanFileTime != pkgSetting.timeStamp) {
10613                // A package on the system image has changed; consider this
10614                // to be an update.
10615                pkgSetting.lastUpdateTime = scanFileTime;
10616            }
10617        }
10618        pkgSetting.setTimeStamp(scanFileTime);
10619
10620        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10621            if (nonMutatedPs != null) {
10622                synchronized (mPackages) {
10623                    mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs);
10624                }
10625            }
10626        } else {
10627            final int userId = user == null ? 0 : user.getIdentifier();
10628            // Modify state for the given package setting
10629            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10630                    (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10631            if (pkgSetting.getInstantApp(userId)) {
10632                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10633            }
10634        }
10635        return pkg;
10636    }
10637
10638    /**
10639     * Applies policy to the parsed package based upon the given policy flags.
10640     * Ensures the package is in a good state.
10641     * <p>
10642     * Implementation detail: This method must NOT have any side effect. It would
10643     * ideally be static, but, it requires locks to read system state.
10644     */
10645    private void applyPolicy(PackageParser.Package pkg, int policyFlags) {
10646        if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
10647            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10648            if (pkg.applicationInfo.isDirectBootAware()) {
10649                // we're direct boot aware; set for all components
10650                for (PackageParser.Service s : pkg.services) {
10651                    s.info.encryptionAware = s.info.directBootAware = true;
10652                }
10653                for (PackageParser.Provider p : pkg.providers) {
10654                    p.info.encryptionAware = p.info.directBootAware = true;
10655                }
10656                for (PackageParser.Activity a : pkg.activities) {
10657                    a.info.encryptionAware = a.info.directBootAware = true;
10658                }
10659                for (PackageParser.Activity r : pkg.receivers) {
10660                    r.info.encryptionAware = r.info.directBootAware = true;
10661                }
10662            }
10663        } else {
10664            // Only allow system apps to be flagged as core apps.
10665            pkg.coreApp = false;
10666            // clear flags not applicable to regular apps
10667            pkg.applicationInfo.privateFlags &=
10668                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10669            pkg.applicationInfo.privateFlags &=
10670                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10671        }
10672        pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0;
10673
10674        if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
10675            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10676        }
10677
10678        if (!isSystemApp(pkg)) {
10679            // Only system apps can use these features.
10680            pkg.mOriginalPackages = null;
10681            pkg.mRealPackage = null;
10682            pkg.mAdoptPermissions = null;
10683        }
10684    }
10685
10686    /**
10687     * Asserts the parsed package is valid according to the given policy. If the
10688     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10689     * <p>
10690     * Implementation detail: This method must NOT have any side effects. It would
10691     * ideally be static, but, it requires locks to read system state.
10692     *
10693     * @throws PackageManagerException If the package fails any of the validation checks
10694     */
10695    private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags)
10696            throws PackageManagerException {
10697        if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10698            assertCodePolicy(pkg);
10699        }
10700
10701        if (pkg.applicationInfo.getCodePath() == null ||
10702                pkg.applicationInfo.getResourcePath() == null) {
10703            // Bail out. The resource and code paths haven't been set.
10704            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10705                    "Code and resource paths haven't been set correctly");
10706        }
10707
10708        // Make sure we're not adding any bogus keyset info
10709        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10710        ksms.assertScannedPackageValid(pkg);
10711
10712        synchronized (mPackages) {
10713            // The special "android" package can only be defined once
10714            if (pkg.packageName.equals("android")) {
10715                if (mAndroidApplication != null) {
10716                    Slog.w(TAG, "*************************************************");
10717                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10718                    Slog.w(TAG, " codePath=" + pkg.codePath);
10719                    Slog.w(TAG, "*************************************************");
10720                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10721                            "Core android package being redefined.  Skipping.");
10722                }
10723            }
10724
10725            // A package name must be unique; don't allow duplicates
10726            if (mPackages.containsKey(pkg.packageName)) {
10727                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10728                        "Application package " + pkg.packageName
10729                        + " already installed.  Skipping duplicate.");
10730            }
10731
10732            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10733                // Static libs have a synthetic package name containing the version
10734                // but we still want the base name to be unique.
10735                if (mPackages.containsKey(pkg.manifestPackageName)) {
10736                    throw new PackageManagerException(
10737                            "Duplicate static shared lib provider package");
10738                }
10739
10740                // Static shared libraries should have at least O target SDK
10741                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10742                    throw new PackageManagerException(
10743                            "Packages declaring static-shared libs must target O SDK or higher");
10744                }
10745
10746                // Package declaring static a shared lib cannot be instant apps
10747                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10748                    throw new PackageManagerException(
10749                            "Packages declaring static-shared libs cannot be instant apps");
10750                }
10751
10752                // Package declaring static a shared lib cannot be renamed since the package
10753                // name is synthetic and apps can't code around package manager internals.
10754                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10755                    throw new PackageManagerException(
10756                            "Packages declaring static-shared libs cannot be renamed");
10757                }
10758
10759                // Package declaring static a shared lib cannot declare child packages
10760                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10761                    throw new PackageManagerException(
10762                            "Packages declaring static-shared libs cannot have child packages");
10763                }
10764
10765                // Package declaring static a shared lib cannot declare dynamic libs
10766                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10767                    throw new PackageManagerException(
10768                            "Packages declaring static-shared libs cannot declare dynamic libs");
10769                }
10770
10771                // Package declaring static a shared lib cannot declare shared users
10772                if (pkg.mSharedUserId != null) {
10773                    throw new PackageManagerException(
10774                            "Packages declaring static-shared libs cannot declare shared users");
10775                }
10776
10777                // Static shared libs cannot declare activities
10778                if (!pkg.activities.isEmpty()) {
10779                    throw new PackageManagerException(
10780                            "Static shared libs cannot declare activities");
10781                }
10782
10783                // Static shared libs cannot declare services
10784                if (!pkg.services.isEmpty()) {
10785                    throw new PackageManagerException(
10786                            "Static shared libs cannot declare services");
10787                }
10788
10789                // Static shared libs cannot declare providers
10790                if (!pkg.providers.isEmpty()) {
10791                    throw new PackageManagerException(
10792                            "Static shared libs cannot declare content providers");
10793                }
10794
10795                // Static shared libs cannot declare receivers
10796                if (!pkg.receivers.isEmpty()) {
10797                    throw new PackageManagerException(
10798                            "Static shared libs cannot declare broadcast receivers");
10799                }
10800
10801                // Static shared libs cannot declare permission groups
10802                if (!pkg.permissionGroups.isEmpty()) {
10803                    throw new PackageManagerException(
10804                            "Static shared libs cannot declare permission groups");
10805                }
10806
10807                // Static shared libs cannot declare permissions
10808                if (!pkg.permissions.isEmpty()) {
10809                    throw new PackageManagerException(
10810                            "Static shared libs cannot declare permissions");
10811                }
10812
10813                // Static shared libs cannot declare protected broadcasts
10814                if (pkg.protectedBroadcasts != null) {
10815                    throw new PackageManagerException(
10816                            "Static shared libs cannot declare protected broadcasts");
10817                }
10818
10819                // Static shared libs cannot be overlay targets
10820                if (pkg.mOverlayTarget != null) {
10821                    throw new PackageManagerException(
10822                            "Static shared libs cannot be overlay targets");
10823                }
10824
10825                // The version codes must be ordered as lib versions
10826                int minVersionCode = Integer.MIN_VALUE;
10827                int maxVersionCode = Integer.MAX_VALUE;
10828
10829                SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10830                        pkg.staticSharedLibName);
10831                if (versionedLib != null) {
10832                    final int versionCount = versionedLib.size();
10833                    for (int i = 0; i < versionCount; i++) {
10834                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10835                        final int libVersionCode = libInfo.getDeclaringPackage()
10836                                .getVersionCode();
10837                        if (libInfo.getVersion() <  pkg.staticSharedLibVersion) {
10838                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10839                        } else if (libInfo.getVersion() >  pkg.staticSharedLibVersion) {
10840                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10841                        } else {
10842                            minVersionCode = maxVersionCode = libVersionCode;
10843                            break;
10844                        }
10845                    }
10846                }
10847                if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) {
10848                    throw new PackageManagerException("Static shared"
10849                            + " lib version codes must be ordered as lib versions");
10850                }
10851            }
10852
10853            // Only privileged apps and updated privileged apps can add child packages.
10854            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10855                if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) {
10856                    throw new PackageManagerException("Only privileged apps can add child "
10857                            + "packages. Ignoring package " + pkg.packageName);
10858                }
10859                final int childCount = pkg.childPackages.size();
10860                for (int i = 0; i < childCount; i++) {
10861                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10862                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10863                            childPkg.packageName)) {
10864                        throw new PackageManagerException("Can't override child of "
10865                                + "another disabled app. Ignoring package " + pkg.packageName);
10866                    }
10867                }
10868            }
10869
10870            // If we're only installing presumed-existing packages, require that the
10871            // scanned APK is both already known and at the path previously established
10872            // for it.  Previously unknown packages we pick up normally, but if we have an
10873            // a priori expectation about this package's install presence, enforce it.
10874            // With a singular exception for new system packages. When an OTA contains
10875            // a new system package, we allow the codepath to change from a system location
10876            // to the user-installed location. If we don't allow this change, any newer,
10877            // user-installed version of the application will be ignored.
10878            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10879                if (mExpectingBetter.containsKey(pkg.packageName)) {
10880                    logCriticalInfo(Log.WARN,
10881                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10882                } else {
10883                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10884                    if (known != null) {
10885                        if (DEBUG_PACKAGE_SCANNING) {
10886                            Log.d(TAG, "Examining " + pkg.codePath
10887                                    + " and requiring known paths " + known.codePathString
10888                                    + " & " + known.resourcePathString);
10889                        }
10890                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10891                                || !pkg.applicationInfo.getResourcePath().equals(
10892                                        known.resourcePathString)) {
10893                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10894                                    "Application package " + pkg.packageName
10895                                    + " found at " + pkg.applicationInfo.getCodePath()
10896                                    + " but expected at " + known.codePathString
10897                                    + "; ignoring.");
10898                        }
10899                    }
10900                }
10901            }
10902
10903            // Verify that this new package doesn't have any content providers
10904            // that conflict with existing packages.  Only do this if the
10905            // package isn't already installed, since we don't want to break
10906            // things that are installed.
10907            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10908                final int N = pkg.providers.size();
10909                int i;
10910                for (i=0; i<N; i++) {
10911                    PackageParser.Provider p = pkg.providers.get(i);
10912                    if (p.info.authority != null) {
10913                        String names[] = p.info.authority.split(";");
10914                        for (int j = 0; j < names.length; j++) {
10915                            if (mProvidersByAuthority.containsKey(names[j])) {
10916                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10917                                final String otherPackageName =
10918                                        ((other != null && other.getComponentName() != null) ?
10919                                                other.getComponentName().getPackageName() : "?");
10920                                throw new PackageManagerException(
10921                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
10922                                        "Can't install because provider name " + names[j]
10923                                                + " (in package " + pkg.applicationInfo.packageName
10924                                                + ") is already used by " + otherPackageName);
10925                            }
10926                        }
10927                    }
10928                }
10929            }
10930        }
10931    }
10932
10933    private boolean addSharedLibraryLPw(String path, String apk, String name, int version,
10934            int type, String declaringPackageName, int declaringVersionCode) {
10935        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10936        if (versionedLib == null) {
10937            versionedLib = new SparseArray<>();
10938            mSharedLibraries.put(name, versionedLib);
10939            if (type == SharedLibraryInfo.TYPE_STATIC) {
10940                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
10941            }
10942        } else if (versionedLib.indexOfKey(version) >= 0) {
10943            return false;
10944        }
10945        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
10946                version, type, declaringPackageName, declaringVersionCode);
10947        versionedLib.put(version, libEntry);
10948        return true;
10949    }
10950
10951    private boolean removeSharedLibraryLPw(String name, int version) {
10952        SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
10953        if (versionedLib == null) {
10954            return false;
10955        }
10956        final int libIdx = versionedLib.indexOfKey(version);
10957        if (libIdx < 0) {
10958            return false;
10959        }
10960        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
10961        versionedLib.remove(version);
10962        if (versionedLib.size() <= 0) {
10963            mSharedLibraries.remove(name);
10964            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
10965                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
10966                        .getPackageName());
10967            }
10968        }
10969        return true;
10970    }
10971
10972    /**
10973     * Adds a scanned package to the system. When this method is finished, the package will
10974     * be available for query, resolution, etc...
10975     */
10976    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
10977            UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException {
10978        final String pkgName = pkg.packageName;
10979        if (mCustomResolverComponentName != null &&
10980                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
10981            setUpCustomResolverActivity(pkg);
10982        }
10983
10984        if (pkg.packageName.equals("android")) {
10985            synchronized (mPackages) {
10986                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10987                    // Set up information for our fall-back user intent resolution activity.
10988                    mPlatformPackage = pkg;
10989                    pkg.mVersionCode = mSdkVersion;
10990                    mAndroidApplication = pkg.applicationInfo;
10991                    if (!mResolverReplaced) {
10992                        mResolveActivity.applicationInfo = mAndroidApplication;
10993                        mResolveActivity.name = ResolverActivity.class.getName();
10994                        mResolveActivity.packageName = mAndroidApplication.packageName;
10995                        mResolveActivity.processName = "system:ui";
10996                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
10997                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
10998                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
10999                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11000                        mResolveActivity.exported = true;
11001                        mResolveActivity.enabled = true;
11002                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11003                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11004                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11005                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11006                                | ActivityInfo.CONFIG_ORIENTATION
11007                                | ActivityInfo.CONFIG_KEYBOARD
11008                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11009                        mResolveInfo.activityInfo = mResolveActivity;
11010                        mResolveInfo.priority = 0;
11011                        mResolveInfo.preferredOrder = 0;
11012                        mResolveInfo.match = 0;
11013                        mResolveComponentName = new ComponentName(
11014                                mAndroidApplication.packageName, mResolveActivity.name);
11015                    }
11016                }
11017            }
11018        }
11019
11020        ArrayList<PackageParser.Package> clientLibPkgs = null;
11021        // writer
11022        synchronized (mPackages) {
11023            boolean hasStaticSharedLibs = false;
11024
11025            // Any app can add new static shared libraries
11026            if (pkg.staticSharedLibName != null) {
11027                // Static shared libs don't allow renaming as they have synthetic package
11028                // names to allow install of multiple versions, so use name from manifest.
11029                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11030                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11031                        pkg.manifestPackageName, pkg.mVersionCode)) {
11032                    hasStaticSharedLibs = true;
11033                } else {
11034                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11035                                + pkg.staticSharedLibName + " already exists; skipping");
11036                }
11037                // Static shared libs cannot be updated once installed since they
11038                // use synthetic package name which includes the version code, so
11039                // not need to update other packages's shared lib dependencies.
11040            }
11041
11042            if (!hasStaticSharedLibs
11043                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11044                // Only system apps can add new dynamic shared libraries.
11045                if (pkg.libraryNames != null) {
11046                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11047                        String name = pkg.libraryNames.get(i);
11048                        boolean allowed = false;
11049                        if (pkg.isUpdatedSystemApp()) {
11050                            // New library entries can only be added through the
11051                            // system image.  This is important to get rid of a lot
11052                            // of nasty edge cases: for example if we allowed a non-
11053                            // system update of the app to add a library, then uninstalling
11054                            // the update would make the library go away, and assumptions
11055                            // we made such as through app install filtering would now
11056                            // have allowed apps on the device which aren't compatible
11057                            // with it.  Better to just have the restriction here, be
11058                            // conservative, and create many fewer cases that can negatively
11059                            // impact the user experience.
11060                            final PackageSetting sysPs = mSettings
11061                                    .getDisabledSystemPkgLPr(pkg.packageName);
11062                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11063                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11064                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11065                                        allowed = true;
11066                                        break;
11067                                    }
11068                                }
11069                            }
11070                        } else {
11071                            allowed = true;
11072                        }
11073                        if (allowed) {
11074                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11075                                    SharedLibraryInfo.VERSION_UNDEFINED,
11076                                    SharedLibraryInfo.TYPE_DYNAMIC,
11077                                    pkg.packageName, pkg.mVersionCode)) {
11078                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11079                                        + name + " already exists; skipping");
11080                            }
11081                        } else {
11082                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11083                                    + name + " that is not declared on system image; skipping");
11084                        }
11085                    }
11086
11087                    if ((scanFlags & SCAN_BOOTING) == 0) {
11088                        // If we are not booting, we need to update any applications
11089                        // that are clients of our shared library.  If we are booting,
11090                        // this will all be done once the scan is complete.
11091                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11092                    }
11093                }
11094            }
11095        }
11096
11097        if ((scanFlags & SCAN_BOOTING) != 0) {
11098            // No apps can run during boot scan, so they don't need to be frozen
11099        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11100            // Caller asked to not kill app, so it's probably not frozen
11101        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11102            // Caller asked us to ignore frozen check for some reason; they
11103            // probably didn't know the package name
11104        } else {
11105            // We're doing major surgery on this package, so it better be frozen
11106            // right now to keep it from launching
11107            checkPackageFrozen(pkgName);
11108        }
11109
11110        // Also need to kill any apps that are dependent on the library.
11111        if (clientLibPkgs != null) {
11112            for (int i=0; i<clientLibPkgs.size(); i++) {
11113                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11114                killApplication(clientPkg.applicationInfo.packageName,
11115                        clientPkg.applicationInfo.uid, "update lib");
11116            }
11117        }
11118
11119        // writer
11120        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11121
11122        synchronized (mPackages) {
11123            // We don't expect installation to fail beyond this point
11124
11125            // Add the new setting to mSettings
11126            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11127            // Add the new setting to mPackages
11128            mPackages.put(pkg.applicationInfo.packageName, pkg);
11129            // Make sure we don't accidentally delete its data.
11130            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11131            while (iter.hasNext()) {
11132                PackageCleanItem item = iter.next();
11133                if (pkgName.equals(item.packageName)) {
11134                    iter.remove();
11135                }
11136            }
11137
11138            // Add the package's KeySets to the global KeySetManagerService
11139            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11140            ksms.addScannedPackageLPw(pkg);
11141
11142            int N = pkg.providers.size();
11143            StringBuilder r = null;
11144            int i;
11145            for (i=0; i<N; i++) {
11146                PackageParser.Provider p = pkg.providers.get(i);
11147                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11148                        p.info.processName);
11149                mProviders.addProvider(p);
11150                p.syncable = p.info.isSyncable;
11151                if (p.info.authority != null) {
11152                    String names[] = p.info.authority.split(";");
11153                    p.info.authority = null;
11154                    for (int j = 0; j < names.length; j++) {
11155                        if (j == 1 && p.syncable) {
11156                            // We only want the first authority for a provider to possibly be
11157                            // syncable, so if we already added this provider using a different
11158                            // authority clear the syncable flag. We copy the provider before
11159                            // changing it because the mProviders object contains a reference
11160                            // to a provider that we don't want to change.
11161                            // Only do this for the second authority since the resulting provider
11162                            // object can be the same for all future authorities for this provider.
11163                            p = new PackageParser.Provider(p);
11164                            p.syncable = false;
11165                        }
11166                        if (!mProvidersByAuthority.containsKey(names[j])) {
11167                            mProvidersByAuthority.put(names[j], p);
11168                            if (p.info.authority == null) {
11169                                p.info.authority = names[j];
11170                            } else {
11171                                p.info.authority = p.info.authority + ";" + names[j];
11172                            }
11173                            if (DEBUG_PACKAGE_SCANNING) {
11174                                if (chatty)
11175                                    Log.d(TAG, "Registered content provider: " + names[j]
11176                                            + ", className = " + p.info.name + ", isSyncable = "
11177                                            + p.info.isSyncable);
11178                            }
11179                        } else {
11180                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11181                            Slog.w(TAG, "Skipping provider name " + names[j] +
11182                                    " (in package " + pkg.applicationInfo.packageName +
11183                                    "): name already used by "
11184                                    + ((other != null && other.getComponentName() != null)
11185                                            ? other.getComponentName().getPackageName() : "?"));
11186                        }
11187                    }
11188                }
11189                if (chatty) {
11190                    if (r == null) {
11191                        r = new StringBuilder(256);
11192                    } else {
11193                        r.append(' ');
11194                    }
11195                    r.append(p.info.name);
11196                }
11197            }
11198            if (r != null) {
11199                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11200            }
11201
11202            N = pkg.services.size();
11203            r = null;
11204            for (i=0; i<N; i++) {
11205                PackageParser.Service s = pkg.services.get(i);
11206                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11207                        s.info.processName);
11208                mServices.addService(s);
11209                if (chatty) {
11210                    if (r == null) {
11211                        r = new StringBuilder(256);
11212                    } else {
11213                        r.append(' ');
11214                    }
11215                    r.append(s.info.name);
11216                }
11217            }
11218            if (r != null) {
11219                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11220            }
11221
11222            N = pkg.receivers.size();
11223            r = null;
11224            for (i=0; i<N; i++) {
11225                PackageParser.Activity a = pkg.receivers.get(i);
11226                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11227                        a.info.processName);
11228                mReceivers.addActivity(a, "receiver");
11229                if (chatty) {
11230                    if (r == null) {
11231                        r = new StringBuilder(256);
11232                    } else {
11233                        r.append(' ');
11234                    }
11235                    r.append(a.info.name);
11236                }
11237            }
11238            if (r != null) {
11239                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11240            }
11241
11242            N = pkg.activities.size();
11243            r = null;
11244            for (i=0; i<N; i++) {
11245                PackageParser.Activity a = pkg.activities.get(i);
11246                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11247                        a.info.processName);
11248                mActivities.addActivity(a, "activity");
11249                if (chatty) {
11250                    if (r == null) {
11251                        r = new StringBuilder(256);
11252                    } else {
11253                        r.append(' ');
11254                    }
11255                    r.append(a.info.name);
11256                }
11257            }
11258            if (r != null) {
11259                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11260            }
11261
11262            N = pkg.permissionGroups.size();
11263            r = null;
11264            for (i=0; i<N; i++) {
11265                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
11266                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
11267                final String curPackageName = cur == null ? null : cur.info.packageName;
11268                // Dont allow ephemeral apps to define new permission groups.
11269                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11270                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11271                            + pg.info.packageName
11272                            + " ignored: instant apps cannot define new permission groups.");
11273                    continue;
11274                }
11275                final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName);
11276                if (cur == null || isPackageUpdate) {
11277                    mPermissionGroups.put(pg.info.name, pg);
11278                    if (chatty) {
11279                        if (r == null) {
11280                            r = new StringBuilder(256);
11281                        } else {
11282                            r.append(' ');
11283                        }
11284                        if (isPackageUpdate) {
11285                            r.append("UPD:");
11286                        }
11287                        r.append(pg.info.name);
11288                    }
11289                } else {
11290                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
11291                            + pg.info.packageName + " ignored: original from "
11292                            + cur.info.packageName);
11293                    if (chatty) {
11294                        if (r == null) {
11295                            r = new StringBuilder(256);
11296                        } else {
11297                            r.append(' ');
11298                        }
11299                        r.append("DUP:");
11300                        r.append(pg.info.name);
11301                    }
11302                }
11303            }
11304            if (r != null) {
11305                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
11306            }
11307
11308            N = pkg.permissions.size();
11309            r = null;
11310            for (i=0; i<N; i++) {
11311                PackageParser.Permission p = pkg.permissions.get(i);
11312
11313                // Dont allow ephemeral apps to define new permissions.
11314                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11315                    Slog.w(TAG, "Permission " + p.info.name + " from package "
11316                            + p.info.packageName
11317                            + " ignored: instant apps cannot define new permissions.");
11318                    continue;
11319                }
11320
11321                // Assume by default that we did not install this permission into the system.
11322                p.info.flags &= ~PermissionInfo.FLAG_INSTALLED;
11323
11324                // Now that permission groups have a special meaning, we ignore permission
11325                // groups for legacy apps to prevent unexpected behavior. In particular,
11326                // permissions for one app being granted to someone just because they happen
11327                // to be in a group defined by another app (before this had no implications).
11328                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
11329                    p.group = mPermissionGroups.get(p.info.group);
11330                    // Warn for a permission in an unknown group.
11331                    if (DEBUG_PERMISSIONS && p.info.group != null && p.group == null) {
11332                        Slog.i(TAG, "Permission " + p.info.name + " from package "
11333                                + p.info.packageName + " in an unknown group " + p.info.group);
11334                    }
11335                }
11336
11337                ArrayMap<String, BasePermission> permissionMap =
11338                        p.tree ? mSettings.mPermissionTrees
11339                                : mSettings.mPermissions;
11340                BasePermission bp = permissionMap.get(p.info.name);
11341
11342                // Allow system apps to redefine non-system permissions
11343                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
11344                    final boolean currentOwnerIsSystem = (bp.perm != null
11345                            && isSystemApp(bp.perm.owner));
11346                    if (isSystemApp(p.owner)) {
11347                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
11348                            // It's a built-in permission and no owner, take ownership now
11349                            bp.packageSetting = pkgSetting;
11350                            bp.perm = p;
11351                            bp.uid = pkg.applicationInfo.uid;
11352                            bp.sourcePackage = p.info.packageName;
11353                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11354                        } else if (!currentOwnerIsSystem) {
11355                            String msg = "New decl " + p.owner + " of permission  "
11356                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
11357                            reportSettingsProblem(Log.WARN, msg);
11358                            bp = null;
11359                        }
11360                    }
11361                }
11362
11363                if (bp == null) {
11364                    bp = new BasePermission(p.info.name, p.info.packageName,
11365                            BasePermission.TYPE_NORMAL);
11366                    permissionMap.put(p.info.name, bp);
11367                }
11368
11369                if (bp.perm == null) {
11370                    if (bp.sourcePackage == null
11371                            || bp.sourcePackage.equals(p.info.packageName)) {
11372                        BasePermission tree = findPermissionTreeLP(p.info.name);
11373                        if (tree == null
11374                                || tree.sourcePackage.equals(p.info.packageName)) {
11375                            bp.packageSetting = pkgSetting;
11376                            bp.perm = p;
11377                            bp.uid = pkg.applicationInfo.uid;
11378                            bp.sourcePackage = p.info.packageName;
11379                            p.info.flags |= PermissionInfo.FLAG_INSTALLED;
11380                            if (chatty) {
11381                                if (r == null) {
11382                                    r = new StringBuilder(256);
11383                                } else {
11384                                    r.append(' ');
11385                                }
11386                                r.append(p.info.name);
11387                            }
11388                        } else {
11389                            Slog.w(TAG, "Permission " + p.info.name + " from package "
11390                                    + p.info.packageName + " ignored: base tree "
11391                                    + tree.name + " is from package "
11392                                    + tree.sourcePackage);
11393                        }
11394                    } else {
11395                        Slog.w(TAG, "Permission " + p.info.name + " from package "
11396                                + p.info.packageName + " ignored: original from "
11397                                + bp.sourcePackage);
11398                    }
11399                } else if (chatty) {
11400                    if (r == null) {
11401                        r = new StringBuilder(256);
11402                    } else {
11403                        r.append(' ');
11404                    }
11405                    r.append("DUP:");
11406                    r.append(p.info.name);
11407                }
11408                if (bp.perm == p) {
11409                    bp.protectionLevel = p.info.protectionLevel;
11410                }
11411            }
11412
11413            if (r != null) {
11414                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
11415            }
11416
11417            N = pkg.instrumentation.size();
11418            r = null;
11419            for (i=0; i<N; i++) {
11420                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11421                a.info.packageName = pkg.applicationInfo.packageName;
11422                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11423                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11424                a.info.splitNames = pkg.splitNames;
11425                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11426                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11427                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11428                a.info.dataDir = pkg.applicationInfo.dataDir;
11429                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11430                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11431                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11432                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11433                mInstrumentation.put(a.getComponentName(), a);
11434                if (chatty) {
11435                    if (r == null) {
11436                        r = new StringBuilder(256);
11437                    } else {
11438                        r.append(' ');
11439                    }
11440                    r.append(a.info.name);
11441                }
11442            }
11443            if (r != null) {
11444                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11445            }
11446
11447            if (pkg.protectedBroadcasts != null) {
11448                N = pkg.protectedBroadcasts.size();
11449                for (i=0; i<N; i++) {
11450                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11451                }
11452            }
11453        }
11454
11455        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11456    }
11457
11458    /**
11459     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11460     * is derived purely on the basis of the contents of {@code scanFile} and
11461     * {@code cpuAbiOverride}.
11462     *
11463     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11464     */
11465    private static void derivePackageAbi(PackageParser.Package pkg, File scanFile,
11466                                 String cpuAbiOverride, boolean extractLibs,
11467                                 File appLib32InstallDir)
11468            throws PackageManagerException {
11469        // Give ourselves some initial paths; we'll come back for another
11470        // pass once we've determined ABI below.
11471        setNativeLibraryPaths(pkg, appLib32InstallDir);
11472
11473        // We would never need to extract libs for forward-locked and external packages,
11474        // since the container service will do it for us. We shouldn't attempt to
11475        // extract libs from system app when it was not updated.
11476        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11477                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11478            extractLibs = false;
11479        }
11480
11481        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11482        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11483
11484        NativeLibraryHelper.Handle handle = null;
11485        try {
11486            handle = NativeLibraryHelper.Handle.create(pkg);
11487            // TODO(multiArch): This can be null for apps that didn't go through the
11488            // usual installation process. We can calculate it again, like we
11489            // do during install time.
11490            //
11491            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11492            // unnecessary.
11493            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11494
11495            // Null out the abis so that they can be recalculated.
11496            pkg.applicationInfo.primaryCpuAbi = null;
11497            pkg.applicationInfo.secondaryCpuAbi = null;
11498            if (isMultiArch(pkg.applicationInfo)) {
11499                // Warn if we've set an abiOverride for multi-lib packages..
11500                // By definition, we need to copy both 32 and 64 bit libraries for
11501                // such packages.
11502                if (pkg.cpuAbiOverride != null
11503                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11504                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11505                }
11506
11507                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11508                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11509                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11510                    if (extractLibs) {
11511                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11512                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11513                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11514                                useIsaSpecificSubdirs);
11515                    } else {
11516                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11517                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11518                    }
11519                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11520                }
11521
11522                maybeThrowExceptionForMultiArchCopy(
11523                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11524
11525                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11526                    if (extractLibs) {
11527                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11528                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11529                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11530                                useIsaSpecificSubdirs);
11531                    } else {
11532                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11533                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11534                    }
11535                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11536                }
11537
11538                maybeThrowExceptionForMultiArchCopy(
11539                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11540
11541                if (abi64 >= 0) {
11542                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11543                }
11544
11545                if (abi32 >= 0) {
11546                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11547                    if (abi64 >= 0) {
11548                        if (pkg.use32bitAbi) {
11549                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11550                            pkg.applicationInfo.primaryCpuAbi = abi;
11551                        } else {
11552                            pkg.applicationInfo.secondaryCpuAbi = abi;
11553                        }
11554                    } else {
11555                        pkg.applicationInfo.primaryCpuAbi = abi;
11556                    }
11557                }
11558
11559            } else {
11560                String[] abiList = (cpuAbiOverride != null) ?
11561                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11562
11563                // Enable gross and lame hacks for apps that are built with old
11564                // SDK tools. We must scan their APKs for renderscript bitcode and
11565                // not launch them if it's present. Don't bother checking on devices
11566                // that don't have 64 bit support.
11567                boolean needsRenderScriptOverride = false;
11568                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11569                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11570                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11571                    needsRenderScriptOverride = true;
11572                }
11573
11574                final int copyRet;
11575                if (extractLibs) {
11576                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11577                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11578                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11579                } else {
11580                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11581                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11582                }
11583                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11584
11585                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11586                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11587                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11588                }
11589
11590                if (copyRet >= 0) {
11591                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11592                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11593                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11594                } else if (needsRenderScriptOverride) {
11595                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11596                }
11597            }
11598        } catch (IOException ioe) {
11599            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11600        } finally {
11601            IoUtils.closeQuietly(handle);
11602        }
11603
11604        // Now that we've calculated the ABIs and determined if it's an internal app,
11605        // we will go ahead and populate the nativeLibraryPath.
11606        setNativeLibraryPaths(pkg, appLib32InstallDir);
11607    }
11608
11609    /**
11610     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11611     * i.e, so that all packages can be run inside a single process if required.
11612     *
11613     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11614     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11615     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11616     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11617     * updating a package that belongs to a shared user.
11618     *
11619     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11620     * adds unnecessary complexity.
11621     */
11622    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
11623            PackageParser.Package scannedPackage) {
11624        String requiredInstructionSet = null;
11625        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11626            requiredInstructionSet = VMRuntime.getInstructionSet(
11627                     scannedPackage.applicationInfo.primaryCpuAbi);
11628        }
11629
11630        PackageSetting requirer = null;
11631        for (PackageSetting ps : packagesForUser) {
11632            // If packagesForUser contains scannedPackage, we skip it. This will happen
11633            // when scannedPackage is an update of an existing package. Without this check,
11634            // we will never be able to change the ABI of any package belonging to a shared
11635            // user, even if it's compatible with other packages.
11636            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11637                if (ps.primaryCpuAbiString == null) {
11638                    continue;
11639                }
11640
11641                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11642                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11643                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11644                    // this but there's not much we can do.
11645                    String errorMessage = "Instruction set mismatch, "
11646                            + ((requirer == null) ? "[caller]" : requirer)
11647                            + " requires " + requiredInstructionSet + " whereas " + ps
11648                            + " requires " + instructionSet;
11649                    Slog.w(TAG, errorMessage);
11650                }
11651
11652                if (requiredInstructionSet == null) {
11653                    requiredInstructionSet = instructionSet;
11654                    requirer = ps;
11655                }
11656            }
11657        }
11658
11659        if (requiredInstructionSet != null) {
11660            String adjustedAbi;
11661            if (requirer != null) {
11662                // requirer != null implies that either scannedPackage was null or that scannedPackage
11663                // did not require an ABI, in which case we have to adjust scannedPackage to match
11664                // the ABI of the set (which is the same as requirer's ABI)
11665                adjustedAbi = requirer.primaryCpuAbiString;
11666                if (scannedPackage != null) {
11667                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11668                }
11669            } else {
11670                // requirer == null implies that we're updating all ABIs in the set to
11671                // match scannedPackage.
11672                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11673            }
11674
11675            for (PackageSetting ps : packagesForUser) {
11676                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11677                    if (ps.primaryCpuAbiString != null) {
11678                        continue;
11679                    }
11680
11681                    ps.primaryCpuAbiString = adjustedAbi;
11682                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11683                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11684                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11685                        if (DEBUG_ABI_SELECTION) {
11686                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11687                                    + " (requirer="
11688                                    + (requirer != null ? requirer.pkg : "null")
11689                                    + ", scannedPackage="
11690                                    + (scannedPackage != null ? scannedPackage : "null")
11691                                    + ")");
11692                        }
11693                        try {
11694                            mInstaller.rmdex(ps.codePathString,
11695                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
11696                        } catch (InstallerException ignored) {
11697                        }
11698                    }
11699                }
11700            }
11701        }
11702    }
11703
11704    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11705        synchronized (mPackages) {
11706            mResolverReplaced = true;
11707            // Set up information for custom user intent resolution activity.
11708            mResolveActivity.applicationInfo = pkg.applicationInfo;
11709            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11710            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11711            mResolveActivity.processName = pkg.applicationInfo.packageName;
11712            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11713            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11714                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11715            mResolveActivity.theme = 0;
11716            mResolveActivity.exported = true;
11717            mResolveActivity.enabled = true;
11718            mResolveInfo.activityInfo = mResolveActivity;
11719            mResolveInfo.priority = 0;
11720            mResolveInfo.preferredOrder = 0;
11721            mResolveInfo.match = 0;
11722            mResolveComponentName = mCustomResolverComponentName;
11723            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11724                    mResolveComponentName);
11725        }
11726    }
11727
11728    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11729        if (installerActivity == null) {
11730            if (DEBUG_EPHEMERAL) {
11731                Slog.d(TAG, "Clear ephemeral installer activity");
11732            }
11733            mInstantAppInstallerActivity = null;
11734            return;
11735        }
11736
11737        if (DEBUG_EPHEMERAL) {
11738            Slog.d(TAG, "Set ephemeral installer activity: "
11739                    + installerActivity.getComponentName());
11740        }
11741        // Set up information for ephemeral installer activity
11742        mInstantAppInstallerActivity = installerActivity;
11743        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11744                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11745        mInstantAppInstallerActivity.exported = true;
11746        mInstantAppInstallerActivity.enabled = true;
11747        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11748        mInstantAppInstallerInfo.priority = 0;
11749        mInstantAppInstallerInfo.preferredOrder = 1;
11750        mInstantAppInstallerInfo.isDefault = true;
11751        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11752                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11753    }
11754
11755    private static String calculateBundledApkRoot(final String codePathString) {
11756        final File codePath = new File(codePathString);
11757        final File codeRoot;
11758        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11759            codeRoot = Environment.getRootDirectory();
11760        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11761            codeRoot = Environment.getOemDirectory();
11762        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11763            codeRoot = Environment.getVendorDirectory();
11764        } else {
11765            // Unrecognized code path; take its top real segment as the apk root:
11766            // e.g. /something/app/blah.apk => /something
11767            try {
11768                File f = codePath.getCanonicalFile();
11769                File parent = f.getParentFile();    // non-null because codePath is a file
11770                File tmp;
11771                while ((tmp = parent.getParentFile()) != null) {
11772                    f = parent;
11773                    parent = tmp;
11774                }
11775                codeRoot = f;
11776                Slog.w(TAG, "Unrecognized code path "
11777                        + codePath + " - using " + codeRoot);
11778            } catch (IOException e) {
11779                // Can't canonicalize the code path -- shenanigans?
11780                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11781                return Environment.getRootDirectory().getPath();
11782            }
11783        }
11784        return codeRoot.getPath();
11785    }
11786
11787    /**
11788     * Derive and set the location of native libraries for the given package,
11789     * which varies depending on where and how the package was installed.
11790     */
11791    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11792        final ApplicationInfo info = pkg.applicationInfo;
11793        final String codePath = pkg.codePath;
11794        final File codeFile = new File(codePath);
11795        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11796        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11797
11798        info.nativeLibraryRootDir = null;
11799        info.nativeLibraryRootRequiresIsa = false;
11800        info.nativeLibraryDir = null;
11801        info.secondaryNativeLibraryDir = null;
11802
11803        if (isApkFile(codeFile)) {
11804            // Monolithic install
11805            if (bundledApp) {
11806                // If "/system/lib64/apkname" exists, assume that is the per-package
11807                // native library directory to use; otherwise use "/system/lib/apkname".
11808                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11809                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11810                        getPrimaryInstructionSet(info));
11811
11812                // This is a bundled system app so choose the path based on the ABI.
11813                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11814                // is just the default path.
11815                final String apkName = deriveCodePathName(codePath);
11816                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11817                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11818                        apkName).getAbsolutePath();
11819
11820                if (info.secondaryCpuAbi != null) {
11821                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11822                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11823                            secondaryLibDir, apkName).getAbsolutePath();
11824                }
11825            } else if (asecApp) {
11826                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11827                        .getAbsolutePath();
11828            } else {
11829                final String apkName = deriveCodePathName(codePath);
11830                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11831                        .getAbsolutePath();
11832            }
11833
11834            info.nativeLibraryRootRequiresIsa = false;
11835            info.nativeLibraryDir = info.nativeLibraryRootDir;
11836        } else {
11837            // Cluster install
11838            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11839            info.nativeLibraryRootRequiresIsa = true;
11840
11841            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11842                    getPrimaryInstructionSet(info)).getAbsolutePath();
11843
11844            if (info.secondaryCpuAbi != null) {
11845                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11846                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11847            }
11848        }
11849    }
11850
11851    /**
11852     * Calculate the abis and roots for a bundled app. These can uniquely
11853     * be determined from the contents of the system partition, i.e whether
11854     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11855     * of this information, and instead assume that the system was built
11856     * sensibly.
11857     */
11858    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11859                                           PackageSetting pkgSetting) {
11860        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11861
11862        // If "/system/lib64/apkname" exists, assume that is the per-package
11863        // native library directory to use; otherwise use "/system/lib/apkname".
11864        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11865        setBundledAppAbi(pkg, apkRoot, apkName);
11866        // pkgSetting might be null during rescan following uninstall of updates
11867        // to a bundled app, so accommodate that possibility.  The settings in
11868        // that case will be established later from the parsed package.
11869        //
11870        // If the settings aren't null, sync them up with what we've just derived.
11871        // note that apkRoot isn't stored in the package settings.
11872        if (pkgSetting != null) {
11873            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11874            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11875        }
11876    }
11877
11878    /**
11879     * Deduces the ABI of a bundled app and sets the relevant fields on the
11880     * parsed pkg object.
11881     *
11882     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11883     *        under which system libraries are installed.
11884     * @param apkName the name of the installed package.
11885     */
11886    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11887        final File codeFile = new File(pkg.codePath);
11888
11889        final boolean has64BitLibs;
11890        final boolean has32BitLibs;
11891        if (isApkFile(codeFile)) {
11892            // Monolithic install
11893            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11894            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11895        } else {
11896            // Cluster install
11897            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11898            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11899                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11900                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11901                has64BitLibs = (new File(rootDir, isa)).exists();
11902            } else {
11903                has64BitLibs = false;
11904            }
11905            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11906                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11907                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11908                has32BitLibs = (new File(rootDir, isa)).exists();
11909            } else {
11910                has32BitLibs = false;
11911            }
11912        }
11913
11914        if (has64BitLibs && !has32BitLibs) {
11915            // The package has 64 bit libs, but not 32 bit libs. Its primary
11916            // ABI should be 64 bit. We can safely assume here that the bundled
11917            // native libraries correspond to the most preferred ABI in the list.
11918
11919            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11920            pkg.applicationInfo.secondaryCpuAbi = null;
11921        } else if (has32BitLibs && !has64BitLibs) {
11922            // The package has 32 bit libs but not 64 bit libs. Its primary
11923            // ABI should be 32 bit.
11924
11925            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11926            pkg.applicationInfo.secondaryCpuAbi = null;
11927        } else if (has32BitLibs && has64BitLibs) {
11928            // The application has both 64 and 32 bit bundled libraries. We check
11929            // here that the app declares multiArch support, and warn if it doesn't.
11930            //
11931            // We will be lenient here and record both ABIs. The primary will be the
11932            // ABI that's higher on the list, i.e, a device that's configured to prefer
11933            // 64 bit apps will see a 64 bit primary ABI,
11934
11935            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11936                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11937            }
11938
11939            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11940                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11941                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11942            } else {
11943                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11944                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11945            }
11946        } else {
11947            pkg.applicationInfo.primaryCpuAbi = null;
11948            pkg.applicationInfo.secondaryCpuAbi = null;
11949        }
11950    }
11951
11952    private void killApplication(String pkgName, int appId, String reason) {
11953        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11954    }
11955
11956    private void killApplication(String pkgName, int appId, int userId, String reason) {
11957        // Request the ActivityManager to kill the process(only for existing packages)
11958        // so that we do not end up in a confused state while the user is still using the older
11959        // version of the application while the new one gets installed.
11960        final long token = Binder.clearCallingIdentity();
11961        try {
11962            IActivityManager am = ActivityManager.getService();
11963            if (am != null) {
11964                try {
11965                    am.killApplication(pkgName, appId, userId, reason);
11966                } catch (RemoteException e) {
11967                }
11968            }
11969        } finally {
11970            Binder.restoreCallingIdentity(token);
11971        }
11972    }
11973
11974    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
11975        // Remove the parent package setting
11976        PackageSetting ps = (PackageSetting) pkg.mExtras;
11977        if (ps != null) {
11978            removePackageLI(ps, chatty);
11979        }
11980        // Remove the child package setting
11981        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
11982        for (int i = 0; i < childCount; i++) {
11983            PackageParser.Package childPkg = pkg.childPackages.get(i);
11984            ps = (PackageSetting) childPkg.mExtras;
11985            if (ps != null) {
11986                removePackageLI(ps, chatty);
11987            }
11988        }
11989    }
11990
11991    void removePackageLI(PackageSetting ps, boolean chatty) {
11992        if (DEBUG_INSTALL) {
11993            if (chatty)
11994                Log.d(TAG, "Removing package " + ps.name);
11995        }
11996
11997        // writer
11998        synchronized (mPackages) {
11999            mPackages.remove(ps.name);
12000            final PackageParser.Package pkg = ps.pkg;
12001            if (pkg != null) {
12002                cleanPackageDataStructuresLILPw(pkg, chatty);
12003            }
12004        }
12005    }
12006
12007    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12008        if (DEBUG_INSTALL) {
12009            if (chatty)
12010                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12011        }
12012
12013        // writer
12014        synchronized (mPackages) {
12015            // Remove the parent package
12016            mPackages.remove(pkg.applicationInfo.packageName);
12017            cleanPackageDataStructuresLILPw(pkg, chatty);
12018
12019            // Remove the child packages
12020            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12021            for (int i = 0; i < childCount; i++) {
12022                PackageParser.Package childPkg = pkg.childPackages.get(i);
12023                mPackages.remove(childPkg.applicationInfo.packageName);
12024                cleanPackageDataStructuresLILPw(childPkg, chatty);
12025            }
12026        }
12027    }
12028
12029    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12030        int N = pkg.providers.size();
12031        StringBuilder r = null;
12032        int i;
12033        for (i=0; i<N; i++) {
12034            PackageParser.Provider p = pkg.providers.get(i);
12035            mProviders.removeProvider(p);
12036            if (p.info.authority == null) {
12037
12038                /* There was another ContentProvider with this authority when
12039                 * this app was installed so this authority is null,
12040                 * Ignore it as we don't have to unregister the provider.
12041                 */
12042                continue;
12043            }
12044            String names[] = p.info.authority.split(";");
12045            for (int j = 0; j < names.length; j++) {
12046                if (mProvidersByAuthority.get(names[j]) == p) {
12047                    mProvidersByAuthority.remove(names[j]);
12048                    if (DEBUG_REMOVE) {
12049                        if (chatty)
12050                            Log.d(TAG, "Unregistered content provider: " + names[j]
12051                                    + ", className = " + p.info.name + ", isSyncable = "
12052                                    + p.info.isSyncable);
12053                    }
12054                }
12055            }
12056            if (DEBUG_REMOVE && chatty) {
12057                if (r == null) {
12058                    r = new StringBuilder(256);
12059                } else {
12060                    r.append(' ');
12061                }
12062                r.append(p.info.name);
12063            }
12064        }
12065        if (r != null) {
12066            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12067        }
12068
12069        N = pkg.services.size();
12070        r = null;
12071        for (i=0; i<N; i++) {
12072            PackageParser.Service s = pkg.services.get(i);
12073            mServices.removeService(s);
12074            if (chatty) {
12075                if (r == null) {
12076                    r = new StringBuilder(256);
12077                } else {
12078                    r.append(' ');
12079                }
12080                r.append(s.info.name);
12081            }
12082        }
12083        if (r != null) {
12084            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12085        }
12086
12087        N = pkg.receivers.size();
12088        r = null;
12089        for (i=0; i<N; i++) {
12090            PackageParser.Activity a = pkg.receivers.get(i);
12091            mReceivers.removeActivity(a, "receiver");
12092            if (DEBUG_REMOVE && chatty) {
12093                if (r == null) {
12094                    r = new StringBuilder(256);
12095                } else {
12096                    r.append(' ');
12097                }
12098                r.append(a.info.name);
12099            }
12100        }
12101        if (r != null) {
12102            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12103        }
12104
12105        N = pkg.activities.size();
12106        r = null;
12107        for (i=0; i<N; i++) {
12108            PackageParser.Activity a = pkg.activities.get(i);
12109            mActivities.removeActivity(a, "activity");
12110            if (DEBUG_REMOVE && chatty) {
12111                if (r == null) {
12112                    r = new StringBuilder(256);
12113                } else {
12114                    r.append(' ');
12115                }
12116                r.append(a.info.name);
12117            }
12118        }
12119        if (r != null) {
12120            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12121        }
12122
12123        N = pkg.permissions.size();
12124        r = null;
12125        for (i=0; i<N; i++) {
12126            PackageParser.Permission p = pkg.permissions.get(i);
12127            BasePermission bp = mSettings.mPermissions.get(p.info.name);
12128            if (bp == null) {
12129                bp = mSettings.mPermissionTrees.get(p.info.name);
12130            }
12131            if (bp != null && bp.perm == p) {
12132                bp.perm = null;
12133                if (DEBUG_REMOVE && chatty) {
12134                    if (r == null) {
12135                        r = new StringBuilder(256);
12136                    } else {
12137                        r.append(' ');
12138                    }
12139                    r.append(p.info.name);
12140                }
12141            }
12142            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12143                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name);
12144                if (appOpPkgs != null) {
12145                    appOpPkgs.remove(pkg.packageName);
12146                }
12147            }
12148        }
12149        if (r != null) {
12150            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12151        }
12152
12153        N = pkg.requestedPermissions.size();
12154        r = null;
12155        for (i=0; i<N; i++) {
12156            String perm = pkg.requestedPermissions.get(i);
12157            BasePermission bp = mSettings.mPermissions.get(perm);
12158            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12159                ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm);
12160                if (appOpPkgs != null) {
12161                    appOpPkgs.remove(pkg.packageName);
12162                    if (appOpPkgs.isEmpty()) {
12163                        mAppOpPermissionPackages.remove(perm);
12164                    }
12165                }
12166            }
12167        }
12168        if (r != null) {
12169            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
12170        }
12171
12172        N = pkg.instrumentation.size();
12173        r = null;
12174        for (i=0; i<N; i++) {
12175            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12176            mInstrumentation.remove(a.getComponentName());
12177            if (DEBUG_REMOVE && chatty) {
12178                if (r == null) {
12179                    r = new StringBuilder(256);
12180                } else {
12181                    r.append(' ');
12182                }
12183                r.append(a.info.name);
12184            }
12185        }
12186        if (r != null) {
12187            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12188        }
12189
12190        r = null;
12191        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12192            // Only system apps can hold shared libraries.
12193            if (pkg.libraryNames != null) {
12194                for (i = 0; i < pkg.libraryNames.size(); i++) {
12195                    String name = pkg.libraryNames.get(i);
12196                    if (removeSharedLibraryLPw(name, 0)) {
12197                        if (DEBUG_REMOVE && chatty) {
12198                            if (r == null) {
12199                                r = new StringBuilder(256);
12200                            } else {
12201                                r.append(' ');
12202                            }
12203                            r.append(name);
12204                        }
12205                    }
12206                }
12207            }
12208        }
12209
12210        r = null;
12211
12212        // Any package can hold static shared libraries.
12213        if (pkg.staticSharedLibName != null) {
12214            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12215                if (DEBUG_REMOVE && chatty) {
12216                    if (r == null) {
12217                        r = new StringBuilder(256);
12218                    } else {
12219                        r.append(' ');
12220                    }
12221                    r.append(pkg.staticSharedLibName);
12222                }
12223            }
12224        }
12225
12226        if (r != null) {
12227            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12228        }
12229    }
12230
12231    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
12232        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
12233            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
12234                return true;
12235            }
12236        }
12237        return false;
12238    }
12239
12240    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
12241    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
12242    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
12243
12244    private void updatePermissionsLPw(PackageParser.Package pkg, int flags) {
12245        // Update the parent permissions
12246        updatePermissionsLPw(pkg.packageName, pkg, flags);
12247        // Update the child permissions
12248        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12249        for (int i = 0; i < childCount; i++) {
12250            PackageParser.Package childPkg = pkg.childPackages.get(i);
12251            updatePermissionsLPw(childPkg.packageName, childPkg, flags);
12252        }
12253    }
12254
12255    private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo,
12256            int flags) {
12257        final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null;
12258        updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags);
12259    }
12260
12261    private void updatePermissionsLPw(String changingPkg,
12262            PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) {
12263        // Make sure there are no dangling permission trees.
12264        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
12265        while (it.hasNext()) {
12266            final BasePermission bp = it.next();
12267            if (bp.packageSetting == null) {
12268                // We may not yet have parsed the package, so just see if
12269                // we still know about its settings.
12270                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12271            }
12272            if (bp.packageSetting == null) {
12273                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
12274                        + " from package " + bp.sourcePackage);
12275                it.remove();
12276            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12277                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12278                    Slog.i(TAG, "Removing old permission tree: " + bp.name
12279                            + " from package " + bp.sourcePackage);
12280                    flags |= UPDATE_PERMISSIONS_ALL;
12281                    it.remove();
12282                }
12283            }
12284        }
12285
12286        // Make sure all dynamic permissions have been assigned to a package,
12287        // and make sure there are no dangling permissions.
12288        it = mSettings.mPermissions.values().iterator();
12289        while (it.hasNext()) {
12290            final BasePermission bp = it.next();
12291            if (bp.type == BasePermission.TYPE_DYNAMIC) {
12292                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
12293                        + bp.name + " pkg=" + bp.sourcePackage
12294                        + " info=" + bp.pendingInfo);
12295                if (bp.packageSetting == null && bp.pendingInfo != null) {
12296                    final BasePermission tree = findPermissionTreeLP(bp.name);
12297                    if (tree != null && tree.perm != null) {
12298                        bp.packageSetting = tree.packageSetting;
12299                        bp.perm = new PackageParser.Permission(tree.perm.owner,
12300                                new PermissionInfo(bp.pendingInfo));
12301                        bp.perm.info.packageName = tree.perm.info.packageName;
12302                        bp.perm.info.name = bp.name;
12303                        bp.uid = tree.uid;
12304                    }
12305                }
12306            }
12307            if (bp.packageSetting == null) {
12308                // We may not yet have parsed the package, so just see if
12309                // we still know about its settings.
12310                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
12311            }
12312            if (bp.packageSetting == null) {
12313                Slog.w(TAG, "Removing dangling permission: " + bp.name
12314                        + " from package " + bp.sourcePackage);
12315                it.remove();
12316            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
12317                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
12318                    Slog.i(TAG, "Removing old permission: " + bp.name
12319                            + " from package " + bp.sourcePackage);
12320                    flags |= UPDATE_PERMISSIONS_ALL;
12321                    it.remove();
12322                }
12323            }
12324        }
12325
12326        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions");
12327        // Now update the permissions for all packages, in particular
12328        // replace the granted permissions of the system packages.
12329        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
12330            for (PackageParser.Package pkg : mPackages.values()) {
12331                if (pkg != pkgInfo) {
12332                    // Only replace for packages on requested volume
12333                    final String volumeUuid = getVolumeUuidForPackage(pkg);
12334                    final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0)
12335                            && Objects.equals(replaceVolumeUuid, volumeUuid);
12336                    grantPermissionsLPw(pkg, replace, changingPkg);
12337                }
12338            }
12339        }
12340
12341        if (pkgInfo != null) {
12342            // Only replace for packages on requested volume
12343            final String volumeUuid = getVolumeUuidForPackage(pkgInfo);
12344            final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0)
12345                    && Objects.equals(replaceVolumeUuid, volumeUuid);
12346            grantPermissionsLPw(pkgInfo, replace, changingPkg);
12347        }
12348        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12349    }
12350
12351    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
12352            String packageOfInterest) {
12353        // IMPORTANT: There are two types of permissions: install and runtime.
12354        // Install time permissions are granted when the app is installed to
12355        // all device users and users added in the future. Runtime permissions
12356        // are granted at runtime explicitly to specific users. Normal and signature
12357        // protected permissions are install time permissions. Dangerous permissions
12358        // are install permissions if the app's target SDK is Lollipop MR1 or older,
12359        // otherwise they are runtime permissions. This function does not manage
12360        // runtime permissions except for the case an app targeting Lollipop MR1
12361        // being upgraded to target a newer SDK, in which case dangerous permissions
12362        // are transformed from install time to runtime ones.
12363
12364        final PackageSetting ps = (PackageSetting) pkg.mExtras;
12365        if (ps == null) {
12366            return;
12367        }
12368
12369        PermissionsState permissionsState = ps.getPermissionsState();
12370        PermissionsState origPermissions = permissionsState;
12371
12372        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
12373
12374        boolean runtimePermissionsRevoked = false;
12375        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
12376
12377        boolean changedInstallPermission = false;
12378
12379        if (replace) {
12380            ps.installPermissionsFixed = false;
12381            if (!ps.isSharedUser()) {
12382                origPermissions = new PermissionsState(permissionsState);
12383                permissionsState.reset();
12384            } else {
12385                // We need to know only about runtime permission changes since the
12386                // calling code always writes the install permissions state but
12387                // the runtime ones are written only if changed. The only cases of
12388                // changed runtime permissions here are promotion of an install to
12389                // runtime and revocation of a runtime from a shared user.
12390                changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw(
12391                        ps.sharedUser, UserManagerService.getInstance().getUserIds());
12392                if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) {
12393                    runtimePermissionsRevoked = true;
12394                }
12395            }
12396        }
12397
12398        permissionsState.setGlobalGids(mGlobalGids);
12399
12400        final int N = pkg.requestedPermissions.size();
12401        for (int i=0; i<N; i++) {
12402            final String name = pkg.requestedPermissions.get(i);
12403            final BasePermission bp = mSettings.mPermissions.get(name);
12404            final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion
12405                    >= Build.VERSION_CODES.M;
12406
12407            if (DEBUG_INSTALL) {
12408                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
12409            }
12410
12411            if (bp == null || bp.packageSetting == null) {
12412                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
12413                    if (DEBUG_PERMISSIONS) {
12414                        Slog.i(TAG, "Unknown permission " + name
12415                                + " in package " + pkg.packageName);
12416                    }
12417                }
12418                continue;
12419            }
12420
12421
12422            // Limit ephemeral apps to ephemeral allowed permissions.
12423            if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) {
12424                if (DEBUG_PERMISSIONS) {
12425                    Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package "
12426                            + pkg.packageName);
12427                }
12428                continue;
12429            }
12430
12431            if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) {
12432                if (DEBUG_PERMISSIONS) {
12433                    Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package "
12434                            + pkg.packageName);
12435                }
12436                continue;
12437            }
12438
12439            final String perm = bp.name;
12440            boolean allowedSig = false;
12441            int grant = GRANT_DENIED;
12442
12443            // Keep track of app op permissions.
12444            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
12445                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
12446                if (pkgs == null) {
12447                    pkgs = new ArraySet<>();
12448                    mAppOpPermissionPackages.put(bp.name, pkgs);
12449                }
12450                pkgs.add(pkg.packageName);
12451            }
12452
12453            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
12454            switch (level) {
12455                case PermissionInfo.PROTECTION_NORMAL: {
12456                    // For all apps normal permissions are install time ones.
12457                    grant = GRANT_INSTALL;
12458                } break;
12459
12460                case PermissionInfo.PROTECTION_DANGEROUS: {
12461                    // If a permission review is required for legacy apps we represent
12462                    // their permissions as always granted runtime ones since we need
12463                    // to keep the review required permission flag per user while an
12464                    // install permission's state is shared across all users.
12465                    if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) {
12466                        // For legacy apps dangerous permissions are install time ones.
12467                        grant = GRANT_INSTALL;
12468                    } else if (origPermissions.hasInstallPermission(bp.name)) {
12469                        // For legacy apps that became modern, install becomes runtime.
12470                        grant = GRANT_UPGRADE;
12471                    } else if (mPromoteSystemApps
12472                            && isSystemApp(ps)
12473                            && mExistingSystemPackages.contains(ps.name)) {
12474                        // For legacy system apps, install becomes runtime.
12475                        // We cannot check hasInstallPermission() for system apps since those
12476                        // permissions were granted implicitly and not persisted pre-M.
12477                        grant = GRANT_UPGRADE;
12478                    } else {
12479                        // For modern apps keep runtime permissions unchanged.
12480                        grant = GRANT_RUNTIME;
12481                    }
12482                } break;
12483
12484                case PermissionInfo.PROTECTION_SIGNATURE: {
12485                    // For all apps signature permissions are install time ones.
12486                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
12487                    if (allowedSig) {
12488                        grant = GRANT_INSTALL;
12489                    }
12490                } break;
12491            }
12492
12493            if (DEBUG_PERMISSIONS) {
12494                Slog.i(TAG, "Granting permission " + perm + " to package " + pkg.packageName);
12495            }
12496
12497            if (grant != GRANT_DENIED) {
12498                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
12499                    // If this is an existing, non-system package, then
12500                    // we can't add any new permissions to it.
12501                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
12502                        // Except...  if this is a permission that was added
12503                        // to the platform (note: need to only do this when
12504                        // updating the platform).
12505                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
12506                            grant = GRANT_DENIED;
12507                        }
12508                    }
12509                }
12510
12511                switch (grant) {
12512                    case GRANT_INSTALL: {
12513                        // Revoke this as runtime permission to handle the case of
12514                        // a runtime permission being downgraded to an install one.
12515                        // Also in permission review mode we keep dangerous permissions
12516                        // for legacy apps
12517                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12518                            if (origPermissions.getRuntimePermissionState(
12519                                    bp.name, userId) != null) {
12520                                // Revoke the runtime permission and clear the flags.
12521                                origPermissions.revokeRuntimePermission(bp, userId);
12522                                origPermissions.updatePermissionFlags(bp, userId,
12523                                      PackageManager.MASK_PERMISSION_FLAGS, 0);
12524                                // If we revoked a permission permission, we have to write.
12525                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12526                                        changedRuntimePermissionUserIds, userId);
12527                            }
12528                        }
12529                        // Grant an install permission.
12530                        if (permissionsState.grantInstallPermission(bp) !=
12531                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
12532                            changedInstallPermission = true;
12533                        }
12534                    } break;
12535
12536                    case GRANT_RUNTIME: {
12537                        // Grant previously granted runtime permissions.
12538                        for (int userId : UserManagerService.getInstance().getUserIds()) {
12539                            PermissionState permissionState = origPermissions
12540                                    .getRuntimePermissionState(bp.name, userId);
12541                            int flags = permissionState != null
12542                                    ? permissionState.getFlags() : 0;
12543                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
12544                                // Don't propagate the permission in a permission review mode if
12545                                // the former was revoked, i.e. marked to not propagate on upgrade.
12546                                // Note that in a permission review mode install permissions are
12547                                // represented as constantly granted runtime ones since we need to
12548                                // keep a per user state associated with the permission. Also the
12549                                // revoke on upgrade flag is no longer applicable and is reset.
12550                                final boolean revokeOnUpgrade = (flags & PackageManager
12551                                        .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
12552                                if (revokeOnUpgrade) {
12553                                    flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
12554                                    // Since we changed the flags, we have to write.
12555                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12556                                            changedRuntimePermissionUserIds, userId);
12557                                }
12558                                if (!mPermissionReviewRequired || !revokeOnUpgrade) {
12559                                    if (permissionsState.grantRuntimePermission(bp, userId) ==
12560                                            PermissionsState.PERMISSION_OPERATION_FAILURE) {
12561                                        // If we cannot put the permission as it was,
12562                                        // we have to write.
12563                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12564                                                changedRuntimePermissionUserIds, userId);
12565                                    }
12566                                }
12567
12568                                // If the app supports runtime permissions no need for a review.
12569                                if (mPermissionReviewRequired
12570                                        && appSupportsRuntimePermissions
12571                                        && (flags & PackageManager
12572                                                .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) {
12573                                    flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
12574                                    // Since we changed the flags, we have to write.
12575                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12576                                            changedRuntimePermissionUserIds, userId);
12577                                }
12578                            } else if (mPermissionReviewRequired
12579                                    && !appSupportsRuntimePermissions) {
12580                                // For legacy apps that need a permission review, every new
12581                                // runtime permission is granted but it is pending a review.
12582                                // We also need to review only platform defined runtime
12583                                // permissions as these are the only ones the platform knows
12584                                // how to disable the API to simulate revocation as legacy
12585                                // apps don't expect to run with revoked permissions.
12586                                if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) {
12587                                    if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
12588                                        flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
12589                                        // We changed the flags, hence have to write.
12590                                        changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12591                                                changedRuntimePermissionUserIds, userId);
12592                                    }
12593                                }
12594                                if (permissionsState.grantRuntimePermission(bp, userId)
12595                                        != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12596                                    // We changed the permission, hence have to write.
12597                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12598                                            changedRuntimePermissionUserIds, userId);
12599                                }
12600                            }
12601                            // Propagate the permission flags.
12602                            permissionsState.updatePermissionFlags(bp, userId, flags, flags);
12603                        }
12604                    } break;
12605
12606                    case GRANT_UPGRADE: {
12607                        // Grant runtime permissions for a previously held install permission.
12608                        PermissionState permissionState = origPermissions
12609                                .getInstallPermissionState(bp.name);
12610                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
12611
12612                        if (origPermissions.revokeInstallPermission(bp)
12613                                != PermissionsState.PERMISSION_OPERATION_FAILURE) {
12614                            // We will be transferring the permission flags, so clear them.
12615                            origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
12616                                    PackageManager.MASK_PERMISSION_FLAGS, 0);
12617                            changedInstallPermission = true;
12618                        }
12619
12620                        // If the permission is not to be promoted to runtime we ignore it and
12621                        // also its other flags as they are not applicable to install permissions.
12622                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
12623                            for (int userId : currentUserIds) {
12624                                if (permissionsState.grantRuntimePermission(bp, userId) !=
12625                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12626                                    // Transfer the permission flags.
12627                                    permissionsState.updatePermissionFlags(bp, userId,
12628                                            flags, flags);
12629                                    // If we granted the permission, we have to write.
12630                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
12631                                            changedRuntimePermissionUserIds, userId);
12632                                }
12633                            }
12634                        }
12635                    } break;
12636
12637                    default: {
12638                        if (packageOfInterest == null
12639                                || packageOfInterest.equals(pkg.packageName)) {
12640                            if (DEBUG_PERMISSIONS) {
12641                                Slog.i(TAG, "Not granting permission " + perm
12642                                        + " to package " + pkg.packageName
12643                                        + " because it was previously installed without");
12644                            }
12645                        }
12646                    } break;
12647                }
12648            } else {
12649                if (permissionsState.revokeInstallPermission(bp) !=
12650                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
12651                    // Also drop the permission flags.
12652                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
12653                            PackageManager.MASK_PERMISSION_FLAGS, 0);
12654                    changedInstallPermission = true;
12655                    Slog.i(TAG, "Un-granting permission " + perm
12656                            + " from package " + pkg.packageName
12657                            + " (protectionLevel=" + bp.protectionLevel
12658                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12659                            + ")");
12660                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
12661                    // Don't print warning for app op permissions, since it is fine for them
12662                    // not to be granted, there is a UI for the user to decide.
12663                    if (DEBUG_PERMISSIONS
12664                            && (packageOfInterest == null
12665                                    || packageOfInterest.equals(pkg.packageName))) {
12666                        Slog.i(TAG, "Not granting permission " + perm
12667                                + " to package " + pkg.packageName
12668                                + " (protectionLevel=" + bp.protectionLevel
12669                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
12670                                + ")");
12671                    }
12672                }
12673            }
12674        }
12675
12676        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
12677                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
12678            // This is the first that we have heard about this package, so the
12679            // permissions we have now selected are fixed until explicitly
12680            // changed.
12681            ps.installPermissionsFixed = true;
12682        }
12683
12684        // Persist the runtime permissions state for users with changes. If permissions
12685        // were revoked because no app in the shared user declares them we have to
12686        // write synchronously to avoid losing runtime permissions state.
12687        for (int userId : changedRuntimePermissionUserIds) {
12688            mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked);
12689        }
12690    }
12691
12692    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
12693        boolean allowed = false;
12694        final int NP = PackageParser.NEW_PERMISSIONS.length;
12695        for (int ip=0; ip<NP; ip++) {
12696            final PackageParser.NewPermissionInfo npi
12697                    = PackageParser.NEW_PERMISSIONS[ip];
12698            if (npi.name.equals(perm)
12699                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
12700                allowed = true;
12701                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
12702                        + pkg.packageName);
12703                break;
12704            }
12705        }
12706        return allowed;
12707    }
12708
12709    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
12710            BasePermission bp, PermissionsState origPermissions) {
12711        boolean privilegedPermission = (bp.protectionLevel
12712                & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0;
12713        boolean privappPermissionsDisable =
12714                RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE;
12715        boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage);
12716        boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName);
12717        if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp()
12718                && !platformPackage && platformPermission) {
12719            ArraySet<String> wlPermissions = SystemConfig.getInstance()
12720                    .getPrivAppPermissions(pkg.packageName);
12721            boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm);
12722            if (!whitelisted) {
12723                Slog.w(TAG, "Privileged permission " + perm + " for package "
12724                        + pkg.packageName + " - not in privapp-permissions whitelist");
12725                // Only report violations for apps on system image
12726                if (!mSystemReady && !pkg.isUpdatedSystemApp()) {
12727                    if (mPrivappPermissionsViolations == null) {
12728                        mPrivappPermissionsViolations = new ArraySet<>();
12729                    }
12730                    mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm);
12731                }
12732                if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) {
12733                    return false;
12734                }
12735            }
12736        }
12737        boolean allowed = (compareSignatures(
12738                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
12739                        == PackageManager.SIGNATURE_MATCH)
12740                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
12741                        == PackageManager.SIGNATURE_MATCH);
12742        if (!allowed && privilegedPermission) {
12743            if (isSystemApp(pkg)) {
12744                // For updated system applications, a system permission
12745                // is granted only if it had been defined by the original application.
12746                if (pkg.isUpdatedSystemApp()) {
12747                    final PackageSetting sysPs = mSettings
12748                            .getDisabledSystemPkgLPr(pkg.packageName);
12749                    if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) {
12750                        // If the original was granted this permission, we take
12751                        // that grant decision as read and propagate it to the
12752                        // update.
12753                        if (sysPs.isPrivileged()) {
12754                            allowed = true;
12755                        }
12756                    } else {
12757                        // The system apk may have been updated with an older
12758                        // version of the one on the data partition, but which
12759                        // granted a new system permission that it didn't have
12760                        // before.  In this case we do want to allow the app to
12761                        // now get the new permission if the ancestral apk is
12762                        // privileged to get it.
12763                        if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) {
12764                            for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) {
12765                                if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) {
12766                                    allowed = true;
12767                                    break;
12768                                }
12769                            }
12770                        }
12771                        // Also if a privileged parent package on the system image or any of
12772                        // its children requested a privileged permission, the updated child
12773                        // packages can also get the permission.
12774                        if (pkg.parentPackage != null) {
12775                            final PackageSetting disabledSysParentPs = mSettings
12776                                    .getDisabledSystemPkgLPr(pkg.parentPackage.packageName);
12777                            if (disabledSysParentPs != null && disabledSysParentPs.pkg != null
12778                                    && disabledSysParentPs.isPrivileged()) {
12779                                if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) {
12780                                    allowed = true;
12781                                } else if (disabledSysParentPs.pkg.childPackages != null) {
12782                                    final int count = disabledSysParentPs.pkg.childPackages.size();
12783                                    for (int i = 0; i < count; i++) {
12784                                        PackageParser.Package disabledSysChildPkg =
12785                                                disabledSysParentPs.pkg.childPackages.get(i);
12786                                        if (isPackageRequestingPermission(disabledSysChildPkg,
12787                                                perm)) {
12788                                            allowed = true;
12789                                            break;
12790                                        }
12791                                    }
12792                                }
12793                            }
12794                        }
12795                    }
12796                } else {
12797                    allowed = isPrivilegedApp(pkg);
12798                }
12799            }
12800        }
12801        if (!allowed) {
12802            if (!allowed && (bp.protectionLevel
12803                    & PermissionInfo.PROTECTION_FLAG_PRE23) != 0
12804                    && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
12805                // If this was a previously normal/dangerous permission that got moved
12806                // to a system permission as part of the runtime permission redesign, then
12807                // we still want to blindly grant it to old apps.
12808                allowed = true;
12809            }
12810            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0
12811                    && pkg.packageName.equals(mRequiredInstallerPackage)) {
12812                // If this permission is to be granted to the system installer and
12813                // this app is an installer, then it gets the permission.
12814                allowed = true;
12815            }
12816            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0
12817                    && pkg.packageName.equals(mRequiredVerifierPackage)) {
12818                // If this permission is to be granted to the system verifier and
12819                // this app is a verifier, then it gets the permission.
12820                allowed = true;
12821            }
12822            if (!allowed && (bp.protectionLevel
12823                    & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0
12824                    && isSystemApp(pkg)) {
12825                // Any pre-installed system app is allowed to get this permission.
12826                allowed = true;
12827            }
12828            if (!allowed && (bp.protectionLevel
12829                    & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
12830                // For development permissions, a development permission
12831                // is granted only if it was already granted.
12832                allowed = origPermissions.hasInstallPermission(perm);
12833            }
12834            if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0
12835                    && pkg.packageName.equals(mSetupWizardPackage)) {
12836                // If this permission is to be granted to the system setup wizard and
12837                // this app is a setup wizard, then it gets the permission.
12838                allowed = true;
12839            }
12840        }
12841        return allowed;
12842    }
12843
12844    private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) {
12845        final int permCount = pkg.requestedPermissions.size();
12846        for (int j = 0; j < permCount; j++) {
12847            String requestedPermission = pkg.requestedPermissions.get(j);
12848            if (permission.equals(requestedPermission)) {
12849                return true;
12850            }
12851        }
12852        return false;
12853    }
12854
12855    final class ActivityIntentResolver
12856            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12857        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12858                boolean defaultOnly, int userId) {
12859            if (!sUserManager.exists(userId)) return null;
12860            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12861            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12862        }
12863
12864        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12865                int userId) {
12866            if (!sUserManager.exists(userId)) return null;
12867            mFlags = flags;
12868            return super.queryIntent(intent, resolvedType,
12869                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12870                    userId);
12871        }
12872
12873        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12874                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12875            if (!sUserManager.exists(userId)) return null;
12876            if (packageActivities == null) {
12877                return null;
12878            }
12879            mFlags = flags;
12880            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12881            final int N = packageActivities.size();
12882            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12883                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12884
12885            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12886            for (int i = 0; i < N; ++i) {
12887                intentFilters = packageActivities.get(i).intents;
12888                if (intentFilters != null && intentFilters.size() > 0) {
12889                    PackageParser.ActivityIntentInfo[] array =
12890                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12891                    intentFilters.toArray(array);
12892                    listCut.add(array);
12893                }
12894            }
12895            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12896        }
12897
12898        /**
12899         * Finds a privileged activity that matches the specified activity names.
12900         */
12901        private PackageParser.Activity findMatchingActivity(
12902                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12903            for (PackageParser.Activity sysActivity : activityList) {
12904                if (sysActivity.info.name.equals(activityInfo.name)) {
12905                    return sysActivity;
12906                }
12907                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12908                    return sysActivity;
12909                }
12910                if (sysActivity.info.targetActivity != null) {
12911                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12912                        return sysActivity;
12913                    }
12914                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12915                        return sysActivity;
12916                    }
12917                }
12918            }
12919            return null;
12920        }
12921
12922        public class IterGenerator<E> {
12923            public Iterator<E> generate(ActivityIntentInfo info) {
12924                return null;
12925            }
12926        }
12927
12928        public class ActionIterGenerator extends IterGenerator<String> {
12929            @Override
12930            public Iterator<String> generate(ActivityIntentInfo info) {
12931                return info.actionsIterator();
12932            }
12933        }
12934
12935        public class CategoriesIterGenerator extends IterGenerator<String> {
12936            @Override
12937            public Iterator<String> generate(ActivityIntentInfo info) {
12938                return info.categoriesIterator();
12939            }
12940        }
12941
12942        public class SchemesIterGenerator extends IterGenerator<String> {
12943            @Override
12944            public Iterator<String> generate(ActivityIntentInfo info) {
12945                return info.schemesIterator();
12946            }
12947        }
12948
12949        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12950            @Override
12951            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12952                return info.authoritiesIterator();
12953            }
12954        }
12955
12956        /**
12957         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12958         * MODIFIED. Do not pass in a list that should not be changed.
12959         */
12960        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12961                IterGenerator<T> generator, Iterator<T> searchIterator) {
12962            // loop through the set of actions; every one must be found in the intent filter
12963            while (searchIterator.hasNext()) {
12964                // we must have at least one filter in the list to consider a match
12965                if (intentList.size() == 0) {
12966                    break;
12967                }
12968
12969                final T searchAction = searchIterator.next();
12970
12971                // loop through the set of intent filters
12972                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12973                while (intentIter.hasNext()) {
12974                    final ActivityIntentInfo intentInfo = intentIter.next();
12975                    boolean selectionFound = false;
12976
12977                    // loop through the intent filter's selection criteria; at least one
12978                    // of them must match the searched criteria
12979                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12980                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12981                        final T intentSelection = intentSelectionIter.next();
12982                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12983                            selectionFound = true;
12984                            break;
12985                        }
12986                    }
12987
12988                    // the selection criteria wasn't found in this filter's set; this filter
12989                    // is not a potential match
12990                    if (!selectionFound) {
12991                        intentIter.remove();
12992                    }
12993                }
12994            }
12995        }
12996
12997        private boolean isProtectedAction(ActivityIntentInfo filter) {
12998            final Iterator<String> actionsIter = filter.actionsIterator();
12999            while (actionsIter != null && actionsIter.hasNext()) {
13000                final String filterAction = actionsIter.next();
13001                if (PROTECTED_ACTIONS.contains(filterAction)) {
13002                    return true;
13003                }
13004            }
13005            return false;
13006        }
13007
13008        /**
13009         * Adjusts the priority of the given intent filter according to policy.
13010         * <p>
13011         * <ul>
13012         * <li>The priority for non privileged applications is capped to '0'</li>
13013         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
13014         * <li>The priority for unbundled updates to privileged applications is capped to the
13015         *      priority defined on the system partition</li>
13016         * </ul>
13017         * <p>
13018         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
13019         * allowed to obtain any priority on any action.
13020         */
13021        private void adjustPriority(
13022                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
13023            // nothing to do; priority is fine as-is
13024            if (intent.getPriority() <= 0) {
13025                return;
13026            }
13027
13028            final ActivityInfo activityInfo = intent.activity.info;
13029            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
13030
13031            final boolean privilegedApp =
13032                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
13033            if (!privilegedApp) {
13034                // non-privileged applications can never define a priority >0
13035                if (DEBUG_FILTERS) {
13036                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
13037                            + " package: " + applicationInfo.packageName
13038                            + " activity: " + intent.activity.className
13039                            + " origPrio: " + intent.getPriority());
13040                }
13041                intent.setPriority(0);
13042                return;
13043            }
13044
13045            if (systemActivities == null) {
13046                // the system package is not disabled; we're parsing the system partition
13047                if (isProtectedAction(intent)) {
13048                    if (mDeferProtectedFilters) {
13049                        // We can't deal with these just yet. No component should ever obtain a
13050                        // >0 priority for a protected actions, with ONE exception -- the setup
13051                        // wizard. The setup wizard, however, cannot be known until we're able to
13052                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
13053                        // until all intent filters have been processed. Chicken, meet egg.
13054                        // Let the filter temporarily have a high priority and rectify the
13055                        // priorities after all system packages have been scanned.
13056                        mProtectedFilters.add(intent);
13057                        if (DEBUG_FILTERS) {
13058                            Slog.i(TAG, "Protected action; save for later;"
13059                                    + " package: " + applicationInfo.packageName
13060                                    + " activity: " + intent.activity.className
13061                                    + " origPrio: " + intent.getPriority());
13062                        }
13063                        return;
13064                    } else {
13065                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
13066                            Slog.i(TAG, "No setup wizard;"
13067                                + " All protected intents capped to priority 0");
13068                        }
13069                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
13070                            if (DEBUG_FILTERS) {
13071                                Slog.i(TAG, "Found setup wizard;"
13072                                    + " allow priority " + intent.getPriority() + ";"
13073                                    + " package: " + intent.activity.info.packageName
13074                                    + " activity: " + intent.activity.className
13075                                    + " priority: " + intent.getPriority());
13076                            }
13077                            // setup wizard gets whatever it wants
13078                            return;
13079                        }
13080                        if (DEBUG_FILTERS) {
13081                            Slog.i(TAG, "Protected action; cap priority to 0;"
13082                                    + " package: " + intent.activity.info.packageName
13083                                    + " activity: " + intent.activity.className
13084                                    + " origPrio: " + intent.getPriority());
13085                        }
13086                        intent.setPriority(0);
13087                        return;
13088                    }
13089                }
13090                // privileged apps on the system image get whatever priority they request
13091                return;
13092            }
13093
13094            // privileged app unbundled update ... try to find the same activity
13095            final PackageParser.Activity foundActivity =
13096                    findMatchingActivity(systemActivities, activityInfo);
13097            if (foundActivity == null) {
13098                // this is a new activity; it cannot obtain >0 priority
13099                if (DEBUG_FILTERS) {
13100                    Slog.i(TAG, "New activity; cap priority to 0;"
13101                            + " package: " + applicationInfo.packageName
13102                            + " activity: " + intent.activity.className
13103                            + " origPrio: " + intent.getPriority());
13104                }
13105                intent.setPriority(0);
13106                return;
13107            }
13108
13109            // found activity, now check for filter equivalence
13110
13111            // a shallow copy is enough; we modify the list, not its contents
13112            final List<ActivityIntentInfo> intentListCopy =
13113                    new ArrayList<>(foundActivity.intents);
13114            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
13115
13116            // find matching action subsets
13117            final Iterator<String> actionsIterator = intent.actionsIterator();
13118            if (actionsIterator != null) {
13119                getIntentListSubset(
13120                        intentListCopy, new ActionIterGenerator(), actionsIterator);
13121                if (intentListCopy.size() == 0) {
13122                    // no more intents to match; we're not equivalent
13123                    if (DEBUG_FILTERS) {
13124                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
13125                                + " package: " + applicationInfo.packageName
13126                                + " activity: " + intent.activity.className
13127                                + " origPrio: " + intent.getPriority());
13128                    }
13129                    intent.setPriority(0);
13130                    return;
13131                }
13132            }
13133
13134            // find matching category subsets
13135            final Iterator<String> categoriesIterator = intent.categoriesIterator();
13136            if (categoriesIterator != null) {
13137                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
13138                        categoriesIterator);
13139                if (intentListCopy.size() == 0) {
13140                    // no more intents to match; we're not equivalent
13141                    if (DEBUG_FILTERS) {
13142                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
13143                                + " package: " + applicationInfo.packageName
13144                                + " activity: " + intent.activity.className
13145                                + " origPrio: " + intent.getPriority());
13146                    }
13147                    intent.setPriority(0);
13148                    return;
13149                }
13150            }
13151
13152            // find matching schemes subsets
13153            final Iterator<String> schemesIterator = intent.schemesIterator();
13154            if (schemesIterator != null) {
13155                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
13156                        schemesIterator);
13157                if (intentListCopy.size() == 0) {
13158                    // no more intents to match; we're not equivalent
13159                    if (DEBUG_FILTERS) {
13160                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
13161                                + " package: " + applicationInfo.packageName
13162                                + " activity: " + intent.activity.className
13163                                + " origPrio: " + intent.getPriority());
13164                    }
13165                    intent.setPriority(0);
13166                    return;
13167                }
13168            }
13169
13170            // find matching authorities subsets
13171            final Iterator<IntentFilter.AuthorityEntry>
13172                    authoritiesIterator = intent.authoritiesIterator();
13173            if (authoritiesIterator != null) {
13174                getIntentListSubset(intentListCopy,
13175                        new AuthoritiesIterGenerator(),
13176                        authoritiesIterator);
13177                if (intentListCopy.size() == 0) {
13178                    // no more intents to match; we're not equivalent
13179                    if (DEBUG_FILTERS) {
13180                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
13181                                + " package: " + applicationInfo.packageName
13182                                + " activity: " + intent.activity.className
13183                                + " origPrio: " + intent.getPriority());
13184                    }
13185                    intent.setPriority(0);
13186                    return;
13187                }
13188            }
13189
13190            // we found matching filter(s); app gets the max priority of all intents
13191            int cappedPriority = 0;
13192            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
13193                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
13194            }
13195            if (intent.getPriority() > cappedPriority) {
13196                if (DEBUG_FILTERS) {
13197                    Slog.i(TAG, "Found matching filter(s);"
13198                            + " cap priority to " + cappedPriority + ";"
13199                            + " package: " + applicationInfo.packageName
13200                            + " activity: " + intent.activity.className
13201                            + " origPrio: " + intent.getPriority());
13202                }
13203                intent.setPriority(cappedPriority);
13204                return;
13205            }
13206            // all this for nothing; the requested priority was <= what was on the system
13207        }
13208
13209        public final void addActivity(PackageParser.Activity a, String type) {
13210            mActivities.put(a.getComponentName(), a);
13211            if (DEBUG_SHOW_INFO)
13212                Log.v(
13213                TAG, "  " + type + " " +
13214                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
13215            if (DEBUG_SHOW_INFO)
13216                Log.v(TAG, "    Class=" + a.info.name);
13217            final int NI = a.intents.size();
13218            for (int j=0; j<NI; j++) {
13219                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13220                if ("activity".equals(type)) {
13221                    final PackageSetting ps =
13222                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
13223                    final List<PackageParser.Activity> systemActivities =
13224                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
13225                    adjustPriority(systemActivities, intent);
13226                }
13227                if (DEBUG_SHOW_INFO) {
13228                    Log.v(TAG, "    IntentFilter:");
13229                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13230                }
13231                if (!intent.debugCheck()) {
13232                    Log.w(TAG, "==> For Activity " + a.info.name);
13233                }
13234                addFilter(intent);
13235            }
13236        }
13237
13238        public final void removeActivity(PackageParser.Activity a, String type) {
13239            mActivities.remove(a.getComponentName());
13240            if (DEBUG_SHOW_INFO) {
13241                Log.v(TAG, "  " + type + " "
13242                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
13243                                : a.info.name) + ":");
13244                Log.v(TAG, "    Class=" + a.info.name);
13245            }
13246            final int NI = a.intents.size();
13247            for (int j=0; j<NI; j++) {
13248                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
13249                if (DEBUG_SHOW_INFO) {
13250                    Log.v(TAG, "    IntentFilter:");
13251                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13252                }
13253                removeFilter(intent);
13254            }
13255        }
13256
13257        @Override
13258        protected boolean allowFilterResult(
13259                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
13260            ActivityInfo filterAi = filter.activity.info;
13261            for (int i=dest.size()-1; i>=0; i--) {
13262                ActivityInfo destAi = dest.get(i).activityInfo;
13263                if (destAi.name == filterAi.name
13264                        && destAi.packageName == filterAi.packageName) {
13265                    return false;
13266                }
13267            }
13268            return true;
13269        }
13270
13271        @Override
13272        protected ActivityIntentInfo[] newArray(int size) {
13273            return new ActivityIntentInfo[size];
13274        }
13275
13276        @Override
13277        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
13278            if (!sUserManager.exists(userId)) return true;
13279            PackageParser.Package p = filter.activity.owner;
13280            if (p != null) {
13281                PackageSetting ps = (PackageSetting)p.mExtras;
13282                if (ps != null) {
13283                    // System apps are never considered stopped for purposes of
13284                    // filtering, because there may be no way for the user to
13285                    // actually re-launch them.
13286                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
13287                            && ps.getStopped(userId);
13288                }
13289            }
13290            return false;
13291        }
13292
13293        @Override
13294        protected boolean isPackageForFilter(String packageName,
13295                PackageParser.ActivityIntentInfo info) {
13296            return packageName.equals(info.activity.owner.packageName);
13297        }
13298
13299        @Override
13300        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
13301                int match, int userId) {
13302            if (!sUserManager.exists(userId)) return null;
13303            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
13304                return null;
13305            }
13306            final PackageParser.Activity activity = info.activity;
13307            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
13308            if (ps == null) {
13309                return null;
13310            }
13311            final PackageUserState userState = ps.readUserState(userId);
13312            ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId);
13313            if (ai == null) {
13314                return null;
13315            }
13316            final boolean matchExplicitlyVisibleOnly =
13317                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
13318            final boolean matchVisibleToInstantApp =
13319                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13320            final boolean componentVisible =
13321                    matchVisibleToInstantApp
13322                    && info.isVisibleToInstantApp()
13323                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
13324            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13325            // throw out filters that aren't visible to ephemeral apps
13326            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
13327                return null;
13328            }
13329            // throw out instant app filters if we're not explicitly requesting them
13330            if (!matchInstantApp && userState.instantApp) {
13331                return null;
13332            }
13333            // throw out instant app filters if updates are available; will trigger
13334            // instant app resolution
13335            if (userState.instantApp && ps.isUpdateAvailable()) {
13336                return null;
13337            }
13338            final ResolveInfo res = new ResolveInfo();
13339            res.activityInfo = ai;
13340            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13341                res.filter = info;
13342            }
13343            if (info != null) {
13344                res.handleAllWebDataURI = info.handleAllWebDataURI();
13345            }
13346            res.priority = info.getPriority();
13347            res.preferredOrder = activity.owner.mPreferredOrder;
13348            //System.out.println("Result: " + res.activityInfo.className +
13349            //                   " = " + res.priority);
13350            res.match = match;
13351            res.isDefault = info.hasDefault;
13352            res.labelRes = info.labelRes;
13353            res.nonLocalizedLabel = info.nonLocalizedLabel;
13354            if (userNeedsBadging(userId)) {
13355                res.noResourceId = true;
13356            } else {
13357                res.icon = info.icon;
13358            }
13359            res.iconResourceId = info.icon;
13360            res.system = res.activityInfo.applicationInfo.isSystemApp();
13361            res.isInstantAppAvailable = userState.instantApp;
13362            return res;
13363        }
13364
13365        @Override
13366        protected void sortResults(List<ResolveInfo> results) {
13367            Collections.sort(results, mResolvePrioritySorter);
13368        }
13369
13370        @Override
13371        protected void dumpFilter(PrintWriter out, String prefix,
13372                PackageParser.ActivityIntentInfo filter) {
13373            out.print(prefix); out.print(
13374                    Integer.toHexString(System.identityHashCode(filter.activity)));
13375                    out.print(' ');
13376                    filter.activity.printComponentShortName(out);
13377                    out.print(" filter ");
13378                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13379        }
13380
13381        @Override
13382        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
13383            return filter.activity;
13384        }
13385
13386        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13387            PackageParser.Activity activity = (PackageParser.Activity)label;
13388            out.print(prefix); out.print(
13389                    Integer.toHexString(System.identityHashCode(activity)));
13390                    out.print(' ');
13391                    activity.printComponentShortName(out);
13392            if (count > 1) {
13393                out.print(" ("); out.print(count); out.print(" filters)");
13394            }
13395            out.println();
13396        }
13397
13398        // Keys are String (activity class name), values are Activity.
13399        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
13400                = new ArrayMap<ComponentName, PackageParser.Activity>();
13401        private int mFlags;
13402    }
13403
13404    private final class ServiceIntentResolver
13405            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
13406        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13407                boolean defaultOnly, int userId) {
13408            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13409            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13410        }
13411
13412        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13413                int userId) {
13414            if (!sUserManager.exists(userId)) return null;
13415            mFlags = flags;
13416            return super.queryIntent(intent, resolvedType,
13417                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13418                    userId);
13419        }
13420
13421        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13422                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
13423            if (!sUserManager.exists(userId)) return null;
13424            if (packageServices == null) {
13425                return null;
13426            }
13427            mFlags = flags;
13428            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
13429            final int N = packageServices.size();
13430            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
13431                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
13432
13433            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
13434            for (int i = 0; i < N; ++i) {
13435                intentFilters = packageServices.get(i).intents;
13436                if (intentFilters != null && intentFilters.size() > 0) {
13437                    PackageParser.ServiceIntentInfo[] array =
13438                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
13439                    intentFilters.toArray(array);
13440                    listCut.add(array);
13441                }
13442            }
13443            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13444        }
13445
13446        public final void addService(PackageParser.Service s) {
13447            mServices.put(s.getComponentName(), s);
13448            if (DEBUG_SHOW_INFO) {
13449                Log.v(TAG, "  "
13450                        + (s.info.nonLocalizedLabel != null
13451                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13452                Log.v(TAG, "    Class=" + s.info.name);
13453            }
13454            final int NI = s.intents.size();
13455            int j;
13456            for (j=0; j<NI; j++) {
13457                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13458                if (DEBUG_SHOW_INFO) {
13459                    Log.v(TAG, "    IntentFilter:");
13460                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13461                }
13462                if (!intent.debugCheck()) {
13463                    Log.w(TAG, "==> For Service " + s.info.name);
13464                }
13465                addFilter(intent);
13466            }
13467        }
13468
13469        public final void removeService(PackageParser.Service s) {
13470            mServices.remove(s.getComponentName());
13471            if (DEBUG_SHOW_INFO) {
13472                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
13473                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
13474                Log.v(TAG, "    Class=" + s.info.name);
13475            }
13476            final int NI = s.intents.size();
13477            int j;
13478            for (j=0; j<NI; j++) {
13479                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
13480                if (DEBUG_SHOW_INFO) {
13481                    Log.v(TAG, "    IntentFilter:");
13482                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13483                }
13484                removeFilter(intent);
13485            }
13486        }
13487
13488        @Override
13489        protected boolean allowFilterResult(
13490                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
13491            ServiceInfo filterSi = filter.service.info;
13492            for (int i=dest.size()-1; i>=0; i--) {
13493                ServiceInfo destAi = dest.get(i).serviceInfo;
13494                if (destAi.name == filterSi.name
13495                        && destAi.packageName == filterSi.packageName) {
13496                    return false;
13497                }
13498            }
13499            return true;
13500        }
13501
13502        @Override
13503        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
13504            return new PackageParser.ServiceIntentInfo[size];
13505        }
13506
13507        @Override
13508        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
13509            if (!sUserManager.exists(userId)) return true;
13510            PackageParser.Package p = filter.service.owner;
13511            if (p != null) {
13512                PackageSetting ps = (PackageSetting)p.mExtras;
13513                if (ps != null) {
13514                    // System apps are never considered stopped for purposes of
13515                    // filtering, because there may be no way for the user to
13516                    // actually re-launch them.
13517                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13518                            && ps.getStopped(userId);
13519                }
13520            }
13521            return false;
13522        }
13523
13524        @Override
13525        protected boolean isPackageForFilter(String packageName,
13526                PackageParser.ServiceIntentInfo info) {
13527            return packageName.equals(info.service.owner.packageName);
13528        }
13529
13530        @Override
13531        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
13532                int match, int userId) {
13533            if (!sUserManager.exists(userId)) return null;
13534            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
13535            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
13536                return null;
13537            }
13538            final PackageParser.Service service = info.service;
13539            PackageSetting ps = (PackageSetting) service.owner.mExtras;
13540            if (ps == null) {
13541                return null;
13542            }
13543            final PackageUserState userState = ps.readUserState(userId);
13544            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
13545                    userState, userId);
13546            if (si == null) {
13547                return null;
13548            }
13549            final boolean matchVisibleToInstantApp =
13550                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13551            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13552            // throw out filters that aren't visible to ephemeral apps
13553            if (matchVisibleToInstantApp
13554                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13555                return null;
13556            }
13557            // throw out ephemeral filters if we're not explicitly requesting them
13558            if (!isInstantApp && userState.instantApp) {
13559                return null;
13560            }
13561            // throw out instant app filters if updates are available; will trigger
13562            // instant app resolution
13563            if (userState.instantApp && ps.isUpdateAvailable()) {
13564                return null;
13565            }
13566            final ResolveInfo res = new ResolveInfo();
13567            res.serviceInfo = si;
13568            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
13569                res.filter = filter;
13570            }
13571            res.priority = info.getPriority();
13572            res.preferredOrder = service.owner.mPreferredOrder;
13573            res.match = match;
13574            res.isDefault = info.hasDefault;
13575            res.labelRes = info.labelRes;
13576            res.nonLocalizedLabel = info.nonLocalizedLabel;
13577            res.icon = info.icon;
13578            res.system = res.serviceInfo.applicationInfo.isSystemApp();
13579            return res;
13580        }
13581
13582        @Override
13583        protected void sortResults(List<ResolveInfo> results) {
13584            Collections.sort(results, mResolvePrioritySorter);
13585        }
13586
13587        @Override
13588        protected void dumpFilter(PrintWriter out, String prefix,
13589                PackageParser.ServiceIntentInfo filter) {
13590            out.print(prefix); out.print(
13591                    Integer.toHexString(System.identityHashCode(filter.service)));
13592                    out.print(' ');
13593                    filter.service.printComponentShortName(out);
13594                    out.print(" filter ");
13595                    out.println(Integer.toHexString(System.identityHashCode(filter)));
13596        }
13597
13598        @Override
13599        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
13600            return filter.service;
13601        }
13602
13603        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13604            PackageParser.Service service = (PackageParser.Service)label;
13605            out.print(prefix); out.print(
13606                    Integer.toHexString(System.identityHashCode(service)));
13607                    out.print(' ');
13608                    service.printComponentShortName(out);
13609            if (count > 1) {
13610                out.print(" ("); out.print(count); out.print(" filters)");
13611            }
13612            out.println();
13613        }
13614
13615//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
13616//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
13617//            final List<ResolveInfo> retList = Lists.newArrayList();
13618//            while (i.hasNext()) {
13619//                final ResolveInfo resolveInfo = (ResolveInfo) i;
13620//                if (isEnabledLP(resolveInfo.serviceInfo)) {
13621//                    retList.add(resolveInfo);
13622//                }
13623//            }
13624//            return retList;
13625//        }
13626
13627        // Keys are String (activity class name), values are Activity.
13628        private final ArrayMap<ComponentName, PackageParser.Service> mServices
13629                = new ArrayMap<ComponentName, PackageParser.Service>();
13630        private int mFlags;
13631    }
13632
13633    private final class ProviderIntentResolver
13634            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13635        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13636                boolean defaultOnly, int userId) {
13637            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13638            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13639        }
13640
13641        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13642                int userId) {
13643            if (!sUserManager.exists(userId))
13644                return null;
13645            mFlags = flags;
13646            return super.queryIntent(intent, resolvedType,
13647                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13648                    userId);
13649        }
13650
13651        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13652                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13653            if (!sUserManager.exists(userId))
13654                return null;
13655            if (packageProviders == null) {
13656                return null;
13657            }
13658            mFlags = flags;
13659            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13660            final int N = packageProviders.size();
13661            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13662                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13663
13664            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13665            for (int i = 0; i < N; ++i) {
13666                intentFilters = packageProviders.get(i).intents;
13667                if (intentFilters != null && intentFilters.size() > 0) {
13668                    PackageParser.ProviderIntentInfo[] array =
13669                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13670                    intentFilters.toArray(array);
13671                    listCut.add(array);
13672                }
13673            }
13674            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13675        }
13676
13677        public final void addProvider(PackageParser.Provider p) {
13678            if (mProviders.containsKey(p.getComponentName())) {
13679                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13680                return;
13681            }
13682
13683            mProviders.put(p.getComponentName(), p);
13684            if (DEBUG_SHOW_INFO) {
13685                Log.v(TAG, "  "
13686                        + (p.info.nonLocalizedLabel != null
13687                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13688                Log.v(TAG, "    Class=" + p.info.name);
13689            }
13690            final int NI = p.intents.size();
13691            int j;
13692            for (j = 0; j < NI; j++) {
13693                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13694                if (DEBUG_SHOW_INFO) {
13695                    Log.v(TAG, "    IntentFilter:");
13696                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13697                }
13698                if (!intent.debugCheck()) {
13699                    Log.w(TAG, "==> For Provider " + p.info.name);
13700                }
13701                addFilter(intent);
13702            }
13703        }
13704
13705        public final void removeProvider(PackageParser.Provider p) {
13706            mProviders.remove(p.getComponentName());
13707            if (DEBUG_SHOW_INFO) {
13708                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13709                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13710                Log.v(TAG, "    Class=" + p.info.name);
13711            }
13712            final int NI = p.intents.size();
13713            int j;
13714            for (j = 0; j < NI; j++) {
13715                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13716                if (DEBUG_SHOW_INFO) {
13717                    Log.v(TAG, "    IntentFilter:");
13718                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13719                }
13720                removeFilter(intent);
13721            }
13722        }
13723
13724        @Override
13725        protected boolean allowFilterResult(
13726                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13727            ProviderInfo filterPi = filter.provider.info;
13728            for (int i = dest.size() - 1; i >= 0; i--) {
13729                ProviderInfo destPi = dest.get(i).providerInfo;
13730                if (destPi.name == filterPi.name
13731                        && destPi.packageName == filterPi.packageName) {
13732                    return false;
13733                }
13734            }
13735            return true;
13736        }
13737
13738        @Override
13739        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13740            return new PackageParser.ProviderIntentInfo[size];
13741        }
13742
13743        @Override
13744        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13745            if (!sUserManager.exists(userId))
13746                return true;
13747            PackageParser.Package p = filter.provider.owner;
13748            if (p != null) {
13749                PackageSetting ps = (PackageSetting) p.mExtras;
13750                if (ps != null) {
13751                    // System apps are never considered stopped for purposes of
13752                    // filtering, because there may be no way for the user to
13753                    // actually re-launch them.
13754                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13755                            && ps.getStopped(userId);
13756                }
13757            }
13758            return false;
13759        }
13760
13761        @Override
13762        protected boolean isPackageForFilter(String packageName,
13763                PackageParser.ProviderIntentInfo info) {
13764            return packageName.equals(info.provider.owner.packageName);
13765        }
13766
13767        @Override
13768        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13769                int match, int userId) {
13770            if (!sUserManager.exists(userId))
13771                return null;
13772            final PackageParser.ProviderIntentInfo info = filter;
13773            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13774                return null;
13775            }
13776            final PackageParser.Provider provider = info.provider;
13777            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13778            if (ps == null) {
13779                return null;
13780            }
13781            final PackageUserState userState = ps.readUserState(userId);
13782            final boolean matchVisibleToInstantApp =
13783                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13784            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13785            // throw out filters that aren't visible to instant applications
13786            if (matchVisibleToInstantApp
13787                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13788                return null;
13789            }
13790            // throw out instant application filters if we're not explicitly requesting them
13791            if (!isInstantApp && userState.instantApp) {
13792                return null;
13793            }
13794            // throw out instant application filters if updates are available; will trigger
13795            // instant application resolution
13796            if (userState.instantApp && ps.isUpdateAvailable()) {
13797                return null;
13798            }
13799            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13800                    userState, userId);
13801            if (pi == null) {
13802                return null;
13803            }
13804            final ResolveInfo res = new ResolveInfo();
13805            res.providerInfo = pi;
13806            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13807                res.filter = filter;
13808            }
13809            res.priority = info.getPriority();
13810            res.preferredOrder = provider.owner.mPreferredOrder;
13811            res.match = match;
13812            res.isDefault = info.hasDefault;
13813            res.labelRes = info.labelRes;
13814            res.nonLocalizedLabel = info.nonLocalizedLabel;
13815            res.icon = info.icon;
13816            res.system = res.providerInfo.applicationInfo.isSystemApp();
13817            return res;
13818        }
13819
13820        @Override
13821        protected void sortResults(List<ResolveInfo> results) {
13822            Collections.sort(results, mResolvePrioritySorter);
13823        }
13824
13825        @Override
13826        protected void dumpFilter(PrintWriter out, String prefix,
13827                PackageParser.ProviderIntentInfo filter) {
13828            out.print(prefix);
13829            out.print(
13830                    Integer.toHexString(System.identityHashCode(filter.provider)));
13831            out.print(' ');
13832            filter.provider.printComponentShortName(out);
13833            out.print(" filter ");
13834            out.println(Integer.toHexString(System.identityHashCode(filter)));
13835        }
13836
13837        @Override
13838        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13839            return filter.provider;
13840        }
13841
13842        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13843            PackageParser.Provider provider = (PackageParser.Provider)label;
13844            out.print(prefix); out.print(
13845                    Integer.toHexString(System.identityHashCode(provider)));
13846                    out.print(' ');
13847                    provider.printComponentShortName(out);
13848            if (count > 1) {
13849                out.print(" ("); out.print(count); out.print(" filters)");
13850            }
13851            out.println();
13852        }
13853
13854        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13855                = new ArrayMap<ComponentName, PackageParser.Provider>();
13856        private int mFlags;
13857    }
13858
13859    static final class EphemeralIntentResolver
13860            extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> {
13861        /**
13862         * The result that has the highest defined order. Ordering applies on a
13863         * per-package basis. Mapping is from package name to Pair of order and
13864         * EphemeralResolveInfo.
13865         * <p>
13866         * NOTE: This is implemented as a field variable for convenience and efficiency.
13867         * By having a field variable, we're able to track filter ordering as soon as
13868         * a non-zero order is defined. Otherwise, multiple loops across the result set
13869         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13870         * this needs to be contained entirely within {@link #filterResults}.
13871         */
13872        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13873
13874        @Override
13875        protected AuxiliaryResolveInfo[] newArray(int size) {
13876            return new AuxiliaryResolveInfo[size];
13877        }
13878
13879        @Override
13880        protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) {
13881            return true;
13882        }
13883
13884        @Override
13885        protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match,
13886                int userId) {
13887            if (!sUserManager.exists(userId)) {
13888                return null;
13889            }
13890            final String packageName = responseObj.resolveInfo.getPackageName();
13891            final Integer order = responseObj.getOrder();
13892            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13893                    mOrderResult.get(packageName);
13894            // ordering is enabled and this item's order isn't high enough
13895            if (lastOrderResult != null && lastOrderResult.first >= order) {
13896                return null;
13897            }
13898            final InstantAppResolveInfo res = responseObj.resolveInfo;
13899            if (order > 0) {
13900                // non-zero order, enable ordering
13901                mOrderResult.put(packageName, new Pair<>(order, res));
13902            }
13903            return responseObj;
13904        }
13905
13906        @Override
13907        protected void filterResults(List<AuxiliaryResolveInfo> results) {
13908            // only do work if ordering is enabled [most of the time it won't be]
13909            if (mOrderResult.size() == 0) {
13910                return;
13911            }
13912            int resultSize = results.size();
13913            for (int i = 0; i < resultSize; i++) {
13914                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13915                final String packageName = info.getPackageName();
13916                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13917                if (savedInfo == null) {
13918                    // package doesn't having ordering
13919                    continue;
13920                }
13921                if (savedInfo.second == info) {
13922                    // circled back to the highest ordered item; remove from order list
13923                    mOrderResult.remove(savedInfo);
13924                    if (mOrderResult.size() == 0) {
13925                        // no more ordered items
13926                        break;
13927                    }
13928                    continue;
13929                }
13930                // item has a worse order, remove it from the result list
13931                results.remove(i);
13932                resultSize--;
13933                i--;
13934            }
13935        }
13936    }
13937
13938    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13939            new Comparator<ResolveInfo>() {
13940        public int compare(ResolveInfo r1, ResolveInfo r2) {
13941            int v1 = r1.priority;
13942            int v2 = r2.priority;
13943            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13944            if (v1 != v2) {
13945                return (v1 > v2) ? -1 : 1;
13946            }
13947            v1 = r1.preferredOrder;
13948            v2 = r2.preferredOrder;
13949            if (v1 != v2) {
13950                return (v1 > v2) ? -1 : 1;
13951            }
13952            if (r1.isDefault != r2.isDefault) {
13953                return r1.isDefault ? -1 : 1;
13954            }
13955            v1 = r1.match;
13956            v2 = r2.match;
13957            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13958            if (v1 != v2) {
13959                return (v1 > v2) ? -1 : 1;
13960            }
13961            if (r1.system != r2.system) {
13962                return r1.system ? -1 : 1;
13963            }
13964            if (r1.activityInfo != null) {
13965                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13966            }
13967            if (r1.serviceInfo != null) {
13968                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13969            }
13970            if (r1.providerInfo != null) {
13971                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13972            }
13973            return 0;
13974        }
13975    };
13976
13977    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13978            new Comparator<ProviderInfo>() {
13979        public int compare(ProviderInfo p1, ProviderInfo p2) {
13980            final int v1 = p1.initOrder;
13981            final int v2 = p2.initOrder;
13982            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13983        }
13984    };
13985
13986    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13987            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13988            final int[] userIds) {
13989        mHandler.post(new Runnable() {
13990            @Override
13991            public void run() {
13992                try {
13993                    final IActivityManager am = ActivityManager.getService();
13994                    if (am == null) return;
13995                    final int[] resolvedUserIds;
13996                    if (userIds == null) {
13997                        resolvedUserIds = am.getRunningUserIds();
13998                    } else {
13999                        resolvedUserIds = userIds;
14000                    }
14001                    for (int id : resolvedUserIds) {
14002                        final Intent intent = new Intent(action,
14003                                pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
14004                        if (extras != null) {
14005                            intent.putExtras(extras);
14006                        }
14007                        if (targetPkg != null) {
14008                            intent.setPackage(targetPkg);
14009                        }
14010                        // Modify the UID when posting to other users
14011                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
14012                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
14013                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
14014                            intent.putExtra(Intent.EXTRA_UID, uid);
14015                        }
14016                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
14017                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
14018                        if (DEBUG_BROADCASTS) {
14019                            RuntimeException here = new RuntimeException("here");
14020                            here.fillInStackTrace();
14021                            Slog.d(TAG, "Sending to user " + id + ": "
14022                                    + intent.toShortString(false, true, false, false)
14023                                    + " " + intent.getExtras(), here);
14024                        }
14025                        am.broadcastIntent(null, intent, null, finishedReceiver,
14026                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
14027                                null, finishedReceiver != null, false, id);
14028                    }
14029                } catch (RemoteException ex) {
14030                }
14031            }
14032        });
14033    }
14034
14035    /**
14036     * Check if the external storage media is available. This is true if there
14037     * is a mounted external storage medium or if the external storage is
14038     * emulated.
14039     */
14040    private boolean isExternalMediaAvailable() {
14041        return mMediaMounted || Environment.isExternalStorageEmulated();
14042    }
14043
14044    @Override
14045    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
14046        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14047            return null;
14048        }
14049        // writer
14050        synchronized (mPackages) {
14051            if (!isExternalMediaAvailable()) {
14052                // If the external storage is no longer mounted at this point,
14053                // the caller may not have been able to delete all of this
14054                // packages files and can not delete any more.  Bail.
14055                return null;
14056            }
14057            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
14058            if (lastPackage != null) {
14059                pkgs.remove(lastPackage);
14060            }
14061            if (pkgs.size() > 0) {
14062                return pkgs.get(0);
14063            }
14064        }
14065        return null;
14066    }
14067
14068    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
14069        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
14070                userId, andCode ? 1 : 0, packageName);
14071        if (mSystemReady) {
14072            msg.sendToTarget();
14073        } else {
14074            if (mPostSystemReadyMessages == null) {
14075                mPostSystemReadyMessages = new ArrayList<>();
14076            }
14077            mPostSystemReadyMessages.add(msg);
14078        }
14079    }
14080
14081    void startCleaningPackages() {
14082        // reader
14083        if (!isExternalMediaAvailable()) {
14084            return;
14085        }
14086        synchronized (mPackages) {
14087            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
14088                return;
14089            }
14090        }
14091        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
14092        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
14093        IActivityManager am = ActivityManager.getService();
14094        if (am != null) {
14095            int dcsUid = -1;
14096            synchronized (mPackages) {
14097                if (!mDefaultContainerWhitelisted) {
14098                    mDefaultContainerWhitelisted = true;
14099                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
14100                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
14101                }
14102            }
14103            try {
14104                if (dcsUid > 0) {
14105                    am.backgroundWhitelistUid(dcsUid);
14106                }
14107                am.startService(null, intent, null, false, mContext.getOpPackageName(),
14108                        UserHandle.USER_SYSTEM);
14109            } catch (RemoteException e) {
14110            }
14111        }
14112    }
14113
14114    @Override
14115    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
14116            int installFlags, String installerPackageName, int userId) {
14117        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
14118
14119        final int callingUid = Binder.getCallingUid();
14120        enforceCrossUserPermission(callingUid, userId,
14121                true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser");
14122
14123        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14124            try {
14125                if (observer != null) {
14126                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
14127                }
14128            } catch (RemoteException re) {
14129            }
14130            return;
14131        }
14132
14133        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
14134            installFlags |= PackageManager.INSTALL_FROM_ADB;
14135
14136        } else {
14137            // Caller holds INSTALL_PACKAGES permission, so we're less strict
14138            // about installerPackageName.
14139
14140            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
14141            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
14142        }
14143
14144        UserHandle user;
14145        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
14146            user = UserHandle.ALL;
14147        } else {
14148            user = new UserHandle(userId);
14149        }
14150
14151        // Only system components can circumvent runtime permissions when installing.
14152        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
14153                && mContext.checkCallingOrSelfPermission(Manifest.permission
14154                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
14155            throw new SecurityException("You need the "
14156                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
14157                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
14158        }
14159
14160        if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0
14161                || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
14162            throw new IllegalArgumentException(
14163                    "New installs into ASEC containers no longer supported");
14164        }
14165
14166        final File originFile = new File(originPath);
14167        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
14168
14169        final Message msg = mHandler.obtainMessage(INIT_COPY);
14170        final VerificationInfo verificationInfo = new VerificationInfo(
14171                null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid);
14172        final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer,
14173                installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user,
14174                null /*packageAbiOverride*/, null /*grantedPermissions*/,
14175                null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN);
14176        params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params));
14177        msg.obj = params;
14178
14179        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser",
14180                System.identityHashCode(msg.obj));
14181        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14182                System.identityHashCode(msg.obj));
14183
14184        mHandler.sendMessage(msg);
14185    }
14186
14187
14188    /**
14189     * Ensure that the install reason matches what we know about the package installer (e.g. whether
14190     * it is acting on behalf on an enterprise or the user).
14191     *
14192     * Note that the ordering of the conditionals in this method is important. The checks we perform
14193     * are as follows, in this order:
14194     *
14195     * 1) If the install is being performed by a system app, we can trust the app to have set the
14196     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
14197     *    what it is.
14198     * 2) If the install is being performed by a device or profile owner app, the install reason
14199     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
14200     *    set the install reason correctly. If the app targets an older SDK version where install
14201     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
14202     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
14203     * 3) In all other cases, the install is being performed by a regular app that is neither part
14204     *    of the system nor a device or profile owner. We have no reason to believe that this app is
14205     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
14206     *    set to enterprise policy and if so, change it to unknown instead.
14207     */
14208    private int fixUpInstallReason(String installerPackageName, int installerUid,
14209            int installReason) {
14210        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
14211                == PERMISSION_GRANTED) {
14212            // If the install is being performed by a system app, we trust that app to have set the
14213            // install reason correctly.
14214            return installReason;
14215        }
14216
14217        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
14218            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
14219        if (dpm != null) {
14220            ComponentName owner = null;
14221            try {
14222                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
14223                if (owner == null) {
14224                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
14225                }
14226            } catch (RemoteException e) {
14227            }
14228            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
14229                // If the install is being performed by a device or profile owner, the install
14230                // reason should be enterprise policy.
14231                return PackageManager.INSTALL_REASON_POLICY;
14232            }
14233        }
14234
14235        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
14236            // If the install is being performed by a regular app (i.e. neither system app nor
14237            // device or profile owner), we have no reason to believe that the app is acting on
14238            // behalf of an enterprise. If the app set the install reason to enterprise policy,
14239            // change it to unknown instead.
14240            return PackageManager.INSTALL_REASON_UNKNOWN;
14241        }
14242
14243        // If the install is being performed by a regular app and the install reason was set to any
14244        // value but enterprise policy, leave the install reason unchanged.
14245        return installReason;
14246    }
14247
14248    void installStage(String packageName, File stagedDir, String stagedCid,
14249            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
14250            String installerPackageName, int installerUid, UserHandle user,
14251            Certificate[][] certificates) {
14252        if (DEBUG_EPHEMERAL) {
14253            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14254                Slog.d(TAG, "Ephemeral install of " + packageName);
14255            }
14256        }
14257        final VerificationInfo verificationInfo = new VerificationInfo(
14258                sessionParams.originatingUri, sessionParams.referrerUri,
14259                sessionParams.originatingUid, installerUid);
14260
14261        final OriginInfo origin;
14262        if (stagedDir != null) {
14263            origin = OriginInfo.fromStagedFile(stagedDir);
14264        } else {
14265            origin = OriginInfo.fromStagedContainer(stagedCid);
14266        }
14267
14268        final Message msg = mHandler.obtainMessage(INIT_COPY);
14269        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
14270                sessionParams.installReason);
14271        final InstallParams params = new InstallParams(origin, null, observer,
14272                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
14273                verificationInfo, user, sessionParams.abiOverride,
14274                sessionParams.grantedRuntimePermissions, certificates, installReason);
14275        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
14276        msg.obj = params;
14277
14278        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
14279                System.identityHashCode(msg.obj));
14280        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
14281                System.identityHashCode(msg.obj));
14282
14283        mHandler.sendMessage(msg);
14284    }
14285
14286    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
14287            int userId) {
14288        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
14289        sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId);
14290
14291        // Send a session commit broadcast
14292        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
14293        info.installReason = pkgSetting.getInstallReason(userId);
14294        info.appPackageName = packageName;
14295        sendSessionCommitBroadcast(info, userId);
14296    }
14297
14298    public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) {
14299        if (ArrayUtils.isEmpty(userIds)) {
14300            return;
14301        }
14302        Bundle extras = new Bundle(1);
14303        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
14304        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId));
14305
14306        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
14307                packageName, extras, 0, null, null, userIds);
14308        if (isSystem) {
14309            mHandler.post(() -> {
14310                        for (int userId : userIds) {
14311                            sendBootCompletedBroadcastToSystemApp(packageName, userId);
14312                        }
14313                    }
14314            );
14315        }
14316    }
14317
14318    /**
14319     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
14320     * automatically without needing an explicit launch.
14321     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
14322     */
14323    private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) {
14324        // If user is not running, the app didn't miss any broadcast
14325        if (!mUserManagerInternal.isUserRunning(userId)) {
14326            return;
14327        }
14328        final IActivityManager am = ActivityManager.getService();
14329        try {
14330            // Deliver LOCKED_BOOT_COMPLETED first
14331            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
14332                    .setPackage(packageName);
14333            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
14334            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
14335                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14336
14337            // Deliver BOOT_COMPLETED only if user is unlocked
14338            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
14339                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
14340                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
14341                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
14342            }
14343        } catch (RemoteException e) {
14344            throw e.rethrowFromSystemServer();
14345        }
14346    }
14347
14348    @Override
14349    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
14350            int userId) {
14351        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14352        PackageSetting pkgSetting;
14353        final int uid = Binder.getCallingUid();
14354        enforceCrossUserPermission(uid, userId,
14355                true /* requireFullPermission */, true /* checkShell */,
14356                "setApplicationHiddenSetting for user " + userId);
14357
14358        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
14359            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
14360            return false;
14361        }
14362
14363        long callingId = Binder.clearCallingIdentity();
14364        try {
14365            boolean sendAdded = false;
14366            boolean sendRemoved = false;
14367            // writer
14368            synchronized (mPackages) {
14369                pkgSetting = mSettings.mPackages.get(packageName);
14370                if (pkgSetting == null) {
14371                    return false;
14372                }
14373                // Do not allow "android" is being disabled
14374                if ("android".equals(packageName)) {
14375                    Slog.w(TAG, "Cannot hide package: android");
14376                    return false;
14377                }
14378                // Cannot hide static shared libs as they are considered
14379                // a part of the using app (emulating static linking). Also
14380                // static libs are installed always on internal storage.
14381                PackageParser.Package pkg = mPackages.get(packageName);
14382                if (pkg != null && pkg.staticSharedLibName != null) {
14383                    Slog.w(TAG, "Cannot hide package: " + packageName
14384                            + " providing static shared library: "
14385                            + pkg.staticSharedLibName);
14386                    return false;
14387                }
14388                // Only allow protected packages to hide themselves.
14389                if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId)
14390                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14391                    Slog.w(TAG, "Not hiding protected package: " + packageName);
14392                    return false;
14393                }
14394
14395                if (pkgSetting.getHidden(userId) != hidden) {
14396                    pkgSetting.setHidden(hidden, userId);
14397                    mSettings.writePackageRestrictionsLPr(userId);
14398                    if (hidden) {
14399                        sendRemoved = true;
14400                    } else {
14401                        sendAdded = true;
14402                    }
14403                }
14404            }
14405            if (sendAdded) {
14406                sendPackageAddedForUser(packageName, pkgSetting, userId);
14407                return true;
14408            }
14409            if (sendRemoved) {
14410                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
14411                        "hiding pkg");
14412                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
14413                return true;
14414            }
14415        } finally {
14416            Binder.restoreCallingIdentity(callingId);
14417        }
14418        return false;
14419    }
14420
14421    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
14422            int userId) {
14423        final PackageRemovedInfo info = new PackageRemovedInfo(this);
14424        info.removedPackage = packageName;
14425        info.installerPackageName = pkgSetting.installerPackageName;
14426        info.removedUsers = new int[] {userId};
14427        info.broadcastUsers = new int[] {userId};
14428        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
14429        info.sendPackageRemovedBroadcasts(true /*killApp*/);
14430    }
14431
14432    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
14433        if (pkgList.length > 0) {
14434            Bundle extras = new Bundle(1);
14435            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14436
14437            sendPackageBroadcast(
14438                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
14439                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
14440                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
14441                    new int[] {userId});
14442        }
14443    }
14444
14445    /**
14446     * Returns true if application is not found or there was an error. Otherwise it returns
14447     * the hidden state of the package for the given user.
14448     */
14449    @Override
14450    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
14451        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14452        final int callingUid = Binder.getCallingUid();
14453        enforceCrossUserPermission(callingUid, userId,
14454                true /* requireFullPermission */, false /* checkShell */,
14455                "getApplicationHidden for user " + userId);
14456        PackageSetting ps;
14457        long callingId = Binder.clearCallingIdentity();
14458        try {
14459            // writer
14460            synchronized (mPackages) {
14461                ps = mSettings.mPackages.get(packageName);
14462                if (ps == null) {
14463                    return true;
14464                }
14465                if (filterAppAccessLPr(ps, callingUid, userId)) {
14466                    return true;
14467                }
14468                return ps.getHidden(userId);
14469            }
14470        } finally {
14471            Binder.restoreCallingIdentity(callingId);
14472        }
14473    }
14474
14475    /**
14476     * @hide
14477     */
14478    @Override
14479    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
14480            int installReason) {
14481        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
14482                null);
14483        PackageSetting pkgSetting;
14484        final int callingUid = Binder.getCallingUid();
14485        enforceCrossUserPermission(callingUid, userId,
14486                true /* requireFullPermission */, true /* checkShell */,
14487                "installExistingPackage for user " + userId);
14488        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
14489            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
14490        }
14491
14492        long callingId = Binder.clearCallingIdentity();
14493        try {
14494            boolean installed = false;
14495            final boolean instantApp =
14496                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
14497            final boolean fullApp =
14498                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
14499
14500            // writer
14501            synchronized (mPackages) {
14502                pkgSetting = mSettings.mPackages.get(packageName);
14503                if (pkgSetting == null) {
14504                    return PackageManager.INSTALL_FAILED_INVALID_URI;
14505                }
14506                if (!pkgSetting.getInstalled(userId)) {
14507                    pkgSetting.setInstalled(true, userId);
14508                    pkgSetting.setHidden(false, userId);
14509                    pkgSetting.setInstallReason(installReason, userId);
14510                    mSettings.writePackageRestrictionsLPr(userId);
14511                    mSettings.writeKernelMappingLPr(pkgSetting);
14512                    installed = true;
14513                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14514                    // upgrade app from instant to full; we don't allow app downgrade
14515                    installed = true;
14516                }
14517                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
14518            }
14519
14520            if (installed) {
14521                if (pkgSetting.pkg != null) {
14522                    synchronized (mInstallLock) {
14523                        // We don't need to freeze for a brand new install
14524                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
14525                    }
14526                }
14527                sendPackageAddedForUser(packageName, pkgSetting, userId);
14528                synchronized (mPackages) {
14529                    updateSequenceNumberLP(packageName, new int[]{ userId });
14530                }
14531            }
14532        } finally {
14533            Binder.restoreCallingIdentity(callingId);
14534        }
14535
14536        return PackageManager.INSTALL_SUCCEEDED;
14537    }
14538
14539    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
14540            boolean instantApp, boolean fullApp) {
14541        // no state specified; do nothing
14542        if (!instantApp && !fullApp) {
14543            return;
14544        }
14545        if (userId != UserHandle.USER_ALL) {
14546            if (instantApp && !pkgSetting.getInstantApp(userId)) {
14547                pkgSetting.setInstantApp(true /*instantApp*/, userId);
14548            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
14549                pkgSetting.setInstantApp(false /*instantApp*/, userId);
14550            }
14551        } else {
14552            for (int currentUserId : sUserManager.getUserIds()) {
14553                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
14554                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
14555                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
14556                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
14557                }
14558            }
14559        }
14560    }
14561
14562    boolean isUserRestricted(int userId, String restrictionKey) {
14563        Bundle restrictions = sUserManager.getUserRestrictions(userId);
14564        if (restrictions.getBoolean(restrictionKey, false)) {
14565            Log.w(TAG, "User is restricted: " + restrictionKey);
14566            return true;
14567        }
14568        return false;
14569    }
14570
14571    @Override
14572    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
14573            int userId) {
14574        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
14575        enforceCrossUserPermission(Binder.getCallingUid(), userId,
14576                true /* requireFullPermission */, true /* checkShell */,
14577                "setPackagesSuspended for user " + userId);
14578
14579        if (ArrayUtils.isEmpty(packageNames)) {
14580            return packageNames;
14581        }
14582
14583        // List of package names for whom the suspended state has changed.
14584        List<String> changedPackages = new ArrayList<>(packageNames.length);
14585        // List of package names for whom the suspended state is not set as requested in this
14586        // method.
14587        List<String> unactionedPackages = new ArrayList<>(packageNames.length);
14588        long callingId = Binder.clearCallingIdentity();
14589        try {
14590            for (int i = 0; i < packageNames.length; i++) {
14591                String packageName = packageNames[i];
14592                boolean changed = false;
14593                final int appId;
14594                synchronized (mPackages) {
14595                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
14596                    if (pkgSetting == null) {
14597                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
14598                                + "\". Skipping suspending/un-suspending.");
14599                        unactionedPackages.add(packageName);
14600                        continue;
14601                    }
14602                    appId = pkgSetting.appId;
14603                    if (pkgSetting.getSuspended(userId) != suspended) {
14604                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
14605                            unactionedPackages.add(packageName);
14606                            continue;
14607                        }
14608                        pkgSetting.setSuspended(suspended, userId);
14609                        mSettings.writePackageRestrictionsLPr(userId);
14610                        changed = true;
14611                        changedPackages.add(packageName);
14612                    }
14613                }
14614
14615                if (changed && suspended) {
14616                    killApplication(packageName, UserHandle.getUid(userId, appId),
14617                            "suspending package");
14618                }
14619            }
14620        } finally {
14621            Binder.restoreCallingIdentity(callingId);
14622        }
14623
14624        if (!changedPackages.isEmpty()) {
14625            sendPackagesSuspendedForUser(changedPackages.toArray(
14626                    new String[changedPackages.size()]), userId, suspended);
14627        }
14628
14629        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14630    }
14631
14632    @Override
14633    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14634        final int callingUid = Binder.getCallingUid();
14635        enforceCrossUserPermission(callingUid, userId,
14636                true /* requireFullPermission */, false /* checkShell */,
14637                "isPackageSuspendedForUser for user " + userId);
14638        synchronized (mPackages) {
14639            final PackageSetting ps = mSettings.mPackages.get(packageName);
14640            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14641                throw new IllegalArgumentException("Unknown target package: " + packageName);
14642            }
14643            return ps.getSuspended(userId);
14644        }
14645    }
14646
14647    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14648        if (isPackageDeviceAdmin(packageName, userId)) {
14649            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14650                    + "\": has an active device admin");
14651            return false;
14652        }
14653
14654        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14655        if (packageName.equals(activeLauncherPackageName)) {
14656            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14657                    + "\": contains the active launcher");
14658            return false;
14659        }
14660
14661        if (packageName.equals(mRequiredInstallerPackage)) {
14662            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14663                    + "\": required for package installation");
14664            return false;
14665        }
14666
14667        if (packageName.equals(mRequiredUninstallerPackage)) {
14668            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14669                    + "\": required for package uninstallation");
14670            return false;
14671        }
14672
14673        if (packageName.equals(mRequiredVerifierPackage)) {
14674            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14675                    + "\": required for package verification");
14676            return false;
14677        }
14678
14679        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14680            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14681                    + "\": is the default dialer");
14682            return false;
14683        }
14684
14685        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14686            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14687                    + "\": protected package");
14688            return false;
14689        }
14690
14691        // Cannot suspend static shared libs as they are considered
14692        // a part of the using app (emulating static linking). Also
14693        // static libs are installed always on internal storage.
14694        PackageParser.Package pkg = mPackages.get(packageName);
14695        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14696            Slog.w(TAG, "Cannot suspend package: " + packageName
14697                    + " providing static shared library: "
14698                    + pkg.staticSharedLibName);
14699            return false;
14700        }
14701
14702        return true;
14703    }
14704
14705    private String getActiveLauncherPackageName(int userId) {
14706        Intent intent = new Intent(Intent.ACTION_MAIN);
14707        intent.addCategory(Intent.CATEGORY_HOME);
14708        ResolveInfo resolveInfo = resolveIntent(
14709                intent,
14710                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14711                PackageManager.MATCH_DEFAULT_ONLY,
14712                userId);
14713
14714        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14715    }
14716
14717    private String getDefaultDialerPackageName(int userId) {
14718        synchronized (mPackages) {
14719            return mSettings.getDefaultDialerPackageNameLPw(userId);
14720        }
14721    }
14722
14723    @Override
14724    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14725        mContext.enforceCallingOrSelfPermission(
14726                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14727                "Only package verification agents can verify applications");
14728
14729        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14730        final PackageVerificationResponse response = new PackageVerificationResponse(
14731                verificationCode, Binder.getCallingUid());
14732        msg.arg1 = id;
14733        msg.obj = response;
14734        mHandler.sendMessage(msg);
14735    }
14736
14737    @Override
14738    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14739            long millisecondsToDelay) {
14740        mContext.enforceCallingOrSelfPermission(
14741                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14742                "Only package verification agents can extend verification timeouts");
14743
14744        final PackageVerificationState state = mPendingVerification.get(id);
14745        final PackageVerificationResponse response = new PackageVerificationResponse(
14746                verificationCodeAtTimeout, Binder.getCallingUid());
14747
14748        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14749            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14750        }
14751        if (millisecondsToDelay < 0) {
14752            millisecondsToDelay = 0;
14753        }
14754        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14755                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14756            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14757        }
14758
14759        if ((state != null) && !state.timeoutExtended()) {
14760            state.extendTimeout();
14761
14762            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14763            msg.arg1 = id;
14764            msg.obj = response;
14765            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14766        }
14767    }
14768
14769    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14770            int verificationCode, UserHandle user) {
14771        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14772        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14773        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14774        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14775        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14776
14777        mContext.sendBroadcastAsUser(intent, user,
14778                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14779    }
14780
14781    private ComponentName matchComponentForVerifier(String packageName,
14782            List<ResolveInfo> receivers) {
14783        ActivityInfo targetReceiver = null;
14784
14785        final int NR = receivers.size();
14786        for (int i = 0; i < NR; i++) {
14787            final ResolveInfo info = receivers.get(i);
14788            if (info.activityInfo == null) {
14789                continue;
14790            }
14791
14792            if (packageName.equals(info.activityInfo.packageName)) {
14793                targetReceiver = info.activityInfo;
14794                break;
14795            }
14796        }
14797
14798        if (targetReceiver == null) {
14799            return null;
14800        }
14801
14802        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14803    }
14804
14805    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14806            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14807        if (pkgInfo.verifiers.length == 0) {
14808            return null;
14809        }
14810
14811        final int N = pkgInfo.verifiers.length;
14812        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14813        for (int i = 0; i < N; i++) {
14814            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14815
14816            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14817                    receivers);
14818            if (comp == null) {
14819                continue;
14820            }
14821
14822            final int verifierUid = getUidForVerifier(verifierInfo);
14823            if (verifierUid == -1) {
14824                continue;
14825            }
14826
14827            if (DEBUG_VERIFY) {
14828                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14829                        + " with the correct signature");
14830            }
14831            sufficientVerifiers.add(comp);
14832            verificationState.addSufficientVerifier(verifierUid);
14833        }
14834
14835        return sufficientVerifiers;
14836    }
14837
14838    private int getUidForVerifier(VerifierInfo verifierInfo) {
14839        synchronized (mPackages) {
14840            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14841            if (pkg == null) {
14842                return -1;
14843            } else if (pkg.mSignatures.length != 1) {
14844                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14845                        + " has more than one signature; ignoring");
14846                return -1;
14847            }
14848
14849            /*
14850             * If the public key of the package's signature does not match
14851             * our expected public key, then this is a different package and
14852             * we should skip.
14853             */
14854
14855            final byte[] expectedPublicKey;
14856            try {
14857                final Signature verifierSig = pkg.mSignatures[0];
14858                final PublicKey publicKey = verifierSig.getPublicKey();
14859                expectedPublicKey = publicKey.getEncoded();
14860            } catch (CertificateException e) {
14861                return -1;
14862            }
14863
14864            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14865
14866            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14867                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14868                        + " does not have the expected public key; ignoring");
14869                return -1;
14870            }
14871
14872            return pkg.applicationInfo.uid;
14873        }
14874    }
14875
14876    @Override
14877    public void finishPackageInstall(int token, boolean didLaunch) {
14878        enforceSystemOrRoot("Only the system is allowed to finish installs");
14879
14880        if (DEBUG_INSTALL) {
14881            Slog.v(TAG, "BM finishing package install for " + token);
14882        }
14883        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14884
14885        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14886        mHandler.sendMessage(msg);
14887    }
14888
14889    /**
14890     * Get the verification agent timeout.  Used for both the APK verifier and the
14891     * intent filter verifier.
14892     *
14893     * @return verification timeout in milliseconds
14894     */
14895    private long getVerificationTimeout() {
14896        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14897                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14898                DEFAULT_VERIFICATION_TIMEOUT);
14899    }
14900
14901    /**
14902     * Get the default verification agent response code.
14903     *
14904     * @return default verification response code
14905     */
14906    private int getDefaultVerificationResponse(UserHandle user) {
14907        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14908            return PackageManager.VERIFICATION_REJECT;
14909        }
14910        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14911                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14912                DEFAULT_VERIFICATION_RESPONSE);
14913    }
14914
14915    /**
14916     * Check whether or not package verification has been enabled.
14917     *
14918     * @return true if verification should be performed
14919     */
14920    private boolean isVerificationEnabled(int userId, int installFlags) {
14921        if (!DEFAULT_VERIFY_ENABLE) {
14922            return false;
14923        }
14924
14925        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14926
14927        // Check if installing from ADB
14928        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14929            // Do not run verification in a test harness environment
14930            if (ActivityManager.isRunningInTestHarness()) {
14931                return false;
14932            }
14933            if (ensureVerifyAppsEnabled) {
14934                return true;
14935            }
14936            // Check if the developer does not want package verification for ADB installs
14937            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14938                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14939                return false;
14940            }
14941        }
14942
14943        if (ensureVerifyAppsEnabled) {
14944            return true;
14945        }
14946
14947        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14948                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14949    }
14950
14951    @Override
14952    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14953            throws RemoteException {
14954        mContext.enforceCallingOrSelfPermission(
14955                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14956                "Only intentfilter verification agents can verify applications");
14957
14958        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14959        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14960                Binder.getCallingUid(), verificationCode, failedDomains);
14961        msg.arg1 = id;
14962        msg.obj = response;
14963        mHandler.sendMessage(msg);
14964    }
14965
14966    @Override
14967    public int getIntentVerificationStatus(String packageName, int userId) {
14968        final int callingUid = Binder.getCallingUid();
14969        if (getInstantAppPackageName(callingUid) != null) {
14970            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14971        }
14972        synchronized (mPackages) {
14973            final PackageSetting ps = mSettings.mPackages.get(packageName);
14974            if (ps == null
14975                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14976                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14977            }
14978            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14979        }
14980    }
14981
14982    @Override
14983    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14984        mContext.enforceCallingOrSelfPermission(
14985                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14986
14987        boolean result = false;
14988        synchronized (mPackages) {
14989            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14990        }
14991        if (result) {
14992            scheduleWritePackageRestrictionsLocked(userId);
14993        }
14994        return result;
14995    }
14996
14997    @Override
14998    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14999            String packageName) {
15000        final int callingUid = Binder.getCallingUid();
15001        if (getInstantAppPackageName(callingUid) != null) {
15002            return ParceledListSlice.emptyList();
15003        }
15004        synchronized (mPackages) {
15005            final PackageSetting ps = mSettings.mPackages.get(packageName);
15006            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
15007                return ParceledListSlice.emptyList();
15008            }
15009            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
15010        }
15011    }
15012
15013    @Override
15014    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
15015        if (TextUtils.isEmpty(packageName)) {
15016            return ParceledListSlice.emptyList();
15017        }
15018        final int callingUid = Binder.getCallingUid();
15019        final int callingUserId = UserHandle.getUserId(callingUid);
15020        synchronized (mPackages) {
15021            PackageParser.Package pkg = mPackages.get(packageName);
15022            if (pkg == null || pkg.activities == null) {
15023                return ParceledListSlice.emptyList();
15024            }
15025            if (pkg.mExtras == null) {
15026                return ParceledListSlice.emptyList();
15027            }
15028            final PackageSetting ps = (PackageSetting) pkg.mExtras;
15029            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
15030                return ParceledListSlice.emptyList();
15031            }
15032            final int count = pkg.activities.size();
15033            ArrayList<IntentFilter> result = new ArrayList<>();
15034            for (int n=0; n<count; n++) {
15035                PackageParser.Activity activity = pkg.activities.get(n);
15036                if (activity.intents != null && activity.intents.size() > 0) {
15037                    result.addAll(activity.intents);
15038                }
15039            }
15040            return new ParceledListSlice<>(result);
15041        }
15042    }
15043
15044    @Override
15045    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
15046        mContext.enforceCallingOrSelfPermission(
15047                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
15048
15049        synchronized (mPackages) {
15050            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
15051            if (packageName != null) {
15052                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr(
15053                        packageName, userId);
15054            }
15055            return result;
15056        }
15057    }
15058
15059    @Override
15060    public String getDefaultBrowserPackageName(int userId) {
15061        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15062            return null;
15063        }
15064        synchronized (mPackages) {
15065            return mSettings.getDefaultBrowserPackageNameLPw(userId);
15066        }
15067    }
15068
15069    /**
15070     * Get the "allow unknown sources" setting.
15071     *
15072     * @return the current "allow unknown sources" setting
15073     */
15074    private int getUnknownSourcesSettings() {
15075        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
15076                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
15077                -1);
15078    }
15079
15080    @Override
15081    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
15082        final int callingUid = Binder.getCallingUid();
15083        if (getInstantAppPackageName(callingUid) != null) {
15084            return;
15085        }
15086        // writer
15087        synchronized (mPackages) {
15088            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
15089            if (targetPackageSetting == null) {
15090                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
15091            }
15092
15093            PackageSetting installerPackageSetting;
15094            if (installerPackageName != null) {
15095                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
15096                if (installerPackageSetting == null) {
15097                    throw new IllegalArgumentException("Unknown installer package: "
15098                            + installerPackageName);
15099                }
15100            } else {
15101                installerPackageSetting = null;
15102            }
15103
15104            Signature[] callerSignature;
15105            Object obj = mSettings.getUserIdLPr(callingUid);
15106            if (obj != null) {
15107                if (obj instanceof SharedUserSetting) {
15108                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
15109                } else if (obj instanceof PackageSetting) {
15110                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
15111                } else {
15112                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
15113                }
15114            } else {
15115                throw new SecurityException("Unknown calling UID: " + callingUid);
15116            }
15117
15118            // Verify: can't set installerPackageName to a package that is
15119            // not signed with the same cert as the caller.
15120            if (installerPackageSetting != null) {
15121                if (compareSignatures(callerSignature,
15122                        installerPackageSetting.signatures.mSignatures)
15123                        != PackageManager.SIGNATURE_MATCH) {
15124                    throw new SecurityException(
15125                            "Caller does not have same cert as new installer package "
15126                            + installerPackageName);
15127                }
15128            }
15129
15130            // Verify: if target already has an installer package, it must
15131            // be signed with the same cert as the caller.
15132            if (targetPackageSetting.installerPackageName != null) {
15133                PackageSetting setting = mSettings.mPackages.get(
15134                        targetPackageSetting.installerPackageName);
15135                // If the currently set package isn't valid, then it's always
15136                // okay to change it.
15137                if (setting != null) {
15138                    if (compareSignatures(callerSignature,
15139                            setting.signatures.mSignatures)
15140                            != PackageManager.SIGNATURE_MATCH) {
15141                        throw new SecurityException(
15142                                "Caller does not have same cert as old installer package "
15143                                + targetPackageSetting.installerPackageName);
15144                    }
15145                }
15146            }
15147
15148            // Okay!
15149            targetPackageSetting.installerPackageName = installerPackageName;
15150            if (installerPackageName != null) {
15151                mSettings.mInstallerPackages.add(installerPackageName);
15152            }
15153            scheduleWriteSettingsLocked();
15154        }
15155    }
15156
15157    @Override
15158    public void setApplicationCategoryHint(String packageName, int categoryHint,
15159            String callerPackageName) {
15160        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
15161            throw new SecurityException("Instant applications don't have access to this method");
15162        }
15163        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
15164                callerPackageName);
15165        synchronized (mPackages) {
15166            PackageSetting ps = mSettings.mPackages.get(packageName);
15167            if (ps == null) {
15168                throw new IllegalArgumentException("Unknown target package " + packageName);
15169            }
15170
15171            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
15172                throw new IllegalArgumentException("Calling package " + callerPackageName
15173                        + " is not installer for " + packageName);
15174            }
15175
15176            if (ps.categoryHint != categoryHint) {
15177                ps.categoryHint = categoryHint;
15178                scheduleWriteSettingsLocked();
15179            }
15180        }
15181    }
15182
15183    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
15184        // Queue up an async operation since the package installation may take a little while.
15185        mHandler.post(new Runnable() {
15186            public void run() {
15187                mHandler.removeCallbacks(this);
15188                 // Result object to be returned
15189                PackageInstalledInfo res = new PackageInstalledInfo();
15190                res.setReturnCode(currentStatus);
15191                res.uid = -1;
15192                res.pkg = null;
15193                res.removedInfo = null;
15194                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
15195                    args.doPreInstall(res.returnCode);
15196                    synchronized (mInstallLock) {
15197                        installPackageTracedLI(args, res);
15198                    }
15199                    args.doPostInstall(res.returnCode, res.uid);
15200                }
15201
15202                // A restore should be performed at this point if (a) the install
15203                // succeeded, (b) the operation is not an update, and (c) the new
15204                // package has not opted out of backup participation.
15205                final boolean update = res.removedInfo != null
15206                        && res.removedInfo.removedPackage != null;
15207                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
15208                boolean doRestore = !update
15209                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
15210
15211                // Set up the post-install work request bookkeeping.  This will be used
15212                // and cleaned up by the post-install event handling regardless of whether
15213                // there's a restore pass performed.  Token values are >= 1.
15214                int token;
15215                if (mNextInstallToken < 0) mNextInstallToken = 1;
15216                token = mNextInstallToken++;
15217
15218                PostInstallData data = new PostInstallData(args, res);
15219                mRunningInstalls.put(token, data);
15220                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
15221
15222                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
15223                    // Pass responsibility to the Backup Manager.  It will perform a
15224                    // restore if appropriate, then pass responsibility back to the
15225                    // Package Manager to run the post-install observer callbacks
15226                    // and broadcasts.
15227                    IBackupManager bm = IBackupManager.Stub.asInterface(
15228                            ServiceManager.getService(Context.BACKUP_SERVICE));
15229                    if (bm != null) {
15230                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
15231                                + " to BM for possible restore");
15232                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
15233                        try {
15234                            // TODO: http://b/22388012
15235                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
15236                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
15237                            } else {
15238                                doRestore = false;
15239                            }
15240                        } catch (RemoteException e) {
15241                            // can't happen; the backup manager is local
15242                        } catch (Exception e) {
15243                            Slog.e(TAG, "Exception trying to enqueue restore", e);
15244                            doRestore = false;
15245                        }
15246                    } else {
15247                        Slog.e(TAG, "Backup Manager not found!");
15248                        doRestore = false;
15249                    }
15250                }
15251
15252                if (!doRestore) {
15253                    // No restore possible, or the Backup Manager was mysteriously not
15254                    // available -- just fire the post-install work request directly.
15255                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
15256
15257                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
15258
15259                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
15260                    mHandler.sendMessage(msg);
15261                }
15262            }
15263        });
15264    }
15265
15266    /**
15267     * Callback from PackageSettings whenever an app is first transitioned out of the
15268     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
15269     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
15270     * here whether the app is the target of an ongoing install, and only send the
15271     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
15272     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
15273     * handling.
15274     */
15275    void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) {
15276        // Serialize this with the rest of the install-process message chain.  In the
15277        // restore-at-install case, this Runnable will necessarily run before the
15278        // POST_INSTALL message is processed, so the contents of mRunningInstalls
15279        // are coherent.  In the non-restore case, the app has already completed install
15280        // and been launched through some other means, so it is not in a problematic
15281        // state for observers to see the FIRST_LAUNCH signal.
15282        mHandler.post(new Runnable() {
15283            @Override
15284            public void run() {
15285                for (int i = 0; i < mRunningInstalls.size(); i++) {
15286                    final PostInstallData data = mRunningInstalls.valueAt(i);
15287                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
15288                        continue;
15289                    }
15290                    if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) {
15291                        // right package; but is it for the right user?
15292                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
15293                            if (userId == data.res.newUsers[uIndex]) {
15294                                if (DEBUG_BACKUP) {
15295                                    Slog.i(TAG, "Package " + pkgName
15296                                            + " being restored so deferring FIRST_LAUNCH");
15297                                }
15298                                return;
15299                            }
15300                        }
15301                    }
15302                }
15303                // didn't find it, so not being restored
15304                if (DEBUG_BACKUP) {
15305                    Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH");
15306                }
15307                sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId});
15308            }
15309        });
15310    }
15311
15312    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) {
15313        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
15314                installerPkg, null, userIds);
15315    }
15316
15317    private abstract class HandlerParams {
15318        private static final int MAX_RETRIES = 4;
15319
15320        /**
15321         * Number of times startCopy() has been attempted and had a non-fatal
15322         * error.
15323         */
15324        private int mRetries = 0;
15325
15326        /** User handle for the user requesting the information or installation. */
15327        private final UserHandle mUser;
15328        String traceMethod;
15329        int traceCookie;
15330
15331        HandlerParams(UserHandle user) {
15332            mUser = user;
15333        }
15334
15335        UserHandle getUser() {
15336            return mUser;
15337        }
15338
15339        HandlerParams setTraceMethod(String traceMethod) {
15340            this.traceMethod = traceMethod;
15341            return this;
15342        }
15343
15344        HandlerParams setTraceCookie(int traceCookie) {
15345            this.traceCookie = traceCookie;
15346            return this;
15347        }
15348
15349        final boolean startCopy() {
15350            boolean res;
15351            try {
15352                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
15353
15354                if (++mRetries > MAX_RETRIES) {
15355                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
15356                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
15357                    handleServiceError();
15358                    return false;
15359                } else {
15360                    handleStartCopy();
15361                    res = true;
15362                }
15363            } catch (RemoteException e) {
15364                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
15365                mHandler.sendEmptyMessage(MCS_RECONNECT);
15366                res = false;
15367            }
15368            handleReturnCode();
15369            return res;
15370        }
15371
15372        final void serviceError() {
15373            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
15374            handleServiceError();
15375            handleReturnCode();
15376        }
15377
15378        abstract void handleStartCopy() throws RemoteException;
15379        abstract void handleServiceError();
15380        abstract void handleReturnCode();
15381    }
15382
15383    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
15384        for (File path : paths) {
15385            try {
15386                mcs.clearDirectory(path.getAbsolutePath());
15387            } catch (RemoteException e) {
15388            }
15389        }
15390    }
15391
15392    static class OriginInfo {
15393        /**
15394         * Location where install is coming from, before it has been
15395         * copied/renamed into place. This could be a single monolithic APK
15396         * file, or a cluster directory. This location may be untrusted.
15397         */
15398        final File file;
15399        final String cid;
15400
15401        /**
15402         * Flag indicating that {@link #file} or {@link #cid} has already been
15403         * staged, meaning downstream users don't need to defensively copy the
15404         * contents.
15405         */
15406        final boolean staged;
15407
15408        /**
15409         * Flag indicating that {@link #file} or {@link #cid} is an already
15410         * installed app that is being moved.
15411         */
15412        final boolean existing;
15413
15414        final String resolvedPath;
15415        final File resolvedFile;
15416
15417        static OriginInfo fromNothing() {
15418            return new OriginInfo(null, null, false, false);
15419        }
15420
15421        static OriginInfo fromUntrustedFile(File file) {
15422            return new OriginInfo(file, null, false, false);
15423        }
15424
15425        static OriginInfo fromExistingFile(File file) {
15426            return new OriginInfo(file, null, false, true);
15427        }
15428
15429        static OriginInfo fromStagedFile(File file) {
15430            return new OriginInfo(file, null, true, false);
15431        }
15432
15433        static OriginInfo fromStagedContainer(String cid) {
15434            return new OriginInfo(null, cid, true, false);
15435        }
15436
15437        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
15438            this.file = file;
15439            this.cid = cid;
15440            this.staged = staged;
15441            this.existing = existing;
15442
15443            if (cid != null) {
15444                resolvedPath = PackageHelper.getSdDir(cid);
15445                resolvedFile = new File(resolvedPath);
15446            } else if (file != null) {
15447                resolvedPath = file.getAbsolutePath();
15448                resolvedFile = file;
15449            } else {
15450                resolvedPath = null;
15451                resolvedFile = null;
15452            }
15453        }
15454    }
15455
15456    static class MoveInfo {
15457        final int moveId;
15458        final String fromUuid;
15459        final String toUuid;
15460        final String packageName;
15461        final String dataAppName;
15462        final int appId;
15463        final String seinfo;
15464        final int targetSdkVersion;
15465
15466        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
15467                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
15468            this.moveId = moveId;
15469            this.fromUuid = fromUuid;
15470            this.toUuid = toUuid;
15471            this.packageName = packageName;
15472            this.dataAppName = dataAppName;
15473            this.appId = appId;
15474            this.seinfo = seinfo;
15475            this.targetSdkVersion = targetSdkVersion;
15476        }
15477    }
15478
15479    static class VerificationInfo {
15480        /** A constant used to indicate that a uid value is not present. */
15481        public static final int NO_UID = -1;
15482
15483        /** URI referencing where the package was downloaded from. */
15484        final Uri originatingUri;
15485
15486        /** HTTP referrer URI associated with the originatingURI. */
15487        final Uri referrer;
15488
15489        /** UID of the application that the install request originated from. */
15490        final int originatingUid;
15491
15492        /** UID of application requesting the install */
15493        final int installerUid;
15494
15495        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
15496            this.originatingUri = originatingUri;
15497            this.referrer = referrer;
15498            this.originatingUid = originatingUid;
15499            this.installerUid = installerUid;
15500        }
15501    }
15502
15503    class InstallParams extends HandlerParams {
15504        final OriginInfo origin;
15505        final MoveInfo move;
15506        final IPackageInstallObserver2 observer;
15507        int installFlags;
15508        final String installerPackageName;
15509        final String volumeUuid;
15510        private InstallArgs mArgs;
15511        private int mRet;
15512        final String packageAbiOverride;
15513        final String[] grantedRuntimePermissions;
15514        final VerificationInfo verificationInfo;
15515        final Certificate[][] certificates;
15516        final int installReason;
15517
15518        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15519                int installFlags, String installerPackageName, String volumeUuid,
15520                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15521                String[] grantedPermissions, Certificate[][] certificates, int installReason) {
15522            super(user);
15523            this.origin = origin;
15524            this.move = move;
15525            this.observer = observer;
15526            this.installFlags = installFlags;
15527            this.installerPackageName = installerPackageName;
15528            this.volumeUuid = volumeUuid;
15529            this.verificationInfo = verificationInfo;
15530            this.packageAbiOverride = packageAbiOverride;
15531            this.grantedRuntimePermissions = grantedPermissions;
15532            this.certificates = certificates;
15533            this.installReason = installReason;
15534        }
15535
15536        @Override
15537        public String toString() {
15538            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15539                    + " file=" + origin.file + " cid=" + origin.cid + "}";
15540        }
15541
15542        private int installLocationPolicy(PackageInfoLite pkgLite) {
15543            String packageName = pkgLite.packageName;
15544            int installLocation = pkgLite.installLocation;
15545            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15546            // reader
15547            synchronized (mPackages) {
15548                // Currently installed package which the new package is attempting to replace or
15549                // null if no such package is installed.
15550                PackageParser.Package installedPkg = mPackages.get(packageName);
15551                // Package which currently owns the data which the new package will own if installed.
15552                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15553                // will be null whereas dataOwnerPkg will contain information about the package
15554                // which was uninstalled while keeping its data.
15555                PackageParser.Package dataOwnerPkg = installedPkg;
15556                if (dataOwnerPkg  == null) {
15557                    PackageSetting ps = mSettings.mPackages.get(packageName);
15558                    if (ps != null) {
15559                        dataOwnerPkg = ps.pkg;
15560                    }
15561                }
15562
15563                if (dataOwnerPkg != null) {
15564                    // If installed, the package will get access to data left on the device by its
15565                    // predecessor. As a security measure, this is permited only if this is not a
15566                    // version downgrade or if the predecessor package is marked as debuggable and
15567                    // a downgrade is explicitly requested.
15568                    //
15569                    // On debuggable platform builds, downgrades are permitted even for
15570                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15571                    // not offer security guarantees and thus it's OK to disable some security
15572                    // mechanisms to make debugging/testing easier on those builds. However, even on
15573                    // debuggable builds downgrades of packages are permitted only if requested via
15574                    // installFlags. This is because we aim to keep the behavior of debuggable
15575                    // platform builds as close as possible to the behavior of non-debuggable
15576                    // platform builds.
15577                    final boolean downgradeRequested =
15578                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15579                    final boolean packageDebuggable =
15580                                (dataOwnerPkg.applicationInfo.flags
15581                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15582                    final boolean downgradePermitted =
15583                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15584                    if (!downgradePermitted) {
15585                        try {
15586                            checkDowngrade(dataOwnerPkg, pkgLite);
15587                        } catch (PackageManagerException e) {
15588                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15589                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15590                        }
15591                    }
15592                }
15593
15594                if (installedPkg != null) {
15595                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15596                        // Check for updated system application.
15597                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15598                            if (onSd) {
15599                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15600                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15601                            }
15602                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15603                        } else {
15604                            if (onSd) {
15605                                // Install flag overrides everything.
15606                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15607                            }
15608                            // If current upgrade specifies particular preference
15609                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15610                                // Application explicitly specified internal.
15611                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15612                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15613                                // App explictly prefers external. Let policy decide
15614                            } else {
15615                                // Prefer previous location
15616                                if (isExternal(installedPkg)) {
15617                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15618                                }
15619                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15620                            }
15621                        }
15622                    } else {
15623                        // Invalid install. Return error code
15624                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15625                    }
15626                }
15627            }
15628            // All the special cases have been taken care of.
15629            // Return result based on recommended install location.
15630            if (onSd) {
15631                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15632            }
15633            return pkgLite.recommendedInstallLocation;
15634        }
15635
15636        /*
15637         * Invoke remote method to get package information and install
15638         * location values. Override install location based on default
15639         * policy if needed and then create install arguments based
15640         * on the install location.
15641         */
15642        public void handleStartCopy() throws RemoteException {
15643            int ret = PackageManager.INSTALL_SUCCEEDED;
15644
15645            // If we're already staged, we've firmly committed to an install location
15646            if (origin.staged) {
15647                if (origin.file != null) {
15648                    installFlags |= PackageManager.INSTALL_INTERNAL;
15649                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15650                } else if (origin.cid != null) {
15651                    installFlags |= PackageManager.INSTALL_EXTERNAL;
15652                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
15653                } else {
15654                    throw new IllegalStateException("Invalid stage location");
15655                }
15656            }
15657
15658            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15659            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15660            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15661            PackageInfoLite pkgLite = null;
15662
15663            if (onInt && onSd) {
15664                // Check if both bits are set.
15665                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15666                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15667            } else if (onSd && ephemeral) {
15668                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15669                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15670            } else {
15671                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15672                        packageAbiOverride);
15673
15674                if (DEBUG_EPHEMERAL && ephemeral) {
15675                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15676                }
15677
15678                /*
15679                 * If we have too little free space, try to free cache
15680                 * before giving up.
15681                 */
15682                if (!origin.staged && pkgLite.recommendedInstallLocation
15683                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15684                    // TODO: focus freeing disk space on the target device
15685                    final StorageManager storage = StorageManager.from(mContext);
15686                    final long lowThreshold = storage.getStorageLowBytes(
15687                            Environment.getDataDirectory());
15688
15689                    final long sizeBytes = mContainerService.calculateInstalledSize(
15690                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
15691
15692                    try {
15693                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15694                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15695                                installFlags, packageAbiOverride);
15696                    } catch (InstallerException e) {
15697                        Slog.w(TAG, "Failed to free cache", e);
15698                    }
15699
15700                    /*
15701                     * The cache free must have deleted the file we
15702                     * downloaded to install.
15703                     *
15704                     * TODO: fix the "freeCache" call to not delete
15705                     *       the file we care about.
15706                     */
15707                    if (pkgLite.recommendedInstallLocation
15708                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15709                        pkgLite.recommendedInstallLocation
15710                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15711                    }
15712                }
15713            }
15714
15715            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15716                int loc = pkgLite.recommendedInstallLocation;
15717                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15718                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15719                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15720                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15721                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15722                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15723                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15724                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15725                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15726                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15727                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15728                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15729                } else {
15730                    // Override with defaults if needed.
15731                    loc = installLocationPolicy(pkgLite);
15732                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15733                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15734                    } else if (!onSd && !onInt) {
15735                        // Override install location with flags
15736                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15737                            // Set the flag to install on external media.
15738                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15739                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15740                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15741                            if (DEBUG_EPHEMERAL) {
15742                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15743                            }
15744                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15745                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15746                                    |PackageManager.INSTALL_INTERNAL);
15747                        } else {
15748                            // Make sure the flag for installing on external
15749                            // media is unset
15750                            installFlags |= PackageManager.INSTALL_INTERNAL;
15751                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15752                        }
15753                    }
15754                }
15755            }
15756
15757            final InstallArgs args = createInstallArgs(this);
15758            mArgs = args;
15759
15760            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15761                // TODO: http://b/22976637
15762                // Apps installed for "all" users use the device owner to verify the app
15763                UserHandle verifierUser = getUser();
15764                if (verifierUser == UserHandle.ALL) {
15765                    verifierUser = UserHandle.SYSTEM;
15766                }
15767
15768                /*
15769                 * Determine if we have any installed package verifiers. If we
15770                 * do, then we'll defer to them to verify the packages.
15771                 */
15772                final int requiredUid = mRequiredVerifierPackage == null ? -1
15773                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15774                                verifierUser.getIdentifier());
15775                if (!origin.existing && requiredUid != -1
15776                        && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) {
15777                    final Intent verification = new Intent(
15778                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15779                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15780                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15781                            PACKAGE_MIME_TYPE);
15782                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15783
15784                    // Query all live verifiers based on current user state
15785                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15786                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier());
15787
15788                    if (DEBUG_VERIFY) {
15789                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15790                                + verification.toString() + " with " + pkgLite.verifiers.length
15791                                + " optional verifiers");
15792                    }
15793
15794                    final int verificationId = mPendingVerificationToken++;
15795
15796                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15797
15798                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15799                            installerPackageName);
15800
15801                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15802                            installFlags);
15803
15804                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15805                            pkgLite.packageName);
15806
15807                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15808                            pkgLite.versionCode);
15809
15810                    if (verificationInfo != null) {
15811                        if (verificationInfo.originatingUri != null) {
15812                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15813                                    verificationInfo.originatingUri);
15814                        }
15815                        if (verificationInfo.referrer != null) {
15816                            verification.putExtra(Intent.EXTRA_REFERRER,
15817                                    verificationInfo.referrer);
15818                        }
15819                        if (verificationInfo.originatingUid >= 0) {
15820                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15821                                    verificationInfo.originatingUid);
15822                        }
15823                        if (verificationInfo.installerUid >= 0) {
15824                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15825                                    verificationInfo.installerUid);
15826                        }
15827                    }
15828
15829                    final PackageVerificationState verificationState = new PackageVerificationState(
15830                            requiredUid, args);
15831
15832                    mPendingVerification.append(verificationId, verificationState);
15833
15834                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15835                            receivers, verificationState);
15836
15837                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15838                    final long idleDuration = getVerificationTimeout();
15839
15840                    /*
15841                     * If any sufficient verifiers were listed in the package
15842                     * manifest, attempt to ask them.
15843                     */
15844                    if (sufficientVerifiers != null) {
15845                        final int N = sufficientVerifiers.size();
15846                        if (N == 0) {
15847                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15848                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15849                        } else {
15850                            for (int i = 0; i < N; i++) {
15851                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15852                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15853                                        verifierComponent.getPackageName(), idleDuration,
15854                                        verifierUser.getIdentifier(), false, "package verifier");
15855
15856                                final Intent sufficientIntent = new Intent(verification);
15857                                sufficientIntent.setComponent(verifierComponent);
15858                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15859                            }
15860                        }
15861                    }
15862
15863                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15864                            mRequiredVerifierPackage, receivers);
15865                    if (ret == PackageManager.INSTALL_SUCCEEDED
15866                            && mRequiredVerifierPackage != null) {
15867                        Trace.asyncTraceBegin(
15868                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15869                        /*
15870                         * Send the intent to the required verification agent,
15871                         * but only start the verification timeout after the
15872                         * target BroadcastReceivers have run.
15873                         */
15874                        verification.setComponent(requiredVerifierComponent);
15875                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15876                                mRequiredVerifierPackage, idleDuration,
15877                                verifierUser.getIdentifier(), false, "package verifier");
15878                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15879                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15880                                new BroadcastReceiver() {
15881                                    @Override
15882                                    public void onReceive(Context context, Intent intent) {
15883                                        final Message msg = mHandler
15884                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15885                                        msg.arg1 = verificationId;
15886                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15887                                    }
15888                                }, null, 0, null, null);
15889
15890                        /*
15891                         * We don't want the copy to proceed until verification
15892                         * succeeds, so null out this field.
15893                         */
15894                        mArgs = null;
15895                    }
15896                } else {
15897                    /*
15898                     * No package verification is enabled, so immediately start
15899                     * the remote call to initiate copy using temporary file.
15900                     */
15901                    ret = args.copyApk(mContainerService, true);
15902                }
15903            }
15904
15905            mRet = ret;
15906        }
15907
15908        @Override
15909        void handleReturnCode() {
15910            // If mArgs is null, then MCS couldn't be reached. When it
15911            // reconnects, it will try again to install. At that point, this
15912            // will succeed.
15913            if (mArgs != null) {
15914                processPendingInstall(mArgs, mRet);
15915            }
15916        }
15917
15918        @Override
15919        void handleServiceError() {
15920            mArgs = createInstallArgs(this);
15921            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15922        }
15923
15924        public boolean isForwardLocked() {
15925            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15926        }
15927    }
15928
15929    /**
15930     * Used during creation of InstallArgs
15931     *
15932     * @param installFlags package installation flags
15933     * @return true if should be installed on external storage
15934     */
15935    private static boolean installOnExternalAsec(int installFlags) {
15936        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
15937            return false;
15938        }
15939        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
15940            return true;
15941        }
15942        return false;
15943    }
15944
15945    /**
15946     * Used during creation of InstallArgs
15947     *
15948     * @param installFlags package installation flags
15949     * @return true if should be installed as forward locked
15950     */
15951    private static boolean installForwardLocked(int installFlags) {
15952        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15953    }
15954
15955    private InstallArgs createInstallArgs(InstallParams params) {
15956        if (params.move != null) {
15957            return new MoveInstallArgs(params);
15958        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
15959            return new AsecInstallArgs(params);
15960        } else {
15961            return new FileInstallArgs(params);
15962        }
15963    }
15964
15965    /**
15966     * Create args that describe an existing installed package. Typically used
15967     * when cleaning up old installs, or used as a move source.
15968     */
15969    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15970            String resourcePath, String[] instructionSets) {
15971        final boolean isInAsec;
15972        if (installOnExternalAsec(installFlags)) {
15973            /* Apps on SD card are always in ASEC containers. */
15974            isInAsec = true;
15975        } else if (installForwardLocked(installFlags)
15976                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
15977            /*
15978             * Forward-locked apps are only in ASEC containers if they're the
15979             * new style
15980             */
15981            isInAsec = true;
15982        } else {
15983            isInAsec = false;
15984        }
15985
15986        if (isInAsec) {
15987            return new AsecInstallArgs(codePath, instructionSets,
15988                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
15989        } else {
15990            return new FileInstallArgs(codePath, resourcePath, instructionSets);
15991        }
15992    }
15993
15994    static abstract class InstallArgs {
15995        /** @see InstallParams#origin */
15996        final OriginInfo origin;
15997        /** @see InstallParams#move */
15998        final MoveInfo move;
15999
16000        final IPackageInstallObserver2 observer;
16001        // Always refers to PackageManager flags only
16002        final int installFlags;
16003        final String installerPackageName;
16004        final String volumeUuid;
16005        final UserHandle user;
16006        final String abiOverride;
16007        final String[] installGrantPermissions;
16008        /** If non-null, drop an async trace when the install completes */
16009        final String traceMethod;
16010        final int traceCookie;
16011        final Certificate[][] certificates;
16012        final int installReason;
16013
16014        // The list of instruction sets supported by this app. This is currently
16015        // only used during the rmdex() phase to clean up resources. We can get rid of this
16016        // if we move dex files under the common app path.
16017        /* nullable */ String[] instructionSets;
16018
16019        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
16020                int installFlags, String installerPackageName, String volumeUuid,
16021                UserHandle user, String[] instructionSets,
16022                String abiOverride, String[] installGrantPermissions,
16023                String traceMethod, int traceCookie, Certificate[][] certificates,
16024                int installReason) {
16025            this.origin = origin;
16026            this.move = move;
16027            this.installFlags = installFlags;
16028            this.observer = observer;
16029            this.installerPackageName = installerPackageName;
16030            this.volumeUuid = volumeUuid;
16031            this.user = user;
16032            this.instructionSets = instructionSets;
16033            this.abiOverride = abiOverride;
16034            this.installGrantPermissions = installGrantPermissions;
16035            this.traceMethod = traceMethod;
16036            this.traceCookie = traceCookie;
16037            this.certificates = certificates;
16038            this.installReason = installReason;
16039        }
16040
16041        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
16042        abstract int doPreInstall(int status);
16043
16044        /**
16045         * Rename package into final resting place. All paths on the given
16046         * scanned package should be updated to reflect the rename.
16047         */
16048        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
16049        abstract int doPostInstall(int status, int uid);
16050
16051        /** @see PackageSettingBase#codePathString */
16052        abstract String getCodePath();
16053        /** @see PackageSettingBase#resourcePathString */
16054        abstract String getResourcePath();
16055
16056        // Need installer lock especially for dex file removal.
16057        abstract void cleanUpResourcesLI();
16058        abstract boolean doPostDeleteLI(boolean delete);
16059
16060        /**
16061         * Called before the source arguments are copied. This is used mostly
16062         * for MoveParams when it needs to read the source file to put it in the
16063         * destination.
16064         */
16065        int doPreCopy() {
16066            return PackageManager.INSTALL_SUCCEEDED;
16067        }
16068
16069        /**
16070         * Called after the source arguments are copied. This is used mostly for
16071         * MoveParams when it needs to read the source file to put it in the
16072         * destination.
16073         */
16074        int doPostCopy(int uid) {
16075            return PackageManager.INSTALL_SUCCEEDED;
16076        }
16077
16078        protected boolean isFwdLocked() {
16079            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
16080        }
16081
16082        protected boolean isExternalAsec() {
16083            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
16084        }
16085
16086        protected boolean isEphemeral() {
16087            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16088        }
16089
16090        UserHandle getUser() {
16091            return user;
16092        }
16093    }
16094
16095    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
16096        if (!allCodePaths.isEmpty()) {
16097            if (instructionSets == null) {
16098                throw new IllegalStateException("instructionSet == null");
16099            }
16100            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
16101            for (String codePath : allCodePaths) {
16102                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
16103                    try {
16104                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
16105                    } catch (InstallerException ignored) {
16106                    }
16107                }
16108            }
16109        }
16110    }
16111
16112    /**
16113     * Logic to handle installation of non-ASEC applications, including copying
16114     * and renaming logic.
16115     */
16116    class FileInstallArgs extends InstallArgs {
16117        private File codeFile;
16118        private File resourceFile;
16119
16120        // Example topology:
16121        // /data/app/com.example/base.apk
16122        // /data/app/com.example/split_foo.apk
16123        // /data/app/com.example/lib/arm/libfoo.so
16124        // /data/app/com.example/lib/arm64/libfoo.so
16125        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
16126
16127        /** New install */
16128        FileInstallArgs(InstallParams params) {
16129            super(params.origin, params.move, params.observer, params.installFlags,
16130                    params.installerPackageName, params.volumeUuid,
16131                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
16132                    params.grantedRuntimePermissions,
16133                    params.traceMethod, params.traceCookie, params.certificates,
16134                    params.installReason);
16135            if (isFwdLocked()) {
16136                throw new IllegalArgumentException("Forward locking only supported in ASEC");
16137            }
16138        }
16139
16140        /** Existing install */
16141        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
16142            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
16143                    null, null, null, 0, null /*certificates*/,
16144                    PackageManager.INSTALL_REASON_UNKNOWN);
16145            this.codeFile = (codePath != null) ? new File(codePath) : null;
16146            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
16147        }
16148
16149        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16150            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
16151            try {
16152                return doCopyApk(imcs, temp);
16153            } finally {
16154                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16155            }
16156        }
16157
16158        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16159            if (origin.staged) {
16160                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
16161                codeFile = origin.file;
16162                resourceFile = origin.file;
16163                return PackageManager.INSTALL_SUCCEEDED;
16164            }
16165
16166            try {
16167                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
16168                final File tempDir =
16169                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
16170                codeFile = tempDir;
16171                resourceFile = tempDir;
16172            } catch (IOException e) {
16173                Slog.w(TAG, "Failed to create copy file: " + e);
16174                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
16175            }
16176
16177            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
16178                @Override
16179                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
16180                    if (!FileUtils.isValidExtFilename(name)) {
16181                        throw new IllegalArgumentException("Invalid filename: " + name);
16182                    }
16183                    try {
16184                        final File file = new File(codeFile, name);
16185                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
16186                                O_RDWR | O_CREAT, 0644);
16187                        Os.chmod(file.getAbsolutePath(), 0644);
16188                        return new ParcelFileDescriptor(fd);
16189                    } catch (ErrnoException e) {
16190                        throw new RemoteException("Failed to open: " + e.getMessage());
16191                    }
16192                }
16193            };
16194
16195            int ret = PackageManager.INSTALL_SUCCEEDED;
16196            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
16197            if (ret != PackageManager.INSTALL_SUCCEEDED) {
16198                Slog.e(TAG, "Failed to copy package");
16199                return ret;
16200            }
16201
16202            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
16203            NativeLibraryHelper.Handle handle = null;
16204            try {
16205                handle = NativeLibraryHelper.Handle.create(codeFile);
16206                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
16207                        abiOverride);
16208            } catch (IOException e) {
16209                Slog.e(TAG, "Copying native libraries failed", e);
16210                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16211            } finally {
16212                IoUtils.closeQuietly(handle);
16213            }
16214
16215            return ret;
16216        }
16217
16218        int doPreInstall(int status) {
16219            if (status != PackageManager.INSTALL_SUCCEEDED) {
16220                cleanUp();
16221            }
16222            return status;
16223        }
16224
16225        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16226            if (status != PackageManager.INSTALL_SUCCEEDED) {
16227                cleanUp();
16228                return false;
16229            }
16230
16231            final File targetDir = codeFile.getParentFile();
16232            final File beforeCodeFile = codeFile;
16233            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
16234
16235            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
16236            try {
16237                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
16238            } catch (ErrnoException e) {
16239                Slog.w(TAG, "Failed to rename", e);
16240                return false;
16241            }
16242
16243            if (!SELinux.restoreconRecursive(afterCodeFile)) {
16244                Slog.w(TAG, "Failed to restorecon");
16245                return false;
16246            }
16247
16248            // Reflect the rename internally
16249            codeFile = afterCodeFile;
16250            resourceFile = afterCodeFile;
16251
16252            // Reflect the rename in scanned details
16253            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16254            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16255                    afterCodeFile, pkg.baseCodePath));
16256            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16257                    afterCodeFile, pkg.splitCodePaths));
16258
16259            // Reflect the rename in app info
16260            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16261            pkg.setApplicationInfoCodePath(pkg.codePath);
16262            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16263            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16264            pkg.setApplicationInfoResourcePath(pkg.codePath);
16265            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16266            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16267
16268            return true;
16269        }
16270
16271        int doPostInstall(int status, int uid) {
16272            if (status != PackageManager.INSTALL_SUCCEEDED) {
16273                cleanUp();
16274            }
16275            return status;
16276        }
16277
16278        @Override
16279        String getCodePath() {
16280            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16281        }
16282
16283        @Override
16284        String getResourcePath() {
16285            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16286        }
16287
16288        private boolean cleanUp() {
16289            if (codeFile == null || !codeFile.exists()) {
16290                return false;
16291            }
16292
16293            removeCodePathLI(codeFile);
16294
16295            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
16296                resourceFile.delete();
16297            }
16298
16299            return true;
16300        }
16301
16302        void cleanUpResourcesLI() {
16303            // Try enumerating all code paths before deleting
16304            List<String> allCodePaths = Collections.EMPTY_LIST;
16305            if (codeFile != null && codeFile.exists()) {
16306                try {
16307                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16308                    allCodePaths = pkg.getAllCodePaths();
16309                } catch (PackageParserException e) {
16310                    // Ignored; we tried our best
16311                }
16312            }
16313
16314            cleanUp();
16315            removeDexFiles(allCodePaths, instructionSets);
16316        }
16317
16318        boolean doPostDeleteLI(boolean delete) {
16319            // XXX err, shouldn't we respect the delete flag?
16320            cleanUpResourcesLI();
16321            return true;
16322        }
16323    }
16324
16325    private boolean isAsecExternal(String cid) {
16326        final String asecPath = PackageHelper.getSdFilesystem(cid);
16327        return !asecPath.startsWith(mAsecInternalPath);
16328    }
16329
16330    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
16331            PackageManagerException {
16332        if (copyRet < 0) {
16333            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
16334                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
16335                throw new PackageManagerException(copyRet, message);
16336            }
16337        }
16338    }
16339
16340    /**
16341     * Extract the StorageManagerService "container ID" from the full code path of an
16342     * .apk.
16343     */
16344    static String cidFromCodePath(String fullCodePath) {
16345        int eidx = fullCodePath.lastIndexOf("/");
16346        String subStr1 = fullCodePath.substring(0, eidx);
16347        int sidx = subStr1.lastIndexOf("/");
16348        return subStr1.substring(sidx+1, eidx);
16349    }
16350
16351    /**
16352     * Logic to handle installation of ASEC applications, including copying and
16353     * renaming logic.
16354     */
16355    class AsecInstallArgs extends InstallArgs {
16356        static final String RES_FILE_NAME = "pkg.apk";
16357        static final String PUBLIC_RES_FILE_NAME = "res.zip";
16358
16359        String cid;
16360        String packagePath;
16361        String resourcePath;
16362
16363        /** New install */
16364        AsecInstallArgs(InstallParams params) {
16365            super(params.origin, params.move, params.observer, params.installFlags,
16366                    params.installerPackageName, params.volumeUuid,
16367                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16368                    params.grantedRuntimePermissions,
16369                    params.traceMethod, params.traceCookie, params.certificates,
16370                    params.installReason);
16371        }
16372
16373        /** Existing install */
16374        AsecInstallArgs(String fullCodePath, String[] instructionSets,
16375                        boolean isExternal, boolean isForwardLocked) {
16376            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
16377                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16378                    instructionSets, null, null, null, 0, null /*certificates*/,
16379                    PackageManager.INSTALL_REASON_UNKNOWN);
16380            // Hackily pretend we're still looking at a full code path
16381            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
16382                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
16383            }
16384
16385            // Extract cid from fullCodePath
16386            int eidx = fullCodePath.lastIndexOf("/");
16387            String subStr1 = fullCodePath.substring(0, eidx);
16388            int sidx = subStr1.lastIndexOf("/");
16389            cid = subStr1.substring(sidx+1, eidx);
16390            setMountPath(subStr1);
16391        }
16392
16393        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
16394            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
16395                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
16396                    instructionSets, null, null, null, 0, null /*certificates*/,
16397                    PackageManager.INSTALL_REASON_UNKNOWN);
16398            this.cid = cid;
16399            setMountPath(PackageHelper.getSdDir(cid));
16400        }
16401
16402        void createCopyFile() {
16403            cid = mInstallerService.allocateExternalStageCidLegacy();
16404        }
16405
16406        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
16407            if (origin.staged && origin.cid != null) {
16408                if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy");
16409                cid = origin.cid;
16410                setMountPath(PackageHelper.getSdDir(cid));
16411                return PackageManager.INSTALL_SUCCEEDED;
16412            }
16413
16414            if (temp) {
16415                createCopyFile();
16416            } else {
16417                /*
16418                 * Pre-emptively destroy the container since it's destroyed if
16419                 * copying fails due to it existing anyway.
16420                 */
16421                PackageHelper.destroySdDir(cid);
16422            }
16423
16424            final String newMountPath = imcs.copyPackageToContainer(
16425                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
16426                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
16427
16428            if (newMountPath != null) {
16429                setMountPath(newMountPath);
16430                return PackageManager.INSTALL_SUCCEEDED;
16431            } else {
16432                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16433            }
16434        }
16435
16436        @Override
16437        String getCodePath() {
16438            return packagePath;
16439        }
16440
16441        @Override
16442        String getResourcePath() {
16443            return resourcePath;
16444        }
16445
16446        int doPreInstall(int status) {
16447            if (status != PackageManager.INSTALL_SUCCEEDED) {
16448                // Destroy container
16449                PackageHelper.destroySdDir(cid);
16450            } else {
16451                boolean mounted = PackageHelper.isContainerMounted(cid);
16452                if (!mounted) {
16453                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
16454                            Process.SYSTEM_UID);
16455                    if (newMountPath != null) {
16456                        setMountPath(newMountPath);
16457                    } else {
16458                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16459                    }
16460                }
16461            }
16462            return status;
16463        }
16464
16465        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16466            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
16467            String newMountPath = null;
16468            if (PackageHelper.isContainerMounted(cid)) {
16469                // Unmount the container
16470                if (!PackageHelper.unMountSdDir(cid)) {
16471                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
16472                    return false;
16473                }
16474            }
16475            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16476                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
16477                        " which might be stale. Will try to clean up.");
16478                // Clean up the stale container and proceed to recreate.
16479                if (!PackageHelper.destroySdDir(newCacheId)) {
16480                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
16481                    return false;
16482                }
16483                // Successfully cleaned up stale container. Try to rename again.
16484                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
16485                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
16486                            + " inspite of cleaning it up.");
16487                    return false;
16488                }
16489            }
16490            if (!PackageHelper.isContainerMounted(newCacheId)) {
16491                Slog.w(TAG, "Mounting container " + newCacheId);
16492                newMountPath = PackageHelper.mountSdDir(newCacheId,
16493                        getEncryptKey(), Process.SYSTEM_UID);
16494            } else {
16495                newMountPath = PackageHelper.getSdDir(newCacheId);
16496            }
16497            if (newMountPath == null) {
16498                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
16499                return false;
16500            }
16501            Log.i(TAG, "Succesfully renamed " + cid +
16502                    " to " + newCacheId +
16503                    " at new path: " + newMountPath);
16504            cid = newCacheId;
16505
16506            final File beforeCodeFile = new File(packagePath);
16507            setMountPath(newMountPath);
16508            final File afterCodeFile = new File(packagePath);
16509
16510            // Reflect the rename in scanned details
16511            pkg.setCodePath(afterCodeFile.getAbsolutePath());
16512            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
16513                    afterCodeFile, pkg.baseCodePath));
16514            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
16515                    afterCodeFile, pkg.splitCodePaths));
16516
16517            // Reflect the rename in app info
16518            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16519            pkg.setApplicationInfoCodePath(pkg.codePath);
16520            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16521            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16522            pkg.setApplicationInfoResourcePath(pkg.codePath);
16523            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16524            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16525
16526            return true;
16527        }
16528
16529        private void setMountPath(String mountPath) {
16530            final File mountFile = new File(mountPath);
16531
16532            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
16533            if (monolithicFile.exists()) {
16534                packagePath = monolithicFile.getAbsolutePath();
16535                if (isFwdLocked()) {
16536                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
16537                } else {
16538                    resourcePath = packagePath;
16539                }
16540            } else {
16541                packagePath = mountFile.getAbsolutePath();
16542                resourcePath = packagePath;
16543            }
16544        }
16545
16546        int doPostInstall(int status, int uid) {
16547            if (status != PackageManager.INSTALL_SUCCEEDED) {
16548                cleanUp();
16549            } else {
16550                final int groupOwner;
16551                final String protectedFile;
16552                if (isFwdLocked()) {
16553                    groupOwner = UserHandle.getSharedAppGid(uid);
16554                    protectedFile = RES_FILE_NAME;
16555                } else {
16556                    groupOwner = -1;
16557                    protectedFile = null;
16558                }
16559
16560                if (uid < Process.FIRST_APPLICATION_UID
16561                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
16562                    Slog.e(TAG, "Failed to finalize " + cid);
16563                    PackageHelper.destroySdDir(cid);
16564                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16565                }
16566
16567                boolean mounted = PackageHelper.isContainerMounted(cid);
16568                if (!mounted) {
16569                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
16570                }
16571            }
16572            return status;
16573        }
16574
16575        private void cleanUp() {
16576            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
16577
16578            // Destroy secure container
16579            PackageHelper.destroySdDir(cid);
16580        }
16581
16582        private List<String> getAllCodePaths() {
16583            final File codeFile = new File(getCodePath());
16584            if (codeFile != null && codeFile.exists()) {
16585                try {
16586                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
16587                    return pkg.getAllCodePaths();
16588                } catch (PackageParserException e) {
16589                    // Ignored; we tried our best
16590                }
16591            }
16592            return Collections.EMPTY_LIST;
16593        }
16594
16595        void cleanUpResourcesLI() {
16596            // Enumerate all code paths before deleting
16597            cleanUpResourcesLI(getAllCodePaths());
16598        }
16599
16600        private void cleanUpResourcesLI(List<String> allCodePaths) {
16601            cleanUp();
16602            removeDexFiles(allCodePaths, instructionSets);
16603        }
16604
16605        String getPackageName() {
16606            return getAsecPackageName(cid);
16607        }
16608
16609        boolean doPostDeleteLI(boolean delete) {
16610            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
16611            final List<String> allCodePaths = getAllCodePaths();
16612            boolean mounted = PackageHelper.isContainerMounted(cid);
16613            if (mounted) {
16614                // Unmount first
16615                if (PackageHelper.unMountSdDir(cid)) {
16616                    mounted = false;
16617                }
16618            }
16619            if (!mounted && delete) {
16620                cleanUpResourcesLI(allCodePaths);
16621            }
16622            return !mounted;
16623        }
16624
16625        @Override
16626        int doPreCopy() {
16627            if (isFwdLocked()) {
16628                if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE,
16629                        MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) {
16630                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16631                }
16632            }
16633
16634            return PackageManager.INSTALL_SUCCEEDED;
16635        }
16636
16637        @Override
16638        int doPostCopy(int uid) {
16639            if (isFwdLocked()) {
16640                if (uid < Process.FIRST_APPLICATION_UID
16641                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
16642                                RES_FILE_NAME)) {
16643                    Slog.e(TAG, "Failed to finalize " + cid);
16644                    PackageHelper.destroySdDir(cid);
16645                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
16646                }
16647            }
16648
16649            return PackageManager.INSTALL_SUCCEEDED;
16650        }
16651    }
16652
16653    /**
16654     * Logic to handle movement of existing installed applications.
16655     */
16656    class MoveInstallArgs extends InstallArgs {
16657        private File codeFile;
16658        private File resourceFile;
16659
16660        /** New install */
16661        MoveInstallArgs(InstallParams params) {
16662            super(params.origin, params.move, params.observer, params.installFlags,
16663                    params.installerPackageName, params.volumeUuid,
16664                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
16665                    params.grantedRuntimePermissions,
16666                    params.traceMethod, params.traceCookie, params.certificates,
16667                    params.installReason);
16668        }
16669
16670        int copyApk(IMediaContainerService imcs, boolean temp) {
16671            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
16672                    + move.fromUuid + " to " + move.toUuid);
16673            synchronized (mInstaller) {
16674                try {
16675                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
16676                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
16677                } catch (InstallerException e) {
16678                    Slog.w(TAG, "Failed to move app", e);
16679                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
16680                }
16681            }
16682
16683            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
16684            resourceFile = codeFile;
16685            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
16686
16687            return PackageManager.INSTALL_SUCCEEDED;
16688        }
16689
16690        int doPreInstall(int status) {
16691            if (status != PackageManager.INSTALL_SUCCEEDED) {
16692                cleanUp(move.toUuid);
16693            }
16694            return status;
16695        }
16696
16697        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
16698            if (status != PackageManager.INSTALL_SUCCEEDED) {
16699                cleanUp(move.toUuid);
16700                return false;
16701            }
16702
16703            // Reflect the move in app info
16704            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
16705            pkg.setApplicationInfoCodePath(pkg.codePath);
16706            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
16707            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
16708            pkg.setApplicationInfoResourcePath(pkg.codePath);
16709            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
16710            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
16711
16712            return true;
16713        }
16714
16715        int doPostInstall(int status, int uid) {
16716            if (status == PackageManager.INSTALL_SUCCEEDED) {
16717                cleanUp(move.fromUuid);
16718            } else {
16719                cleanUp(move.toUuid);
16720            }
16721            return status;
16722        }
16723
16724        @Override
16725        String getCodePath() {
16726            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
16727        }
16728
16729        @Override
16730        String getResourcePath() {
16731            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
16732        }
16733
16734        private boolean cleanUp(String volumeUuid) {
16735            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
16736                    move.dataAppName);
16737            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
16738            final int[] userIds = sUserManager.getUserIds();
16739            synchronized (mInstallLock) {
16740                // Clean up both app data and code
16741                // All package moves are frozen until finished
16742                for (int userId : userIds) {
16743                    try {
16744                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
16745                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
16746                    } catch (InstallerException e) {
16747                        Slog.w(TAG, String.valueOf(e));
16748                    }
16749                }
16750                removeCodePathLI(codeFile);
16751            }
16752            return true;
16753        }
16754
16755        void cleanUpResourcesLI() {
16756            throw new UnsupportedOperationException();
16757        }
16758
16759        boolean doPostDeleteLI(boolean delete) {
16760            throw new UnsupportedOperationException();
16761        }
16762    }
16763
16764    static String getAsecPackageName(String packageCid) {
16765        int idx = packageCid.lastIndexOf("-");
16766        if (idx == -1) {
16767            return packageCid;
16768        }
16769        return packageCid.substring(0, idx);
16770    }
16771
16772    // Utility method used to create code paths based on package name and available index.
16773    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
16774        String idxStr = "";
16775        int idx = 1;
16776        // Fall back to default value of idx=1 if prefix is not
16777        // part of oldCodePath
16778        if (oldCodePath != null) {
16779            String subStr = oldCodePath;
16780            // Drop the suffix right away
16781            if (suffix != null && subStr.endsWith(suffix)) {
16782                subStr = subStr.substring(0, subStr.length() - suffix.length());
16783            }
16784            // If oldCodePath already contains prefix find out the
16785            // ending index to either increment or decrement.
16786            int sidx = subStr.lastIndexOf(prefix);
16787            if (sidx != -1) {
16788                subStr = subStr.substring(sidx + prefix.length());
16789                if (subStr != null) {
16790                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
16791                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
16792                    }
16793                    try {
16794                        idx = Integer.parseInt(subStr);
16795                        if (idx <= 1) {
16796                            idx++;
16797                        } else {
16798                            idx--;
16799                        }
16800                    } catch(NumberFormatException e) {
16801                    }
16802                }
16803            }
16804        }
16805        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
16806        return prefix + idxStr;
16807    }
16808
16809    private File getNextCodePath(File targetDir, String packageName) {
16810        File result;
16811        SecureRandom random = new SecureRandom();
16812        byte[] bytes = new byte[16];
16813        do {
16814            random.nextBytes(bytes);
16815            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16816            result = new File(targetDir, packageName + "-" + suffix);
16817        } while (result.exists());
16818        return result;
16819    }
16820
16821    // Utility method that returns the relative package path with respect
16822    // to the installation directory. Like say for /data/data/com.test-1.apk
16823    // string com.test-1 is returned.
16824    static String deriveCodePathName(String codePath) {
16825        if (codePath == null) {
16826            return null;
16827        }
16828        final File codeFile = new File(codePath);
16829        final String name = codeFile.getName();
16830        if (codeFile.isDirectory()) {
16831            return name;
16832        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16833            final int lastDot = name.lastIndexOf('.');
16834            return name.substring(0, lastDot);
16835        } else {
16836            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16837            return null;
16838        }
16839    }
16840
16841    static class PackageInstalledInfo {
16842        String name;
16843        int uid;
16844        // The set of users that originally had this package installed.
16845        int[] origUsers;
16846        // The set of users that now have this package installed.
16847        int[] newUsers;
16848        PackageParser.Package pkg;
16849        int returnCode;
16850        String returnMsg;
16851        PackageRemovedInfo removedInfo;
16852        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16853
16854        public void setError(int code, String msg) {
16855            setReturnCode(code);
16856            setReturnMessage(msg);
16857            Slog.w(TAG, msg);
16858        }
16859
16860        public void setError(String msg, PackageParserException e) {
16861            setReturnCode(e.error);
16862            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16863            Slog.w(TAG, msg, e);
16864        }
16865
16866        public void setError(String msg, PackageManagerException e) {
16867            returnCode = e.error;
16868            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16869            Slog.w(TAG, msg, e);
16870        }
16871
16872        public void setReturnCode(int returnCode) {
16873            this.returnCode = returnCode;
16874            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16875            for (int i = 0; i < childCount; i++) {
16876                addedChildPackages.valueAt(i).returnCode = returnCode;
16877            }
16878        }
16879
16880        private void setReturnMessage(String returnMsg) {
16881            this.returnMsg = returnMsg;
16882            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16883            for (int i = 0; i < childCount; i++) {
16884                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16885            }
16886        }
16887
16888        // In some error cases we want to convey more info back to the observer
16889        String origPackage;
16890        String origPermission;
16891    }
16892
16893    /*
16894     * Install a non-existing package.
16895     */
16896    private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags,
16897            int scanFlags, UserHandle user, String installerPackageName, String volumeUuid,
16898            PackageInstalledInfo res, int installReason) {
16899        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16900
16901        // Remember this for later, in case we need to rollback this install
16902        String pkgName = pkg.packageName;
16903
16904        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16905
16906        synchronized(mPackages) {
16907            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16908            if (renamedPackage != null) {
16909                // A package with the same name is already installed, though
16910                // it has been renamed to an older name.  The package we
16911                // are trying to install should be installed as an update to
16912                // the existing one, but that has not been requested, so bail.
16913                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16914                        + " without first uninstalling package running as "
16915                        + renamedPackage);
16916                return;
16917            }
16918            if (mPackages.containsKey(pkgName)) {
16919                // Don't allow installation over an existing package with the same name.
16920                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16921                        + " without first uninstalling.");
16922                return;
16923            }
16924        }
16925
16926        try {
16927            PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags,
16928                    System.currentTimeMillis(), user);
16929
16930            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16931
16932            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16933                prepareAppDataAfterInstallLIF(newPackage);
16934
16935            } else {
16936                // Remove package from internal structures, but keep around any
16937                // data that might have already existed
16938                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16939                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16940            }
16941        } catch (PackageManagerException e) {
16942            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16943        }
16944
16945        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16946    }
16947
16948    private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) {
16949        // Can't rotate keys during boot or if sharedUser.
16950        if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null
16951                || !oldPs.keySetData.isUsingUpgradeKeySets()) {
16952            return false;
16953        }
16954        // app is using upgradeKeySets; make sure all are valid
16955        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16956        long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets();
16957        for (int i = 0; i < upgradeKeySets.length; i++) {
16958            if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) {
16959                Slog.wtf(TAG, "Package "
16960                         + (oldPs.name != null ? oldPs.name : "<null>")
16961                         + " contains upgrade-key-set reference to unknown key-set: "
16962                         + upgradeKeySets[i]
16963                         + " reverting to signatures check.");
16964                return false;
16965            }
16966        }
16967        return true;
16968    }
16969
16970    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
16971        // Upgrade keysets are being used.  Determine if new package has a superset of the
16972        // required keys.
16973        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
16974        KeySetManagerService ksms = mSettings.mKeySetManagerService;
16975        for (int i = 0; i < upgradeKeySets.length; i++) {
16976            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
16977            if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) {
16978                return true;
16979            }
16980        }
16981        return false;
16982    }
16983
16984    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16985        try (DigestInputStream digestStream =
16986                new DigestInputStream(new FileInputStream(file), digest)) {
16987            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16988        }
16989    }
16990
16991    private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags,
16992            UserHandle user, String installerPackageName, PackageInstalledInfo res,
16993            int installReason) {
16994        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16995
16996        final PackageParser.Package oldPackage;
16997        final PackageSetting ps;
16998        final String pkgName = pkg.packageName;
16999        final int[] allUsers;
17000        final int[] installedUsers;
17001
17002        synchronized(mPackages) {
17003            oldPackage = mPackages.get(pkgName);
17004            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17005
17006            // don't allow upgrade to target a release SDK from a pre-release SDK
17007            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
17008                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17009            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
17010                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
17011            if (oldTargetsPreRelease
17012                    && !newTargetsPreRelease
17013                    && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
17014                Slog.w(TAG, "Can't install package targeting released sdk");
17015                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
17016                return;
17017            }
17018
17019            ps = mSettings.mPackages.get(pkgName);
17020
17021            // verify signatures are valid
17022            if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) {
17023                if (!checkUpgradeKeySetLP(ps, pkg)) {
17024                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17025                            "New package not signed by keys specified by upgrade-keysets: "
17026                                    + pkgName);
17027                    return;
17028                }
17029            } else {
17030                // default to original signature matching
17031                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
17032                        != PackageManager.SIGNATURE_MATCH) {
17033                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17034                            "New package has a different signature: " + pkgName);
17035                    return;
17036                }
17037            }
17038
17039            // don't allow a system upgrade unless the upgrade hash matches
17040            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) {
17041                byte[] digestBytes = null;
17042                try {
17043                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17044                    updateDigest(digest, new File(pkg.baseCodePath));
17045                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17046                        for (String path : pkg.splitCodePaths) {
17047                            updateDigest(digest, new File(path));
17048                        }
17049                    }
17050                    digestBytes = digest.digest();
17051                } catch (NoSuchAlgorithmException | IOException e) {
17052                    res.setError(INSTALL_FAILED_INVALID_APK,
17053                            "Could not compute hash: " + pkgName);
17054                    return;
17055                }
17056                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17057                    res.setError(INSTALL_FAILED_INVALID_APK,
17058                            "New package fails restrict-update check: " + pkgName);
17059                    return;
17060                }
17061                // retain upgrade restriction
17062                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17063            }
17064
17065            // Check for shared user id changes
17066            String invalidPackageName =
17067                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17068            if (invalidPackageName != null) {
17069                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17070                        "Package " + invalidPackageName + " tried to change user "
17071                                + oldPackage.mSharedUserId);
17072                return;
17073            }
17074
17075            // In case of rollback, remember per-user/profile install state
17076            allUsers = sUserManager.getUserIds();
17077            installedUsers = ps.queryInstalledUsers(allUsers, true);
17078
17079            // don't allow an upgrade from full to ephemeral
17080            if (isInstantApp) {
17081                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
17082                    for (int currentUser : allUsers) {
17083                        if (!ps.getInstantApp(currentUser)) {
17084                            // can't downgrade from full to instant
17085                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17086                                    + " for user: " + currentUser);
17087                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17088                            return;
17089                        }
17090                    }
17091                } else if (!ps.getInstantApp(user.getIdentifier())) {
17092                    // can't downgrade from full to instant
17093                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
17094                            + " for user: " + user.getIdentifier());
17095                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17096                    return;
17097                }
17098            }
17099        }
17100
17101        // Update what is removed
17102        res.removedInfo = new PackageRemovedInfo(this);
17103        res.removedInfo.uid = oldPackage.applicationInfo.uid;
17104        res.removedInfo.removedPackage = oldPackage.packageName;
17105        res.removedInfo.installerPackageName = ps.installerPackageName;
17106        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17107        res.removedInfo.isUpdate = true;
17108        res.removedInfo.origUsers = installedUsers;
17109        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17110        for (int i = 0; i < installedUsers.length; i++) {
17111            final int userId = installedUsers[i];
17112            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17113        }
17114
17115        final int childCount = (oldPackage.childPackages != null)
17116                ? oldPackage.childPackages.size() : 0;
17117        for (int i = 0; i < childCount; i++) {
17118            boolean childPackageUpdated = false;
17119            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
17120            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17121            if (res.addedChildPackages != null) {
17122                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17123                if (childRes != null) {
17124                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17125                    childRes.removedInfo.removedPackage = childPkg.packageName;
17126                    if (childPs != null) {
17127                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17128                    }
17129                    childRes.removedInfo.isUpdate = true;
17130                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
17131                    childPackageUpdated = true;
17132                }
17133            }
17134            if (!childPackageUpdated) {
17135                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17136                childRemovedRes.removedPackage = childPkg.packageName;
17137                if (childPs != null) {
17138                    childRemovedRes.installerPackageName = childPs.installerPackageName;
17139                }
17140                childRemovedRes.isUpdate = false;
17141                childRemovedRes.dataRemoved = true;
17142                synchronized (mPackages) {
17143                    if (childPs != null) {
17144                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
17145                    }
17146                }
17147                if (res.removedInfo.removedChildPackages == null) {
17148                    res.removedInfo.removedChildPackages = new ArrayMap<>();
17149                }
17150                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
17151            }
17152        }
17153
17154        boolean sysPkg = (isSystemApp(oldPackage));
17155        if (sysPkg) {
17156            // Set the system/privileged flags as needed
17157            final boolean privileged =
17158                    (oldPackage.applicationInfo.privateFlags
17159                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17160            final int systemPolicyFlags = policyFlags
17161                    | PackageParser.PARSE_IS_SYSTEM
17162                    | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0);
17163
17164            replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags,
17165                    user, allUsers, installerPackageName, res, installReason);
17166        } else {
17167            replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags,
17168                    user, allUsers, installerPackageName, res, installReason);
17169        }
17170    }
17171
17172    @Override
17173    public List<String> getPreviousCodePaths(String packageName) {
17174        final int callingUid = Binder.getCallingUid();
17175        final List<String> result = new ArrayList<>();
17176        if (getInstantAppPackageName(callingUid) != null) {
17177            return result;
17178        }
17179        final PackageSetting ps = mSettings.mPackages.get(packageName);
17180        if (ps != null
17181                && ps.oldCodePaths != null
17182                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
17183            result.addAll(ps.oldCodePaths);
17184        }
17185        return result;
17186    }
17187
17188    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
17189            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17190            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17191            int installReason) {
17192        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
17193                + deletedPackage);
17194
17195        String pkgName = deletedPackage.packageName;
17196        boolean deletedPkg = true;
17197        boolean addedPkg = false;
17198        boolean updatedSettings = false;
17199        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
17200        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
17201                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
17202
17203        final long origUpdateTime = (pkg.mExtras != null)
17204                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
17205
17206        // First delete the existing package while retaining the data directory
17207        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17208                res.removedInfo, true, pkg)) {
17209            // If the existing package wasn't successfully deleted
17210            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
17211            deletedPkg = false;
17212        } else {
17213            // Successfully deleted the old package; proceed with replace.
17214
17215            // If deleted package lived in a container, give users a chance to
17216            // relinquish resources before killing.
17217            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
17218                if (DEBUG_INSTALL) {
17219                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
17220                }
17221                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
17222                final ArrayList<String> pkgList = new ArrayList<String>(1);
17223                pkgList.add(deletedPackage.applicationInfo.packageName);
17224                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
17225            }
17226
17227            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17228                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17229            clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17230
17231            try {
17232                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags,
17233                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
17234                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17235                        installReason);
17236
17237                // Update the in-memory copy of the previous code paths.
17238                PackageSetting ps = mSettings.mPackages.get(pkgName);
17239                if (!killApp) {
17240                    if (ps.oldCodePaths == null) {
17241                        ps.oldCodePaths = new ArraySet<>();
17242                    }
17243                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
17244                    if (deletedPackage.splitCodePaths != null) {
17245                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
17246                    }
17247                } else {
17248                    ps.oldCodePaths = null;
17249                }
17250                if (ps.childPackageNames != null) {
17251                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
17252                        final String childPkgName = ps.childPackageNames.get(i);
17253                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
17254                        childPs.oldCodePaths = ps.oldCodePaths;
17255                    }
17256                }
17257                // set instant app status, but, only if it's explicitly specified
17258                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17259                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
17260                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
17261                prepareAppDataAfterInstallLIF(newPackage);
17262                addedPkg = true;
17263                mDexManager.notifyPackageUpdated(newPackage.packageName,
17264                        newPackage.baseCodePath, newPackage.splitCodePaths);
17265            } catch (PackageManagerException e) {
17266                res.setError("Package couldn't be installed in " + pkg.codePath, e);
17267            }
17268        }
17269
17270        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17271            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
17272
17273            // Revert all internal state mutations and added folders for the failed install
17274            if (addedPkg) {
17275                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
17276                        res.removedInfo, true, null);
17277            }
17278
17279            // Restore the old package
17280            if (deletedPkg) {
17281                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
17282                File restoreFile = new File(deletedPackage.codePath);
17283                // Parse old package
17284                boolean oldExternal = isExternal(deletedPackage);
17285                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
17286                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
17287                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17288                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
17289                try {
17290                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
17291                            null);
17292                } catch (PackageManagerException e) {
17293                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
17294                            + e.getMessage());
17295                    return;
17296                }
17297
17298                synchronized (mPackages) {
17299                    // Ensure the installer package name up to date
17300                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17301
17302                    // Update permissions for restored package
17303                    updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17304
17305                    mSettings.writeLPr();
17306                }
17307
17308                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
17309            }
17310        } else {
17311            synchronized (mPackages) {
17312                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
17313                if (ps != null) {
17314                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
17315                    if (res.removedInfo.removedChildPackages != null) {
17316                        final int childCount = res.removedInfo.removedChildPackages.size();
17317                        // Iterate in reverse as we may modify the collection
17318                        for (int i = childCount - 1; i >= 0; i--) {
17319                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
17320                            if (res.addedChildPackages.containsKey(childPackageName)) {
17321                                res.removedInfo.removedChildPackages.removeAt(i);
17322                            } else {
17323                                PackageRemovedInfo childInfo = res.removedInfo
17324                                        .removedChildPackages.valueAt(i);
17325                                childInfo.removedForAllUsers = mPackages.get(
17326                                        childInfo.removedPackage) == null;
17327                            }
17328                        }
17329                    }
17330                }
17331            }
17332        }
17333    }
17334
17335    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
17336            PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user,
17337            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
17338            int installReason) {
17339        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17340                + ", old=" + deletedPackage);
17341
17342        final boolean disabledSystem;
17343
17344        // Remove existing system package
17345        removePackageLI(deletedPackage, true);
17346
17347        synchronized (mPackages) {
17348            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
17349        }
17350        if (!disabledSystem) {
17351            // We didn't need to disable the .apk as a current system package,
17352            // which means we are replacing another update that is already
17353            // installed.  We need to make sure to delete the older one's .apk.
17354            res.removedInfo.args = createInstallArgsForExisting(0,
17355                    deletedPackage.applicationInfo.getCodePath(),
17356                    deletedPackage.applicationInfo.getResourcePath(),
17357                    getAppDexInstructionSets(deletedPackage.applicationInfo));
17358        } else {
17359            res.removedInfo.args = null;
17360        }
17361
17362        // Successfully disabled the old package. Now proceed with re-installation
17363        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
17364                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17365        clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL);
17366
17367        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17368        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17369                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17370
17371        PackageParser.Package newPackage = null;
17372        try {
17373            // Add the package to the internal data structures
17374            newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user);
17375
17376            // Set the update and install times
17377            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
17378            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
17379                    System.currentTimeMillis());
17380
17381            // Update the package dynamic state if succeeded
17382            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17383                // Now that the install succeeded make sure we remove data
17384                // directories for any child package the update removed.
17385                final int deletedChildCount = (deletedPackage.childPackages != null)
17386                        ? deletedPackage.childPackages.size() : 0;
17387                final int newChildCount = (newPackage.childPackages != null)
17388                        ? newPackage.childPackages.size() : 0;
17389                for (int i = 0; i < deletedChildCount; i++) {
17390                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
17391                    boolean childPackageDeleted = true;
17392                    for (int j = 0; j < newChildCount; j++) {
17393                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
17394                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
17395                            childPackageDeleted = false;
17396                            break;
17397                        }
17398                    }
17399                    if (childPackageDeleted) {
17400                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
17401                                deletedChildPkg.packageName);
17402                        if (ps != null && res.removedInfo.removedChildPackages != null) {
17403                            PackageRemovedInfo removedChildRes = res.removedInfo
17404                                    .removedChildPackages.get(deletedChildPkg.packageName);
17405                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
17406                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
17407                        }
17408                    }
17409                }
17410
17411                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
17412                        installReason);
17413                prepareAppDataAfterInstallLIF(newPackage);
17414
17415                mDexManager.notifyPackageUpdated(newPackage.packageName,
17416                            newPackage.baseCodePath, newPackage.splitCodePaths);
17417            }
17418        } catch (PackageManagerException e) {
17419            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
17420            res.setError("Package couldn't be installed in " + pkg.codePath, e);
17421        }
17422
17423        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
17424            // Re installation failed. Restore old information
17425            // Remove new pkg information
17426            if (newPackage != null) {
17427                removeInstalledPackageLI(newPackage, true);
17428            }
17429            // Add back the old system package
17430            try {
17431                scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user);
17432            } catch (PackageManagerException e) {
17433                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
17434            }
17435
17436            synchronized (mPackages) {
17437                if (disabledSystem) {
17438                    enableSystemPackageLPw(deletedPackage);
17439                }
17440
17441                // Ensure the installer package name up to date
17442                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
17443
17444                // Update permissions for restored package
17445                updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL);
17446
17447                mSettings.writeLPr();
17448            }
17449
17450            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
17451                    + " after failed upgrade");
17452        }
17453    }
17454
17455    /**
17456     * Checks whether the parent or any of the child packages have a change shared
17457     * user. For a package to be a valid update the shred users of the parent and
17458     * the children should match. We may later support changing child shared users.
17459     * @param oldPkg The updated package.
17460     * @param newPkg The update package.
17461     * @return The shared user that change between the versions.
17462     */
17463    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
17464            PackageParser.Package newPkg) {
17465        // Check parent shared user
17466        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
17467            return newPkg.packageName;
17468        }
17469        // Check child shared users
17470        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17471        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
17472        for (int i = 0; i < newChildCount; i++) {
17473            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
17474            // If this child was present, did it have the same shared user?
17475            for (int j = 0; j < oldChildCount; j++) {
17476                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
17477                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
17478                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
17479                    return newChildPkg.packageName;
17480                }
17481            }
17482        }
17483        return null;
17484    }
17485
17486    private void removeNativeBinariesLI(PackageSetting ps) {
17487        // Remove the lib path for the parent package
17488        if (ps != null) {
17489            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
17490            // Remove the lib path for the child packages
17491            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
17492            for (int i = 0; i < childCount; i++) {
17493                PackageSetting childPs = null;
17494                synchronized (mPackages) {
17495                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
17496                }
17497                if (childPs != null) {
17498                    NativeLibraryHelper.removeNativeBinariesLI(childPs
17499                            .legacyNativeLibraryPathString);
17500                }
17501            }
17502        }
17503    }
17504
17505    private void enableSystemPackageLPw(PackageParser.Package pkg) {
17506        // Enable the parent package
17507        mSettings.enableSystemPackageLPw(pkg.packageName);
17508        // Enable the child packages
17509        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17510        for (int i = 0; i < childCount; i++) {
17511            PackageParser.Package childPkg = pkg.childPackages.get(i);
17512            mSettings.enableSystemPackageLPw(childPkg.packageName);
17513        }
17514    }
17515
17516    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
17517            PackageParser.Package newPkg) {
17518        // Disable the parent package (parent always replaced)
17519        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
17520        // Disable the child packages
17521        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
17522        for (int i = 0; i < childCount; i++) {
17523            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
17524            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
17525            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
17526        }
17527        return disabled;
17528    }
17529
17530    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
17531            String installerPackageName) {
17532        // Enable the parent package
17533        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
17534        // Enable the child packages
17535        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17536        for (int i = 0; i < childCount; i++) {
17537            PackageParser.Package childPkg = pkg.childPackages.get(i);
17538            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
17539        }
17540    }
17541
17542    private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) {
17543        // Collect all used permissions in the UID
17544        ArraySet<String> usedPermissions = new ArraySet<>();
17545        final int packageCount = su.packages.size();
17546        for (int i = 0; i < packageCount; i++) {
17547            PackageSetting ps = su.packages.valueAt(i);
17548            if (ps.pkg == null) {
17549                continue;
17550            }
17551            final int requestedPermCount = ps.pkg.requestedPermissions.size();
17552            for (int j = 0; j < requestedPermCount; j++) {
17553                String permission = ps.pkg.requestedPermissions.get(j);
17554                BasePermission bp = mSettings.mPermissions.get(permission);
17555                if (bp != null) {
17556                    usedPermissions.add(permission);
17557                }
17558            }
17559        }
17560
17561        PermissionsState permissionsState = su.getPermissionsState();
17562        // Prune install permissions
17563        List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates();
17564        final int installPermCount = installPermStates.size();
17565        for (int i = installPermCount - 1; i >= 0;  i--) {
17566            PermissionState permissionState = installPermStates.get(i);
17567            if (!usedPermissions.contains(permissionState.getName())) {
17568                BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17569                if (bp != null) {
17570                    permissionsState.revokeInstallPermission(bp);
17571                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
17572                            PackageManager.MASK_PERMISSION_FLAGS, 0);
17573                }
17574            }
17575        }
17576
17577        int[] runtimePermissionChangedUserIds = EmptyArray.INT;
17578
17579        // Prune runtime permissions
17580        for (int userId : allUserIds) {
17581            List<PermissionState> runtimePermStates = permissionsState
17582                    .getRuntimePermissionStates(userId);
17583            final int runtimePermCount = runtimePermStates.size();
17584            for (int i = runtimePermCount - 1; i >= 0; i--) {
17585                PermissionState permissionState = runtimePermStates.get(i);
17586                if (!usedPermissions.contains(permissionState.getName())) {
17587                    BasePermission bp = mSettings.mPermissions.get(permissionState.getName());
17588                    if (bp != null) {
17589                        permissionsState.revokeRuntimePermission(bp, userId);
17590                        permissionsState.updatePermissionFlags(bp, userId,
17591                                PackageManager.MASK_PERMISSION_FLAGS, 0);
17592                        runtimePermissionChangedUserIds = ArrayUtils.appendInt(
17593                                runtimePermissionChangedUserIds, userId);
17594                    }
17595                }
17596            }
17597        }
17598
17599        return runtimePermissionChangedUserIds;
17600    }
17601
17602    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
17603            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
17604        // Update the parent package setting
17605        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
17606                res, user, installReason);
17607        // Update the child packages setting
17608        final int childCount = (newPackage.childPackages != null)
17609                ? newPackage.childPackages.size() : 0;
17610        for (int i = 0; i < childCount; i++) {
17611            PackageParser.Package childPackage = newPackage.childPackages.get(i);
17612            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
17613            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
17614                    childRes.origUsers, childRes, user, installReason);
17615        }
17616    }
17617
17618    private void updateSettingsInternalLI(PackageParser.Package newPackage,
17619            String installerPackageName, int[] allUsers, int[] installedForUsers,
17620            PackageInstalledInfo res, UserHandle user, int installReason) {
17621        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
17622
17623        String pkgName = newPackage.packageName;
17624        synchronized (mPackages) {
17625            //write settings. the installStatus will be incomplete at this stage.
17626            //note that the new package setting would have already been
17627            //added to mPackages. It hasn't been persisted yet.
17628            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
17629            // TODO: Remove this write? It's also written at the end of this method
17630            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17631            mSettings.writeLPr();
17632            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17633        }
17634
17635        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
17636        synchronized (mPackages) {
17637            updatePermissionsLPw(newPackage.packageName, newPackage,
17638                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
17639                            ? UPDATE_PERMISSIONS_ALL : 0));
17640            // For system-bundled packages, we assume that installing an upgraded version
17641            // of the package implies that the user actually wants to run that new code,
17642            // so we enable the package.
17643            PackageSetting ps = mSettings.mPackages.get(pkgName);
17644            final int userId = user.getIdentifier();
17645            if (ps != null) {
17646                if (isSystemApp(newPackage)) {
17647                    if (DEBUG_INSTALL) {
17648                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
17649                    }
17650                    // Enable system package for requested users
17651                    if (res.origUsers != null) {
17652                        for (int origUserId : res.origUsers) {
17653                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
17654                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
17655                                        origUserId, installerPackageName);
17656                            }
17657                        }
17658                    }
17659                    // Also convey the prior install/uninstall state
17660                    if (allUsers != null && installedForUsers != null) {
17661                        for (int currentUserId : allUsers) {
17662                            final boolean installed = ArrayUtils.contains(
17663                                    installedForUsers, currentUserId);
17664                            if (DEBUG_INSTALL) {
17665                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
17666                            }
17667                            ps.setInstalled(installed, currentUserId);
17668                        }
17669                        // these install state changes will be persisted in the
17670                        // upcoming call to mSettings.writeLPr().
17671                    }
17672                }
17673                // It's implied that when a user requests installation, they want the app to be
17674                // installed and enabled.
17675                if (userId != UserHandle.USER_ALL) {
17676                    ps.setInstalled(true, userId);
17677                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
17678                }
17679
17680                // When replacing an existing package, preserve the original install reason for all
17681                // users that had the package installed before.
17682                final Set<Integer> previousUserIds = new ArraySet<>();
17683                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
17684                    final int installReasonCount = res.removedInfo.installReasons.size();
17685                    for (int i = 0; i < installReasonCount; i++) {
17686                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
17687                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
17688                        ps.setInstallReason(previousInstallReason, previousUserId);
17689                        previousUserIds.add(previousUserId);
17690                    }
17691                }
17692
17693                // Set install reason for users that are having the package newly installed.
17694                if (userId == UserHandle.USER_ALL) {
17695                    for (int currentUserId : sUserManager.getUserIds()) {
17696                        if (!previousUserIds.contains(currentUserId)) {
17697                            ps.setInstallReason(installReason, currentUserId);
17698                        }
17699                    }
17700                } else if (!previousUserIds.contains(userId)) {
17701                    ps.setInstallReason(installReason, userId);
17702                }
17703                mSettings.writeKernelMappingLPr(ps);
17704            }
17705            res.name = pkgName;
17706            res.uid = newPackage.applicationInfo.uid;
17707            res.pkg = newPackage;
17708            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
17709            mSettings.setInstallerPackageName(pkgName, installerPackageName);
17710            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17711            //to update install status
17712            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
17713            mSettings.writeLPr();
17714            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17715        }
17716
17717        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17718    }
17719
17720    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
17721        try {
17722            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
17723            installPackageLI(args, res);
17724        } finally {
17725            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17726        }
17727    }
17728
17729    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
17730        final int installFlags = args.installFlags;
17731        final String installerPackageName = args.installerPackageName;
17732        final String volumeUuid = args.volumeUuid;
17733        final File tmpPackageFile = new File(args.getCodePath());
17734        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
17735        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
17736                || (args.volumeUuid != null));
17737        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17738        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17739        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
17740        boolean replace = false;
17741        int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17742        if (args.move != null) {
17743            // moving a complete application; perform an initial scan on the new install location
17744            scanFlags |= SCAN_INITIAL;
17745        }
17746        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17747            scanFlags |= SCAN_DONT_KILL_APP;
17748        }
17749        if (instantApp) {
17750            scanFlags |= SCAN_AS_INSTANT_APP;
17751        }
17752        if (fullApp) {
17753            scanFlags |= SCAN_AS_FULL_APP;
17754        }
17755
17756        // Result object to be returned
17757        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17758
17759        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17760
17761        // Sanity check
17762        if (instantApp && (forwardLocked || onExternal)) {
17763            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
17764                    + " external=" + onExternal);
17765            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17766            return;
17767        }
17768
17769        // Retrieve PackageSettings and parse package
17770        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17771                | PackageParser.PARSE_ENFORCE_CODE
17772                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
17773                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
17774                | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0)
17775                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
17776        PackageParser pp = new PackageParser();
17777        pp.setSeparateProcesses(mSeparateProcesses);
17778        pp.setDisplayMetrics(mMetrics);
17779        pp.setCallback(mPackageParserCallback);
17780
17781        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17782        final PackageParser.Package pkg;
17783        try {
17784            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17785        } catch (PackageParserException e) {
17786            res.setError("Failed parse during installPackageLI", e);
17787            return;
17788        } finally {
17789            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17790        }
17791
17792        // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2
17793        if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) {
17794            Slog.w(TAG, "Instant app package " + pkg.packageName
17795                    + " does not target O, this will be a fatal error.");
17796            // STOPSHIP: Make this a fatal error
17797            pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O;
17798        }
17799        if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) {
17800            Slog.w(TAG, "Instant app package " + pkg.packageName
17801                    + " does not target targetSandboxVersion 2, this will be a fatal error.");
17802            // STOPSHIP: Make this a fatal error
17803            pkg.applicationInfo.targetSandboxVersion = 2;
17804        }
17805
17806        if (pkg.applicationInfo.isStaticSharedLibrary()) {
17807            // Static shared libraries have synthetic package names
17808            renameStaticSharedLibraryPackage(pkg);
17809
17810            // No static shared libs on external storage
17811            if (onExternal) {
17812                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17813                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17814                        "Packages declaring static-shared libs cannot be updated");
17815                return;
17816            }
17817        }
17818
17819        // If we are installing a clustered package add results for the children
17820        if (pkg.childPackages != null) {
17821            synchronized (mPackages) {
17822                final int childCount = pkg.childPackages.size();
17823                for (int i = 0; i < childCount; i++) {
17824                    PackageParser.Package childPkg = pkg.childPackages.get(i);
17825                    PackageInstalledInfo childRes = new PackageInstalledInfo();
17826                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17827                    childRes.pkg = childPkg;
17828                    childRes.name = childPkg.packageName;
17829                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17830                    if (childPs != null) {
17831                        childRes.origUsers = childPs.queryInstalledUsers(
17832                                sUserManager.getUserIds(), true);
17833                    }
17834                    if ((mPackages.containsKey(childPkg.packageName))) {
17835                        childRes.removedInfo = new PackageRemovedInfo(this);
17836                        childRes.removedInfo.removedPackage = childPkg.packageName;
17837                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17838                    }
17839                    if (res.addedChildPackages == null) {
17840                        res.addedChildPackages = new ArrayMap<>();
17841                    }
17842                    res.addedChildPackages.put(childPkg.packageName, childRes);
17843                }
17844            }
17845        }
17846
17847        // If package doesn't declare API override, mark that we have an install
17848        // time CPU ABI override.
17849        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17850            pkg.cpuAbiOverride = args.abiOverride;
17851        }
17852
17853        String pkgName = res.name = pkg.packageName;
17854        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17855            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17856                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17857                return;
17858            }
17859        }
17860
17861        try {
17862            // either use what we've been given or parse directly from the APK
17863            if (args.certificates != null) {
17864                try {
17865                    PackageParser.populateCertificates(pkg, args.certificates);
17866                } catch (PackageParserException e) {
17867                    // there was something wrong with the certificates we were given;
17868                    // try to pull them from the APK
17869                    PackageParser.collectCertificates(pkg, parseFlags);
17870                }
17871            } else {
17872                PackageParser.collectCertificates(pkg, parseFlags);
17873            }
17874        } catch (PackageParserException e) {
17875            res.setError("Failed collect during installPackageLI", e);
17876            return;
17877        }
17878
17879        // Get rid of all references to package scan path via parser.
17880        pp = null;
17881        String oldCodePath = null;
17882        boolean systemApp = false;
17883        synchronized (mPackages) {
17884            // Check if installing already existing package
17885            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17886                String oldName = mSettings.getRenamedPackageLPr(pkgName);
17887                if (pkg.mOriginalPackages != null
17888                        && pkg.mOriginalPackages.contains(oldName)
17889                        && mPackages.containsKey(oldName)) {
17890                    // This package is derived from an original package,
17891                    // and this device has been updating from that original
17892                    // name.  We must continue using the original name, so
17893                    // rename the new package here.
17894                    pkg.setPackageName(oldName);
17895                    pkgName = pkg.packageName;
17896                    replace = true;
17897                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
17898                            + oldName + " pkgName=" + pkgName);
17899                } else if (mPackages.containsKey(pkgName)) {
17900                    // This package, under its official name, already exists
17901                    // on the device; we should replace it.
17902                    replace = true;
17903                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17904                }
17905
17906                // Child packages are installed through the parent package
17907                if (pkg.parentPackage != null) {
17908                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17909                            "Package " + pkg.packageName + " is child of package "
17910                                    + pkg.parentPackage.parentPackage + ". Child packages "
17911                                    + "can be updated only through the parent package.");
17912                    return;
17913                }
17914
17915                if (replace) {
17916                    // Prevent apps opting out from runtime permissions
17917                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17918                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17919                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17920                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17921                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17922                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17923                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17924                                        + " doesn't support runtime permissions but the old"
17925                                        + " target SDK " + oldTargetSdk + " does.");
17926                        return;
17927                    }
17928                    // Prevent apps from downgrading their targetSandbox.
17929                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17930                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17931                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17932                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17933                                "Package " + pkg.packageName + " new target sandbox "
17934                                + newTargetSandbox + " is incompatible with the previous value of"
17935                                + oldTargetSandbox + ".");
17936                        return;
17937                    }
17938
17939                    // Prevent installing of child packages
17940                    if (oldPackage.parentPackage != null) {
17941                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17942                                "Package " + pkg.packageName + " is child of package "
17943                                        + oldPackage.parentPackage + ". Child packages "
17944                                        + "can be updated only through the parent package.");
17945                        return;
17946                    }
17947                }
17948            }
17949
17950            PackageSetting ps = mSettings.mPackages.get(pkgName);
17951            if (ps != null) {
17952                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17953
17954                // Static shared libs have same package with different versions where
17955                // we internally use a synthetic package name to allow multiple versions
17956                // of the same package, therefore we need to compare signatures against
17957                // the package setting for the latest library version.
17958                PackageSetting signatureCheckPs = ps;
17959                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17960                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17961                    if (libraryEntry != null) {
17962                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17963                    }
17964                }
17965
17966                // Quick sanity check that we're signed correctly if updating;
17967                // we'll check this again later when scanning, but we want to
17968                // bail early here before tripping over redefined permissions.
17969                if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) {
17970                    if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) {
17971                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17972                                + pkg.packageName + " upgrade keys do not match the "
17973                                + "previously installed version");
17974                        return;
17975                    }
17976                } else {
17977                    try {
17978                        verifySignaturesLP(signatureCheckPs, pkg);
17979                    } catch (PackageManagerException e) {
17980                        res.setError(e.error, e.getMessage());
17981                        return;
17982                    }
17983                }
17984
17985                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17986                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17987                    systemApp = (ps.pkg.applicationInfo.flags &
17988                            ApplicationInfo.FLAG_SYSTEM) != 0;
17989                }
17990                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17991            }
17992
17993            int N = pkg.permissions.size();
17994            for (int i = N-1; i >= 0; i--) {
17995                PackageParser.Permission perm = pkg.permissions.get(i);
17996                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
17997
17998                // Don't allow anyone but the system to define ephemeral permissions.
17999                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0
18000                        && !systemApp) {
18001                    Slog.w(TAG, "Non-System package " + pkg.packageName
18002                            + " attempting to delcare ephemeral permission "
18003                            + perm.info.name + "; Removing ephemeral.");
18004                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL;
18005                }
18006                // Check whether the newly-scanned package wants to define an already-defined perm
18007                if (bp != null) {
18008                    // If the defining package is signed with our cert, it's okay.  This
18009                    // also includes the "updating the same package" case, of course.
18010                    // "updating same package" could also involve key-rotation.
18011                    final boolean sigsOk;
18012                    if (bp.sourcePackage.equals(pkg.packageName)
18013                            && (bp.packageSetting instanceof PackageSetting)
18014                            && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting,
18015                                    scanFlags))) {
18016                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
18017                    } else {
18018                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
18019                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
18020                    }
18021                    if (!sigsOk) {
18022                        // If the owning package is the system itself, we log but allow
18023                        // install to proceed; we fail the install on all other permission
18024                        // redefinitions.
18025                        if (!bp.sourcePackage.equals("android")) {
18026                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
18027                                    + pkg.packageName + " attempting to redeclare permission "
18028                                    + perm.info.name + " already owned by " + bp.sourcePackage);
18029                            res.origPermission = perm.info.name;
18030                            res.origPackage = bp.sourcePackage;
18031                            return;
18032                        } else {
18033                            Slog.w(TAG, "Package " + pkg.packageName
18034                                    + " attempting to redeclare system permission "
18035                                    + perm.info.name + "; ignoring new declaration");
18036                            pkg.permissions.remove(i);
18037                        }
18038                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
18039                        // Prevent apps to change protection level to dangerous from any other
18040                        // type as this would allow a privilege escalation where an app adds a
18041                        // normal/signature permission in other app's group and later redefines
18042                        // it as dangerous leading to the group auto-grant.
18043                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
18044                                == PermissionInfo.PROTECTION_DANGEROUS) {
18045                            if (bp != null && !bp.isRuntime()) {
18046                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
18047                                        + "non-runtime permission " + perm.info.name
18048                                        + " to runtime; keeping old protection level");
18049                                perm.info.protectionLevel = bp.protectionLevel;
18050                            }
18051                        }
18052                    }
18053                }
18054            }
18055        }
18056
18057        if (systemApp) {
18058            if (onExternal) {
18059                // Abort update; system app can't be replaced with app on sdcard
18060                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
18061                        "Cannot install updates to system apps on sdcard");
18062                return;
18063            } else if (instantApp) {
18064                // Abort update; system app can't be replaced with an instant app
18065                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
18066                        "Cannot update a system app with an instant app");
18067                return;
18068            }
18069        }
18070
18071        if (args.move != null) {
18072            // We did an in-place move, so dex is ready to roll
18073            scanFlags |= SCAN_NO_DEX;
18074            scanFlags |= SCAN_MOVE;
18075
18076            synchronized (mPackages) {
18077                final PackageSetting ps = mSettings.mPackages.get(pkgName);
18078                if (ps == null) {
18079                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
18080                            "Missing settings for moved package " + pkgName);
18081                }
18082
18083                // We moved the entire application as-is, so bring over the
18084                // previously derived ABI information.
18085                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
18086                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
18087            }
18088
18089        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
18090            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
18091            scanFlags |= SCAN_NO_DEX;
18092
18093            try {
18094                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
18095                    args.abiOverride : pkg.cpuAbiOverride);
18096                derivePackageAbi(pkg, new File(pkg.codePath), abiOverride,
18097                        true /*extractLibs*/, mAppLib32InstallDir);
18098            } catch (PackageManagerException pme) {
18099                Slog.e(TAG, "Error deriving application ABI", pme);
18100                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
18101                return;
18102            }
18103
18104            // Shared libraries for the package need to be updated.
18105            synchronized (mPackages) {
18106                try {
18107                    updateSharedLibrariesLPr(pkg, null);
18108                } catch (PackageManagerException e) {
18109                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18110                }
18111            }
18112
18113            // dexopt can take some time to complete, so, for instant apps, we skip this
18114            // step during installation. Instead, we'll take extra time the first time the
18115            // instant app starts. It's preferred to do it this way to provide continuous
18116            // progress to the user instead of mysteriously blocking somewhere in the
18117            // middle of running an instant app.
18118            if (!instantApp) {
18119                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
18120                // Do not run PackageDexOptimizer through the local performDexOpt
18121                // method because `pkg` may not be in `mPackages` yet.
18122                //
18123                // Also, don't fail application installs if the dexopt step fails.
18124                mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
18125                        null /* instructionSets */, false /* checkProfiles */,
18126                        getCompilerFilterForReason(REASON_INSTALL),
18127                        getOrCreateCompilerPackageStats(pkg),
18128                        mDexManager.isUsedByOtherApps(pkg.packageName));
18129                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
18130            }
18131
18132            // Notify BackgroundDexOptService that the package has been changed.
18133            // If this is an update of a package which used to fail to compile,
18134            // BDOS will remove it from its blacklist.
18135            // TODO: Layering violation
18136            BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
18137        }
18138
18139        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
18140            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
18141            return;
18142        }
18143
18144        startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
18145
18146        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
18147                "installPackageLI")) {
18148            if (replace) {
18149                if (pkg.applicationInfo.isStaticSharedLibrary()) {
18150                    // Static libs have a synthetic package name containing the version
18151                    // and cannot be updated as an update would get a new package name,
18152                    // unless this is the exact same version code which is useful for
18153                    // development.
18154                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
18155                    if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) {
18156                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
18157                                + "static-shared libs cannot be updated");
18158                        return;
18159                    }
18160                }
18161                replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
18162                        installerPackageName, res, args.installReason);
18163            } else {
18164                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
18165                        args.user, installerPackageName, volumeUuid, res, args.installReason);
18166            }
18167        }
18168
18169        synchronized (mPackages) {
18170            final PackageSetting ps = mSettings.mPackages.get(pkgName);
18171            if (ps != null) {
18172                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
18173                ps.setUpdateAvailable(false /*updateAvailable*/);
18174            }
18175
18176            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18177            for (int i = 0; i < childCount; i++) {
18178                PackageParser.Package childPkg = pkg.childPackages.get(i);
18179                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
18180                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
18181                if (childPs != null) {
18182                    childRes.newUsers = childPs.queryInstalledUsers(
18183                            sUserManager.getUserIds(), true);
18184                }
18185            }
18186
18187            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
18188                updateSequenceNumberLP(pkgName, res.newUsers);
18189                updateInstantAppInstallerLocked(pkgName);
18190            }
18191        }
18192    }
18193
18194    private void startIntentFilterVerifications(int userId, boolean replacing,
18195            PackageParser.Package pkg) {
18196        if (mIntentFilterVerifierComponent == null) {
18197            Slog.w(TAG, "No IntentFilter verification will not be done as "
18198                    + "there is no IntentFilterVerifier available!");
18199            return;
18200        }
18201
18202        final int verifierUid = getPackageUid(
18203                mIntentFilterVerifierComponent.getPackageName(),
18204                MATCH_DEBUG_TRIAGED_MISSING,
18205                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18206
18207        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18208        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18209        mHandler.sendMessage(msg);
18210
18211        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18212        for (int i = 0; i < childCount; i++) {
18213            PackageParser.Package childPkg = pkg.childPackages.get(i);
18214            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18215            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18216            mHandler.sendMessage(msg);
18217        }
18218    }
18219
18220    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18221            PackageParser.Package pkg) {
18222        int size = pkg.activities.size();
18223        if (size == 0) {
18224            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18225                    "No activity, so no need to verify any IntentFilter!");
18226            return;
18227        }
18228
18229        final boolean hasDomainURLs = hasDomainURLs(pkg);
18230        if (!hasDomainURLs) {
18231            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18232                    "No domain URLs, so no need to verify any IntentFilter!");
18233            return;
18234        }
18235
18236        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18237                + " if any IntentFilter from the " + size
18238                + " Activities needs verification ...");
18239
18240        int count = 0;
18241        final String packageName = pkg.packageName;
18242
18243        synchronized (mPackages) {
18244            // If this is a new install and we see that we've already run verification for this
18245            // package, we have nothing to do: it means the state was restored from backup.
18246            if (!replacing) {
18247                IntentFilterVerificationInfo ivi =
18248                        mSettings.getIntentFilterVerificationLPr(packageName);
18249                if (ivi != null) {
18250                    if (DEBUG_DOMAIN_VERIFICATION) {
18251                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
18252                                + ivi.getStatusString());
18253                    }
18254                    return;
18255                }
18256            }
18257
18258            // If any filters need to be verified, then all need to be.
18259            boolean needToVerify = false;
18260            for (PackageParser.Activity a : pkg.activities) {
18261                for (ActivityIntentInfo filter : a.intents) {
18262                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18263                        if (DEBUG_DOMAIN_VERIFICATION) {
18264                            Slog.d(TAG, "Intent filter needs verification, so processing all filters");
18265                        }
18266                        needToVerify = true;
18267                        break;
18268                    }
18269                }
18270            }
18271
18272            if (needToVerify) {
18273                final int verificationId = mIntentFilterVerificationToken++;
18274                for (PackageParser.Activity a : pkg.activities) {
18275                    for (ActivityIntentInfo filter : a.intents) {
18276                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18277                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18278                                    "Verification needed for IntentFilter:" + filter.toString());
18279                            mIntentFilterVerifier.addOneIntentFilterVerification(
18280                                    verifierUid, userId, verificationId, filter, packageName);
18281                            count++;
18282                        }
18283                    }
18284                }
18285            }
18286        }
18287
18288        if (count > 0) {
18289            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18290                    + " IntentFilter verification" + (count > 1 ? "s" : "")
18291                    +  " for userId:" + userId);
18292            mIntentFilterVerifier.startVerifications(userId);
18293        } else {
18294            if (DEBUG_DOMAIN_VERIFICATION) {
18295                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18296            }
18297        }
18298    }
18299
18300    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18301        final ComponentName cn  = filter.activity.getComponentName();
18302        final String packageName = cn.getPackageName();
18303
18304        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18305                packageName);
18306        if (ivi == null) {
18307            return true;
18308        }
18309        int status = ivi.getStatus();
18310        switch (status) {
18311            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18312            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18313                return true;
18314
18315            default:
18316                // Nothing to do
18317                return false;
18318        }
18319    }
18320
18321    private static boolean isMultiArch(ApplicationInfo info) {
18322        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18323    }
18324
18325    private static boolean isExternal(PackageParser.Package pkg) {
18326        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18327    }
18328
18329    private static boolean isExternal(PackageSetting ps) {
18330        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18331    }
18332
18333    private static boolean isSystemApp(PackageParser.Package pkg) {
18334        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18335    }
18336
18337    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18338        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18339    }
18340
18341    private static boolean hasDomainURLs(PackageParser.Package pkg) {
18342        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18343    }
18344
18345    private static boolean isSystemApp(PackageSetting ps) {
18346        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18347    }
18348
18349    private static boolean isUpdatedSystemApp(PackageSetting ps) {
18350        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18351    }
18352
18353    private int packageFlagsToInstallFlags(PackageSetting ps) {
18354        int installFlags = 0;
18355        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
18356            // This existing package was an external ASEC install when we have
18357            // the external flag without a UUID
18358            installFlags |= PackageManager.INSTALL_EXTERNAL;
18359        }
18360        if (ps.isForwardLocked()) {
18361            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
18362        }
18363        return installFlags;
18364    }
18365
18366    private String getVolumeUuidForPackage(PackageParser.Package pkg) {
18367        if (isExternal(pkg)) {
18368            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18369                return StorageManager.UUID_PRIMARY_PHYSICAL;
18370            } else {
18371                return pkg.volumeUuid;
18372            }
18373        } else {
18374            return StorageManager.UUID_PRIVATE_INTERNAL;
18375        }
18376    }
18377
18378    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18379        if (isExternal(pkg)) {
18380            if (TextUtils.isEmpty(pkg.volumeUuid)) {
18381                return mSettings.getExternalVersion();
18382            } else {
18383                return mSettings.findOrCreateVersion(pkg.volumeUuid);
18384            }
18385        } else {
18386            return mSettings.getInternalVersion();
18387        }
18388    }
18389
18390    private void deleteTempPackageFiles() {
18391        final FilenameFilter filter = new FilenameFilter() {
18392            public boolean accept(File dir, String name) {
18393                return name.startsWith("vmdl") && name.endsWith(".tmp");
18394            }
18395        };
18396        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
18397            file.delete();
18398        }
18399    }
18400
18401    @Override
18402    public void deletePackageAsUser(String packageName, int versionCode,
18403            IPackageDeleteObserver observer, int userId, int flags) {
18404        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18405                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18406    }
18407
18408    @Override
18409    public void deletePackageVersioned(VersionedPackage versionedPackage,
18410            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18411        final int callingUid = Binder.getCallingUid();
18412        mContext.enforceCallingOrSelfPermission(
18413                android.Manifest.permission.DELETE_PACKAGES, null);
18414        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
18415                android.Manifest.permission.ACCESS_INSTANT_APPS);
18416        Preconditions.checkNotNull(versionedPackage);
18417        Preconditions.checkNotNull(observer);
18418        Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(),
18419                PackageManager.VERSION_CODE_HIGHEST,
18420                Integer.MAX_VALUE, "versionCode must be >= -1");
18421
18422        final String packageName = versionedPackage.getPackageName();
18423        final int versionCode = versionedPackage.getVersionCode();
18424        final String internalPackageName;
18425        synchronized (mPackages) {
18426            // Normalize package name to handle renamed packages and static libs
18427            internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(),
18428                    versionedPackage.getVersionCode());
18429        }
18430
18431        final int uid = Binder.getCallingUid();
18432        if (!isOrphaned(internalPackageName)
18433                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18434            try {
18435                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18436                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18437                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18438                observer.onUserActionRequired(intent);
18439            } catch (RemoteException re) {
18440            }
18441            return;
18442        }
18443        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18444        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
18445        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18446            mContext.enforceCallingOrSelfPermission(
18447                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18448                    "deletePackage for user " + userId);
18449        }
18450
18451        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18452            try {
18453                observer.onPackageDeleted(packageName,
18454                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18455            } catch (RemoteException re) {
18456            }
18457            return;
18458        }
18459
18460        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18461            try {
18462                observer.onPackageDeleted(packageName,
18463                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18464            } catch (RemoteException re) {
18465            }
18466            return;
18467        }
18468
18469        if (DEBUG_REMOVE) {
18470            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18471                    + " deleteAllUsers: " + deleteAllUsers + " version="
18472                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18473                    ? "VERSION_CODE_HIGHEST" : versionCode));
18474        }
18475        // Queue up an async operation since the package deletion may take a little while.
18476        mHandler.post(new Runnable() {
18477            public void run() {
18478                mHandler.removeCallbacks(this);
18479                int returnCode;
18480                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18481                boolean doDeletePackage = true;
18482                if (ps != null) {
18483                    final boolean targetIsInstantApp =
18484                            ps.getInstantApp(UserHandle.getUserId(callingUid));
18485                    doDeletePackage = !targetIsInstantApp
18486                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
18487                }
18488                if (doDeletePackage) {
18489                    if (!deleteAllUsers) {
18490                        returnCode = deletePackageX(internalPackageName, versionCode,
18491                                userId, deleteFlags);
18492                    } else {
18493                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
18494                                internalPackageName, users);
18495                        // If nobody is blocking uninstall, proceed with delete for all users
18496                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18497                            returnCode = deletePackageX(internalPackageName, versionCode,
18498                                    userId, deleteFlags);
18499                        } else {
18500                            // Otherwise uninstall individually for users with blockUninstalls=false
18501                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18502                            for (int userId : users) {
18503                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
18504                                    returnCode = deletePackageX(internalPackageName, versionCode,
18505                                            userId, userFlags);
18506                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18507                                        Slog.w(TAG, "Package delete failed for user " + userId
18508                                                + ", returnCode " + returnCode);
18509                                    }
18510                                }
18511                            }
18512                            // The app has only been marked uninstalled for certain users.
18513                            // We still need to report that delete was blocked
18514                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18515                        }
18516                    }
18517                } else {
18518                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18519                }
18520                try {
18521                    observer.onPackageDeleted(packageName, returnCode, null);
18522                } catch (RemoteException e) {
18523                    Log.i(TAG, "Observer no longer exists.");
18524                } //end catch
18525            } //end run
18526        });
18527    }
18528
18529    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18530        if (pkg.staticSharedLibName != null) {
18531            return pkg.manifestPackageName;
18532        }
18533        return pkg.packageName;
18534    }
18535
18536    private String resolveInternalPackageNameLPr(String packageName, int versionCode) {
18537        // Handle renamed packages
18538        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18539        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18540
18541        // Is this a static library?
18542        SparseArray<SharedLibraryEntry> versionedLib =
18543                mStaticLibsByDeclaringPackage.get(packageName);
18544        if (versionedLib == null || versionedLib.size() <= 0) {
18545            return packageName;
18546        }
18547
18548        // Figure out which lib versions the caller can see
18549        SparseIntArray versionsCallerCanSee = null;
18550        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18551        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18552                && callingAppId != Process.ROOT_UID) {
18553            versionsCallerCanSee = new SparseIntArray();
18554            String libName = versionedLib.valueAt(0).info.getName();
18555            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18556            if (uidPackages != null) {
18557                for (String uidPackage : uidPackages) {
18558                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18559                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18560                    if (libIdx >= 0) {
18561                        final int libVersion = ps.usesStaticLibrariesVersions[libIdx];
18562                        versionsCallerCanSee.append(libVersion, libVersion);
18563                    }
18564                }
18565            }
18566        }
18567
18568        // Caller can see nothing - done
18569        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18570            return packageName;
18571        }
18572
18573        // Find the version the caller can see and the app version code
18574        SharedLibraryEntry highestVersion = null;
18575        final int versionCount = versionedLib.size();
18576        for (int i = 0; i < versionCount; i++) {
18577            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
18578            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18579                    libEntry.info.getVersion()) < 0) {
18580                continue;
18581            }
18582            final int libVersionCode = libEntry.info.getDeclaringPackage().getVersionCode();
18583            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18584                if (libVersionCode == versionCode) {
18585                    return libEntry.apk;
18586                }
18587            } else if (highestVersion == null) {
18588                highestVersion = libEntry;
18589            } else if (libVersionCode  > highestVersion.info
18590                    .getDeclaringPackage().getVersionCode()) {
18591                highestVersion = libEntry;
18592            }
18593        }
18594
18595        if (highestVersion != null) {
18596            return highestVersion.apk;
18597        }
18598
18599        return packageName;
18600    }
18601
18602    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18603        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18604              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18605            return true;
18606        }
18607        final int callingUserId = UserHandle.getUserId(callingUid);
18608        // If the caller installed the pkgName, then allow it to silently uninstall.
18609        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18610            return true;
18611        }
18612
18613        // Allow package verifier to silently uninstall.
18614        if (mRequiredVerifierPackage != null &&
18615                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18616            return true;
18617        }
18618
18619        // Allow package uninstaller to silently uninstall.
18620        if (mRequiredUninstallerPackage != null &&
18621                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18622            return true;
18623        }
18624
18625        // Allow storage manager to silently uninstall.
18626        if (mStorageManagerPackage != null &&
18627                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18628            return true;
18629        }
18630        return false;
18631    }
18632
18633    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18634        int[] result = EMPTY_INT_ARRAY;
18635        for (int userId : userIds) {
18636            if (getBlockUninstallForUser(packageName, userId)) {
18637                result = ArrayUtils.appendInt(result, userId);
18638            }
18639        }
18640        return result;
18641    }
18642
18643    @Override
18644    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18645        final int callingUid = Binder.getCallingUid();
18646        if (getInstantAppPackageName(callingUid) != null
18647                && !isCallerSameApp(packageName, callingUid)) {
18648            return false;
18649        }
18650        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18651    }
18652
18653    private boolean isPackageDeviceAdmin(String packageName, int userId) {
18654        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18655                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18656        try {
18657            if (dpm != null) {
18658                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18659                        /* callingUserOnly =*/ false);
18660                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18661                        : deviceOwnerComponentName.getPackageName();
18662                // Does the package contains the device owner?
18663                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18664                // this check is probably not needed, since DO should be registered as a device
18665                // admin on some user too. (Original bug for this: b/17657954)
18666                if (packageName.equals(deviceOwnerPackageName)) {
18667                    return true;
18668                }
18669                // Does it contain a device admin for any user?
18670                int[] users;
18671                if (userId == UserHandle.USER_ALL) {
18672                    users = sUserManager.getUserIds();
18673                } else {
18674                    users = new int[]{userId};
18675                }
18676                for (int i = 0; i < users.length; ++i) {
18677                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18678                        return true;
18679                    }
18680                }
18681            }
18682        } catch (RemoteException e) {
18683        }
18684        return false;
18685    }
18686
18687    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18688        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18689    }
18690
18691    /**
18692     *  This method is an internal method that could be get invoked either
18693     *  to delete an installed package or to clean up a failed installation.
18694     *  After deleting an installed package, a broadcast is sent to notify any
18695     *  listeners that the package has been removed. For cleaning up a failed
18696     *  installation, the broadcast is not necessary since the package's
18697     *  installation wouldn't have sent the initial broadcast either
18698     *  The key steps in deleting a package are
18699     *  deleting the package information in internal structures like mPackages,
18700     *  deleting the packages base directories through installd
18701     *  updating mSettings to reflect current status
18702     *  persisting settings for later use
18703     *  sending a broadcast if necessary
18704     */
18705    int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) {
18706        final PackageRemovedInfo info = new PackageRemovedInfo(this);
18707        final boolean res;
18708
18709        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18710                ? UserHandle.USER_ALL : userId;
18711
18712        if (isPackageDeviceAdmin(packageName, removeUser)) {
18713            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18714            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18715        }
18716
18717        PackageSetting uninstalledPs = null;
18718        PackageParser.Package pkg = null;
18719
18720        // for the uninstall-updates case and restricted profiles, remember the per-
18721        // user handle installed state
18722        int[] allUsers;
18723        synchronized (mPackages) {
18724            uninstalledPs = mSettings.mPackages.get(packageName);
18725            if (uninstalledPs == null) {
18726                Slog.w(TAG, "Not removing non-existent package " + packageName);
18727                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18728            }
18729
18730            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18731                    && uninstalledPs.versionCode != versionCode) {
18732                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18733                        + uninstalledPs.versionCode + " != " + versionCode);
18734                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18735            }
18736
18737            // Static shared libs can be declared by any package, so let us not
18738            // allow removing a package if it provides a lib others depend on.
18739            pkg = mPackages.get(packageName);
18740
18741            allUsers = sUserManager.getUserIds();
18742
18743            if (pkg != null && pkg.staticSharedLibName != null) {
18744                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
18745                        pkg.staticSharedLibVersion);
18746                if (libEntry != null) {
18747                    for (int currUserId : allUsers) {
18748                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18749                            continue;
18750                        }
18751                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18752                                libEntry.info, 0, currUserId);
18753                        if (!ArrayUtils.isEmpty(libClientPackages)) {
18754                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18755                                    + " hosting lib " + libEntry.info.getName() + " version "
18756                                    + libEntry.info.getVersion() + " used by " + libClientPackages
18757                                    + " for user " + currUserId);
18758                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18759                        }
18760                    }
18761                }
18762            }
18763
18764            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18765        }
18766
18767        final int freezeUser;
18768        if (isUpdatedSystemApp(uninstalledPs)
18769                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18770            // We're downgrading a system app, which will apply to all users, so
18771            // freeze them all during the downgrade
18772            freezeUser = UserHandle.USER_ALL;
18773        } else {
18774            freezeUser = removeUser;
18775        }
18776
18777        synchronized (mInstallLock) {
18778            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18779            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18780                    deleteFlags, "deletePackageX")) {
18781                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18782                        deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null);
18783            }
18784            synchronized (mPackages) {
18785                if (res) {
18786                    if (pkg != null) {
18787                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18788                    }
18789                    updateSequenceNumberLP(packageName, info.removedUsers);
18790                    updateInstantAppInstallerLocked(packageName);
18791                }
18792            }
18793        }
18794
18795        if (res) {
18796            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18797            info.sendPackageRemovedBroadcasts(killApp);
18798            info.sendSystemPackageUpdatedBroadcasts();
18799            info.sendSystemPackageAppearedBroadcasts();
18800        }
18801        // Force a gc here.
18802        Runtime.getRuntime().gc();
18803        // Delete the resources here after sending the broadcast to let
18804        // other processes clean up before deleting resources.
18805        if (info.args != null) {
18806            synchronized (mInstallLock) {
18807                info.args.doPostDeleteLI(true);
18808            }
18809        }
18810
18811        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18812    }
18813
18814    static class PackageRemovedInfo {
18815        final PackageSender packageSender;
18816        String removedPackage;
18817        String installerPackageName;
18818        int uid = -1;
18819        int removedAppId = -1;
18820        int[] origUsers;
18821        int[] removedUsers = null;
18822        int[] broadcastUsers = null;
18823        SparseArray<Integer> installReasons;
18824        boolean isRemovedPackageSystemUpdate = false;
18825        boolean isUpdate;
18826        boolean dataRemoved;
18827        boolean removedForAllUsers;
18828        boolean isStaticSharedLib;
18829        // Clean up resources deleted packages.
18830        InstallArgs args = null;
18831        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18832        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18833
18834        PackageRemovedInfo(PackageSender packageSender) {
18835            this.packageSender = packageSender;
18836        }
18837
18838        void sendPackageRemovedBroadcasts(boolean killApp) {
18839            sendPackageRemovedBroadcastInternal(killApp);
18840            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18841            for (int i = 0; i < childCount; i++) {
18842                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18843                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18844            }
18845        }
18846
18847        void sendSystemPackageUpdatedBroadcasts() {
18848            if (isRemovedPackageSystemUpdate) {
18849                sendSystemPackageUpdatedBroadcastsInternal();
18850                final int childCount = (removedChildPackages != null)
18851                        ? removedChildPackages.size() : 0;
18852                for (int i = 0; i < childCount; i++) {
18853                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18854                    if (childInfo.isRemovedPackageSystemUpdate) {
18855                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18856                    }
18857                }
18858            }
18859        }
18860
18861        void sendSystemPackageAppearedBroadcasts() {
18862            final int packageCount = (appearedChildPackages != null)
18863                    ? appearedChildPackages.size() : 0;
18864            for (int i = 0; i < packageCount; i++) {
18865                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18866                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18867                    true, UserHandle.getAppId(installedInfo.uid),
18868                    installedInfo.newUsers);
18869            }
18870        }
18871
18872        private void sendSystemPackageUpdatedBroadcastsInternal() {
18873            Bundle extras = new Bundle(2);
18874            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18875            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18876            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18877                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18878            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18879                removedPackage, extras, 0, null /*targetPackage*/, null, null);
18880            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18881                null, null, 0, removedPackage, null, null);
18882            if (installerPackageName != null) {
18883                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18884                        removedPackage, extras, 0 /*flags*/,
18885                        installerPackageName, null, null);
18886                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18887                        removedPackage, extras, 0 /*flags*/,
18888                        installerPackageName, null, null);
18889            }
18890        }
18891
18892        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18893            // Don't send static shared library removal broadcasts as these
18894            // libs are visible only the the apps that depend on them an one
18895            // cannot remove the library if it has a dependency.
18896            if (isStaticSharedLib) {
18897                return;
18898            }
18899            Bundle extras = new Bundle(2);
18900            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18901            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18902            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18903            if (isUpdate || isRemovedPackageSystemUpdate) {
18904                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18905            }
18906            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18907            if (removedPackage != null) {
18908                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18909                    removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers);
18910                if (installerPackageName != null) {
18911                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18912                            removedPackage, extras, 0 /*flags*/,
18913                            installerPackageName, null, broadcastUsers);
18914                }
18915                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18916                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18917                        removedPackage, extras,
18918                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18919                        null, null, broadcastUsers);
18920                }
18921            }
18922            if (removedAppId >= 0) {
18923                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras,
18924                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers);
18925            }
18926        }
18927
18928        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18929            removedUsers = userIds;
18930            if (removedUsers == null) {
18931                broadcastUsers = null;
18932                return;
18933            }
18934
18935            broadcastUsers = EMPTY_INT_ARRAY;
18936            for (int i = userIds.length - 1; i >= 0; --i) {
18937                final int userId = userIds[i];
18938                if (deletedPackageSetting.getInstantApp(userId)) {
18939                    continue;
18940                }
18941                broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18942            }
18943        }
18944    }
18945
18946    /*
18947     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18948     * flag is not set, the data directory is removed as well.
18949     * make sure this flag is set for partially installed apps. If not its meaningless to
18950     * delete a partially installed application.
18951     */
18952    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18953            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18954        String packageName = ps.name;
18955        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18956        // Retrieve object to delete permissions for shared user later on
18957        final PackageParser.Package deletedPkg;
18958        final PackageSetting deletedPs;
18959        // reader
18960        synchronized (mPackages) {
18961            deletedPkg = mPackages.get(packageName);
18962            deletedPs = mSettings.mPackages.get(packageName);
18963            if (outInfo != null) {
18964                outInfo.removedPackage = packageName;
18965                outInfo.installerPackageName = ps.installerPackageName;
18966                outInfo.isStaticSharedLib = deletedPkg != null
18967                        && deletedPkg.staticSharedLibName != null;
18968                outInfo.populateUsers(deletedPs == null ? null
18969                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18970            }
18971        }
18972
18973        removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0);
18974
18975        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18976            final PackageParser.Package resolvedPkg;
18977            if (deletedPkg != null) {
18978                resolvedPkg = deletedPkg;
18979            } else {
18980                // We don't have a parsed package when it lives on an ejected
18981                // adopted storage device, so fake something together
18982                resolvedPkg = new PackageParser.Package(ps.name);
18983                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18984            }
18985            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18986                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18987            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18988            if (outInfo != null) {
18989                outInfo.dataRemoved = true;
18990            }
18991            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18992        }
18993
18994        int removedAppId = -1;
18995
18996        // writer
18997        synchronized (mPackages) {
18998            boolean installedStateChanged = false;
18999            if (deletedPs != null) {
19000                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
19001                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
19002                    clearDefaultBrowserIfNeeded(packageName);
19003                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
19004                    removedAppId = mSettings.removePackageLPw(packageName);
19005                    if (outInfo != null) {
19006                        outInfo.removedAppId = removedAppId;
19007                    }
19008                    updatePermissionsLPw(deletedPs.name, null, 0);
19009                    if (deletedPs.sharedUser != null) {
19010                        // Remove permissions associated with package. Since runtime
19011                        // permissions are per user we have to kill the removed package
19012                        // or packages running under the shared user of the removed
19013                        // package if revoking the permissions requested only by the removed
19014                        // package is successful and this causes a change in gids.
19015                        for (int userId : UserManagerService.getInstance().getUserIds()) {
19016                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
19017                                    userId);
19018                            if (userIdToKill == UserHandle.USER_ALL
19019                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
19020                                // If gids changed for this user, kill all affected packages.
19021                                mHandler.post(new Runnable() {
19022                                    @Override
19023                                    public void run() {
19024                                        // This has to happen with no lock held.
19025                                        killApplication(deletedPs.name, deletedPs.appId,
19026                                                KILL_APP_REASON_GIDS_CHANGED);
19027                                    }
19028                                });
19029                                break;
19030                            }
19031                        }
19032                    }
19033                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
19034                }
19035                // make sure to preserve per-user disabled state if this removal was just
19036                // a downgrade of a system app to the factory package
19037                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
19038                    if (DEBUG_REMOVE) {
19039                        Slog.d(TAG, "Propagating install state across downgrade");
19040                    }
19041                    for (int userId : allUserHandles) {
19042                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19043                        if (DEBUG_REMOVE) {
19044                            Slog.d(TAG, "    user " + userId + " => " + installed);
19045                        }
19046                        if (installed != ps.getInstalled(userId)) {
19047                            installedStateChanged = true;
19048                        }
19049                        ps.setInstalled(installed, userId);
19050                    }
19051                }
19052            }
19053            // can downgrade to reader
19054            if (writeSettings) {
19055                // Save settings now
19056                mSettings.writeLPr();
19057            }
19058            if (installedStateChanged) {
19059                mSettings.writeKernelMappingLPr(ps);
19060            }
19061        }
19062        if (removedAppId != -1) {
19063            // A user ID was deleted here. Go through all users and remove it
19064            // from KeyStore.
19065            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
19066        }
19067    }
19068
19069    static boolean locationIsPrivileged(File path) {
19070        try {
19071            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
19072                    .getCanonicalPath();
19073            return path.getCanonicalPath().startsWith(privilegedAppDir);
19074        } catch (IOException e) {
19075            Slog.e(TAG, "Unable to access code path " + path);
19076        }
19077        return false;
19078    }
19079
19080    /*
19081     * Tries to delete system package.
19082     */
19083    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
19084            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
19085            boolean writeSettings) {
19086        if (deletedPs.parentPackageName != null) {
19087            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
19088            return false;
19089        }
19090
19091        final boolean applyUserRestrictions
19092                = (allUserHandles != null) && (outInfo.origUsers != null);
19093        final PackageSetting disabledPs;
19094        // Confirm if the system package has been updated
19095        // An updated system app can be deleted. This will also have to restore
19096        // the system pkg from system partition
19097        // reader
19098        synchronized (mPackages) {
19099            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
19100        }
19101
19102        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19103                + " disabledPs=" + disabledPs);
19104
19105        if (disabledPs == null) {
19106            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
19107            return false;
19108        } else if (DEBUG_REMOVE) {
19109            Slog.d(TAG, "Deleting system pkg from data partition");
19110        }
19111
19112        if (DEBUG_REMOVE) {
19113            if (applyUserRestrictions) {
19114                Slog.d(TAG, "Remembering install states:");
19115                for (int userId : allUserHandles) {
19116                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19117                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19118                }
19119            }
19120        }
19121
19122        // Delete the updated package
19123        outInfo.isRemovedPackageSystemUpdate = true;
19124        if (outInfo.removedChildPackages != null) {
19125            final int childCount = (deletedPs.childPackageNames != null)
19126                    ? deletedPs.childPackageNames.size() : 0;
19127            for (int i = 0; i < childCount; i++) {
19128                String childPackageName = deletedPs.childPackageNames.get(i);
19129                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19130                        .contains(childPackageName)) {
19131                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19132                            childPackageName);
19133                    if (childInfo != null) {
19134                        childInfo.isRemovedPackageSystemUpdate = true;
19135                    }
19136                }
19137            }
19138        }
19139
19140        if (disabledPs.versionCode < deletedPs.versionCode) {
19141            // Delete data for downgrades
19142            flags &= ~PackageManager.DELETE_KEEP_DATA;
19143        } else {
19144            // Preserve data by setting flag
19145            flags |= PackageManager.DELETE_KEEP_DATA;
19146        }
19147
19148        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19149                outInfo, writeSettings, disabledPs.pkg);
19150        if (!ret) {
19151            return false;
19152        }
19153
19154        // writer
19155        synchronized (mPackages) {
19156            // Reinstate the old system package
19157            enableSystemPackageLPw(disabledPs.pkg);
19158            // Remove any native libraries from the upgraded package.
19159            removeNativeBinariesLI(deletedPs);
19160        }
19161
19162        // Install the system package
19163        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19164        int parseFlags = mDefParseFlags
19165                | PackageParser.PARSE_MUST_BE_APK
19166                | PackageParser.PARSE_IS_SYSTEM
19167                | PackageParser.PARSE_IS_SYSTEM_DIR;
19168        if (locationIsPrivileged(disabledPs.codePath)) {
19169            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
19170        }
19171
19172        final PackageParser.Package newPkg;
19173        try {
19174            newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */,
19175                0 /* currentTime */, null);
19176        } catch (PackageManagerException e) {
19177            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19178                    + e.getMessage());
19179            return false;
19180        }
19181
19182        try {
19183            // update shared libraries for the newly re-installed system package
19184            updateSharedLibrariesLPr(newPkg, null);
19185        } catch (PackageManagerException e) {
19186            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19187        }
19188
19189        prepareAppDataAfterInstallLIF(newPkg);
19190
19191        // writer
19192        synchronized (mPackages) {
19193            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
19194
19195            // Propagate the permissions state as we do not want to drop on the floor
19196            // runtime permissions. The update permissions method below will take
19197            // care of removing obsolete permissions and grant install permissions.
19198            ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState());
19199            updatePermissionsLPw(newPkg.packageName, newPkg,
19200                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
19201
19202            if (applyUserRestrictions) {
19203                boolean installedStateChanged = false;
19204                if (DEBUG_REMOVE) {
19205                    Slog.d(TAG, "Propagating install state across reinstall");
19206                }
19207                for (int userId : allUserHandles) {
19208                    final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
19209                    if (DEBUG_REMOVE) {
19210                        Slog.d(TAG, "    user " + userId + " => " + installed);
19211                    }
19212                    if (installed != ps.getInstalled(userId)) {
19213                        installedStateChanged = true;
19214                    }
19215                    ps.setInstalled(installed, userId);
19216
19217                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19218                }
19219                // Regardless of writeSettings we need to ensure that this restriction
19220                // state propagation is persisted
19221                mSettings.writeAllUsersPackageRestrictionsLPr();
19222                if (installedStateChanged) {
19223                    mSettings.writeKernelMappingLPr(ps);
19224                }
19225            }
19226            // can downgrade to reader here
19227            if (writeSettings) {
19228                mSettings.writeLPr();
19229            }
19230        }
19231        return true;
19232    }
19233
19234    private boolean deleteInstalledPackageLIF(PackageSetting ps,
19235            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19236            PackageRemovedInfo outInfo, boolean writeSettings,
19237            PackageParser.Package replacingPackage) {
19238        synchronized (mPackages) {
19239            if (outInfo != null) {
19240                outInfo.uid = ps.appId;
19241            }
19242
19243            if (outInfo != null && outInfo.removedChildPackages != null) {
19244                final int childCount = (ps.childPackageNames != null)
19245                        ? ps.childPackageNames.size() : 0;
19246                for (int i = 0; i < childCount; i++) {
19247                    String childPackageName = ps.childPackageNames.get(i);
19248                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19249                    if (childPs == null) {
19250                        return false;
19251                    }
19252                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19253                            childPackageName);
19254                    if (childInfo != null) {
19255                        childInfo.uid = childPs.appId;
19256                    }
19257                }
19258            }
19259        }
19260
19261        // Delete package data from internal structures and also remove data if flag is set
19262        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19263
19264        // Delete the child packages data
19265        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19266        for (int i = 0; i < childCount; i++) {
19267            PackageSetting childPs;
19268            synchronized (mPackages) {
19269                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19270            }
19271            if (childPs != null) {
19272                PackageRemovedInfo childOutInfo = (outInfo != null
19273                        && outInfo.removedChildPackages != null)
19274                        ? outInfo.removedChildPackages.get(childPs.name) : null;
19275                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19276                        && (replacingPackage != null
19277                        && !replacingPackage.hasChildPackage(childPs.name))
19278                        ? flags & ~DELETE_KEEP_DATA : flags;
19279                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19280                        deleteFlags, writeSettings);
19281            }
19282        }
19283
19284        // Delete application code and resources only for parent packages
19285        if (ps.parentPackageName == null) {
19286            if (deleteCodeAndResources && (outInfo != null)) {
19287                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
19288                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19289                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19290            }
19291        }
19292
19293        return true;
19294    }
19295
19296    @Override
19297    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19298            int userId) {
19299        mContext.enforceCallingOrSelfPermission(
19300                android.Manifest.permission.DELETE_PACKAGES, null);
19301        synchronized (mPackages) {
19302            // Cannot block uninstall of static shared libs as they are
19303            // considered a part of the using app (emulating static linking).
19304            // Also static libs are installed always on internal storage.
19305            PackageParser.Package pkg = mPackages.get(packageName);
19306            if (pkg != null && pkg.staticSharedLibName != null) {
19307                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19308                        + " providing static shared library: " + pkg.staticSharedLibName);
19309                return false;
19310            }
19311            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19312            mSettings.writePackageRestrictionsLPr(userId);
19313        }
19314        return true;
19315    }
19316
19317    @Override
19318    public boolean getBlockUninstallForUser(String packageName, int userId) {
19319        synchronized (mPackages) {
19320            final PackageSetting ps = mSettings.mPackages.get(packageName);
19321            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19322                return true;
19323            }
19324            return mSettings.getBlockUninstallLPr(userId, packageName);
19325        }
19326    }
19327
19328    @Override
19329    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19330        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19331        synchronized (mPackages) {
19332            PackageSetting ps = mSettings.mPackages.get(packageName);
19333            if (ps == null) {
19334                Log.w(TAG, "Package doesn't exist: " + packageName);
19335                return false;
19336            }
19337            if (systemUserApp) {
19338                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19339            } else {
19340                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19341            }
19342            mSettings.writeLPr();
19343        }
19344        return true;
19345    }
19346
19347    /*
19348     * This method handles package deletion in general
19349     */
19350    private boolean deletePackageLIF(String packageName, UserHandle user,
19351            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19352            PackageRemovedInfo outInfo, boolean writeSettings,
19353            PackageParser.Package replacingPackage) {
19354        if (packageName == null) {
19355            Slog.w(TAG, "Attempt to delete null packageName.");
19356            return false;
19357        }
19358
19359        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19360
19361        PackageSetting ps;
19362        synchronized (mPackages) {
19363            ps = mSettings.mPackages.get(packageName);
19364            if (ps == null) {
19365                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19366                return false;
19367            }
19368
19369            if (ps.parentPackageName != null && (!isSystemApp(ps)
19370                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19371                if (DEBUG_REMOVE) {
19372                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19373                            + ((user == null) ? UserHandle.USER_ALL : user));
19374                }
19375                final int removedUserId = (user != null) ? user.getIdentifier()
19376                        : UserHandle.USER_ALL;
19377                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
19378                    return false;
19379                }
19380                markPackageUninstalledForUserLPw(ps, user);
19381                scheduleWritePackageRestrictionsLocked(user);
19382                return true;
19383            }
19384        }
19385
19386        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
19387                && user.getIdentifier() != UserHandle.USER_ALL)) {
19388            // The caller is asking that the package only be deleted for a single
19389            // user.  To do this, we just mark its uninstalled state and delete
19390            // its data. If this is a system app, we only allow this to happen if
19391            // they have set the special DELETE_SYSTEM_APP which requests different
19392            // semantics than normal for uninstalling system apps.
19393            markPackageUninstalledForUserLPw(ps, user);
19394
19395            if (!isSystemApp(ps)) {
19396                // Do not uninstall the APK if an app should be cached
19397                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19398                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19399                    // Other user still have this package installed, so all
19400                    // we need to do is clear this user's data and save that
19401                    // it is uninstalled.
19402                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19403                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19404                        return false;
19405                    }
19406                    scheduleWritePackageRestrictionsLocked(user);
19407                    return true;
19408                } else {
19409                    // We need to set it back to 'installed' so the uninstall
19410                    // broadcasts will be sent correctly.
19411                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19412                    ps.setInstalled(true, user.getIdentifier());
19413                    mSettings.writeKernelMappingLPr(ps);
19414                }
19415            } else {
19416                // This is a system app, so we assume that the
19417                // other users still have this package installed, so all
19418                // we need to do is clear this user's data and save that
19419                // it is uninstalled.
19420                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19421                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
19422                    return false;
19423                }
19424                scheduleWritePackageRestrictionsLocked(user);
19425                return true;
19426            }
19427        }
19428
19429        // If we are deleting a composite package for all users, keep track
19430        // of result for each child.
19431        if (ps.childPackageNames != null && outInfo != null) {
19432            synchronized (mPackages) {
19433                final int childCount = ps.childPackageNames.size();
19434                outInfo.removedChildPackages = new ArrayMap<>(childCount);
19435                for (int i = 0; i < childCount; i++) {
19436                    String childPackageName = ps.childPackageNames.get(i);
19437                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19438                    childInfo.removedPackage = childPackageName;
19439                    childInfo.installerPackageName = ps.installerPackageName;
19440                    outInfo.removedChildPackages.put(childPackageName, childInfo);
19441                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19442                    if (childPs != null) {
19443                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19444                    }
19445                }
19446            }
19447        }
19448
19449        boolean ret = false;
19450        if (isSystemApp(ps)) {
19451            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19452            // When an updated system application is deleted we delete the existing resources
19453            // as well and fall back to existing code in system partition
19454            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
19455        } else {
19456            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19457            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19458                    outInfo, writeSettings, replacingPackage);
19459        }
19460
19461        // Take a note whether we deleted the package for all users
19462        if (outInfo != null) {
19463            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19464            if (outInfo.removedChildPackages != null) {
19465                synchronized (mPackages) {
19466                    final int childCount = outInfo.removedChildPackages.size();
19467                    for (int i = 0; i < childCount; i++) {
19468                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19469                        if (childInfo != null) {
19470                            childInfo.removedForAllUsers = mPackages.get(
19471                                    childInfo.removedPackage) == null;
19472                        }
19473                    }
19474                }
19475            }
19476            // If we uninstalled an update to a system app there may be some
19477            // child packages that appeared as they are declared in the system
19478            // app but were not declared in the update.
19479            if (isSystemApp(ps)) {
19480                synchronized (mPackages) {
19481                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19482                    final int childCount = (updatedPs.childPackageNames != null)
19483                            ? updatedPs.childPackageNames.size() : 0;
19484                    for (int i = 0; i < childCount; i++) {
19485                        String childPackageName = updatedPs.childPackageNames.get(i);
19486                        if (outInfo.removedChildPackages == null
19487                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19488                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19489                            if (childPs == null) {
19490                                continue;
19491                            }
19492                            PackageInstalledInfo installRes = new PackageInstalledInfo();
19493                            installRes.name = childPackageName;
19494                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19495                            installRes.pkg = mPackages.get(childPackageName);
19496                            installRes.uid = childPs.pkg.applicationInfo.uid;
19497                            if (outInfo.appearedChildPackages == null) {
19498                                outInfo.appearedChildPackages = new ArrayMap<>();
19499                            }
19500                            outInfo.appearedChildPackages.put(childPackageName, installRes);
19501                        }
19502                    }
19503                }
19504            }
19505        }
19506
19507        return ret;
19508    }
19509
19510    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19511        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19512                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19513        for (int nextUserId : userIds) {
19514            if (DEBUG_REMOVE) {
19515                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19516            }
19517            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19518                    false /*installed*/,
19519                    true /*stopped*/,
19520                    true /*notLaunched*/,
19521                    false /*hidden*/,
19522                    false /*suspended*/,
19523                    false /*instantApp*/,
19524                    null /*lastDisableAppCaller*/,
19525                    null /*enabledComponents*/,
19526                    null /*disabledComponents*/,
19527                    ps.readUserState(nextUserId).domainVerificationStatus,
19528                    0, PackageManager.INSTALL_REASON_UNKNOWN);
19529        }
19530        mSettings.writeKernelMappingLPr(ps);
19531    }
19532
19533    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
19534            PackageRemovedInfo outInfo) {
19535        final PackageParser.Package pkg;
19536        synchronized (mPackages) {
19537            pkg = mPackages.get(ps.name);
19538        }
19539
19540        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19541                : new int[] {userId};
19542        for (int nextUserId : userIds) {
19543            if (DEBUG_REMOVE) {
19544                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19545                        + nextUserId);
19546            }
19547
19548            destroyAppDataLIF(pkg, userId,
19549                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19550            destroyAppProfilesLIF(pkg, userId);
19551            clearDefaultBrowserIfNeededForUser(ps.name, userId);
19552            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19553            schedulePackageCleaning(ps.name, nextUserId, false);
19554            synchronized (mPackages) {
19555                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
19556                    scheduleWritePackageRestrictionsLocked(nextUserId);
19557                }
19558                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19559            }
19560        }
19561
19562        if (outInfo != null) {
19563            outInfo.removedPackage = ps.name;
19564            outInfo.installerPackageName = ps.installerPackageName;
19565            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19566            outInfo.removedAppId = ps.appId;
19567            outInfo.removedUsers = userIds;
19568            outInfo.broadcastUsers = userIds;
19569        }
19570
19571        return true;
19572    }
19573
19574    private final class ClearStorageConnection implements ServiceConnection {
19575        IMediaContainerService mContainerService;
19576
19577        @Override
19578        public void onServiceConnected(ComponentName name, IBinder service) {
19579            synchronized (this) {
19580                mContainerService = IMediaContainerService.Stub
19581                        .asInterface(Binder.allowBlocking(service));
19582                notifyAll();
19583            }
19584        }
19585
19586        @Override
19587        public void onServiceDisconnected(ComponentName name) {
19588        }
19589    }
19590
19591    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
19592        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
19593
19594        final boolean mounted;
19595        if (Environment.isExternalStorageEmulated()) {
19596            mounted = true;
19597        } else {
19598            final String status = Environment.getExternalStorageState();
19599
19600            mounted = status.equals(Environment.MEDIA_MOUNTED)
19601                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
19602        }
19603
19604        if (!mounted) {
19605            return;
19606        }
19607
19608        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
19609        int[] users;
19610        if (userId == UserHandle.USER_ALL) {
19611            users = sUserManager.getUserIds();
19612        } else {
19613            users = new int[] { userId };
19614        }
19615        final ClearStorageConnection conn = new ClearStorageConnection();
19616        if (mContext.bindServiceAsUser(
19617                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
19618            try {
19619                for (int curUser : users) {
19620                    long timeout = SystemClock.uptimeMillis() + 5000;
19621                    synchronized (conn) {
19622                        long now;
19623                        while (conn.mContainerService == null &&
19624                                (now = SystemClock.uptimeMillis()) < timeout) {
19625                            try {
19626                                conn.wait(timeout - now);
19627                            } catch (InterruptedException e) {
19628                            }
19629                        }
19630                    }
19631                    if (conn.mContainerService == null) {
19632                        return;
19633                    }
19634
19635                    final UserEnvironment userEnv = new UserEnvironment(curUser);
19636                    clearDirectory(conn.mContainerService,
19637                            userEnv.buildExternalStorageAppCacheDirs(packageName));
19638                    if (allData) {
19639                        clearDirectory(conn.mContainerService,
19640                                userEnv.buildExternalStorageAppDataDirs(packageName));
19641                        clearDirectory(conn.mContainerService,
19642                                userEnv.buildExternalStorageAppMediaDirs(packageName));
19643                    }
19644                }
19645            } finally {
19646                mContext.unbindService(conn);
19647            }
19648        }
19649    }
19650
19651    @Override
19652    public void clearApplicationProfileData(String packageName) {
19653        enforceSystemOrRoot("Only the system can clear all profile data");
19654
19655        final PackageParser.Package pkg;
19656        synchronized (mPackages) {
19657            pkg = mPackages.get(packageName);
19658        }
19659
19660        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19661            synchronized (mInstallLock) {
19662                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19663            }
19664        }
19665    }
19666
19667    @Override
19668    public void clearApplicationUserData(final String packageName,
19669            final IPackageDataObserver observer, final int userId) {
19670        mContext.enforceCallingOrSelfPermission(
19671                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19672
19673        final int callingUid = Binder.getCallingUid();
19674        enforceCrossUserPermission(callingUid, userId,
19675                true /* requireFullPermission */, false /* checkShell */, "clear application data");
19676
19677        final PackageSetting ps = mSettings.getPackageLPr(packageName);
19678        if (ps != null && filterAppAccessLPr(ps, callingUid, userId)) {
19679            return;
19680        }
19681        if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19682            throw new SecurityException("Cannot clear data for a protected package: "
19683                    + packageName);
19684        }
19685        // Queue up an async operation since the package deletion may take a little while.
19686        mHandler.post(new Runnable() {
19687            public void run() {
19688                mHandler.removeCallbacks(this);
19689                final boolean succeeded;
19690                try (PackageFreezer freezer = freezePackage(packageName,
19691                        "clearApplicationUserData")) {
19692                    synchronized (mInstallLock) {
19693                        succeeded = clearApplicationUserDataLIF(packageName, userId);
19694                    }
19695                    clearExternalStorageDataSync(packageName, userId, true);
19696                    synchronized (mPackages) {
19697                        mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19698                                packageName, userId);
19699                    }
19700                }
19701                if (succeeded) {
19702                    // invoke DeviceStorageMonitor's update method to clear any notifications
19703                    DeviceStorageMonitorInternal dsm = LocalServices
19704                            .getService(DeviceStorageMonitorInternal.class);
19705                    if (dsm != null) {
19706                        dsm.checkMemory();
19707                    }
19708                }
19709                if(observer != null) {
19710                    try {
19711                        observer.onRemoveCompleted(packageName, succeeded);
19712                    } catch (RemoteException e) {
19713                        Log.i(TAG, "Observer no longer exists.");
19714                    }
19715                } //end if observer
19716            } //end run
19717        });
19718    }
19719
19720    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19721        if (packageName == null) {
19722            Slog.w(TAG, "Attempt to delete null packageName.");
19723            return false;
19724        }
19725
19726        // Try finding details about the requested package
19727        PackageParser.Package pkg;
19728        synchronized (mPackages) {
19729            pkg = mPackages.get(packageName);
19730            if (pkg == null) {
19731                final PackageSetting ps = mSettings.mPackages.get(packageName);
19732                if (ps != null) {
19733                    pkg = ps.pkg;
19734                }
19735            }
19736
19737            if (pkg == null) {
19738                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19739                return false;
19740            }
19741
19742            PackageSetting ps = (PackageSetting) pkg.mExtras;
19743            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19744        }
19745
19746        clearAppDataLIF(pkg, userId,
19747                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19748
19749        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19750        removeKeystoreDataIfNeeded(userId, appId);
19751
19752        UserManagerInternal umInternal = getUserManagerInternal();
19753        final int flags;
19754        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19755            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19756        } else if (umInternal.isUserRunning(userId)) {
19757            flags = StorageManager.FLAG_STORAGE_DE;
19758        } else {
19759            flags = 0;
19760        }
19761        prepareAppDataContentsLIF(pkg, userId, flags);
19762
19763        return true;
19764    }
19765
19766    /**
19767     * Reverts user permission state changes (permissions and flags) in
19768     * all packages for a given user.
19769     *
19770     * @param userId The device user for which to do a reset.
19771     */
19772    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19773        final int packageCount = mPackages.size();
19774        for (int i = 0; i < packageCount; i++) {
19775            PackageParser.Package pkg = mPackages.valueAt(i);
19776            PackageSetting ps = (PackageSetting) pkg.mExtras;
19777            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19778        }
19779    }
19780
19781    private void resetNetworkPolicies(int userId) {
19782        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19783    }
19784
19785    /**
19786     * Reverts user permission state changes (permissions and flags).
19787     *
19788     * @param ps The package for which to reset.
19789     * @param userId The device user for which to do a reset.
19790     */
19791    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19792            final PackageSetting ps, final int userId) {
19793        if (ps.pkg == null) {
19794            return;
19795        }
19796
19797        // These are flags that can change base on user actions.
19798        final int userSettableMask = FLAG_PERMISSION_USER_SET
19799                | FLAG_PERMISSION_USER_FIXED
19800                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19801                | FLAG_PERMISSION_REVIEW_REQUIRED;
19802
19803        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19804                | FLAG_PERMISSION_POLICY_FIXED;
19805
19806        boolean writeInstallPermissions = false;
19807        boolean writeRuntimePermissions = false;
19808
19809        final int permissionCount = ps.pkg.requestedPermissions.size();
19810        for (int i = 0; i < permissionCount; i++) {
19811            String permission = ps.pkg.requestedPermissions.get(i);
19812
19813            BasePermission bp = mSettings.mPermissions.get(permission);
19814            if (bp == null) {
19815                continue;
19816            }
19817
19818            // If shared user we just reset the state to which only this app contributed.
19819            if (ps.sharedUser != null) {
19820                boolean used = false;
19821                final int packageCount = ps.sharedUser.packages.size();
19822                for (int j = 0; j < packageCount; j++) {
19823                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19824                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19825                            && pkg.pkg.requestedPermissions.contains(permission)) {
19826                        used = true;
19827                        break;
19828                    }
19829                }
19830                if (used) {
19831                    continue;
19832                }
19833            }
19834
19835            PermissionsState permissionsState = ps.getPermissionsState();
19836
19837            final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId);
19838
19839            // Always clear the user settable flags.
19840            final boolean hasInstallState = permissionsState.getInstallPermissionState(
19841                    bp.name) != null;
19842            // If permission review is enabled and this is a legacy app, mark the
19843            // permission as requiring a review as this is the initial state.
19844            int flags = 0;
19845            if (mPermissionReviewRequired
19846                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19847                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19848            }
19849            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19850                if (hasInstallState) {
19851                    writeInstallPermissions = true;
19852                } else {
19853                    writeRuntimePermissions = true;
19854                }
19855            }
19856
19857            // Below is only runtime permission handling.
19858            if (!bp.isRuntime()) {
19859                continue;
19860            }
19861
19862            // Never clobber system or policy.
19863            if ((oldFlags & policyOrSystemFlags) != 0) {
19864                continue;
19865            }
19866
19867            // If this permission was granted by default, make sure it is.
19868            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19869                if (permissionsState.grantRuntimePermission(bp, userId)
19870                        != PERMISSION_OPERATION_FAILURE) {
19871                    writeRuntimePermissions = true;
19872                }
19873            // If permission review is enabled the permissions for a legacy apps
19874            // are represented as constantly granted runtime ones, so don't revoke.
19875            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19876                // Otherwise, reset the permission.
19877                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19878                switch (revokeResult) {
19879                    case PERMISSION_OPERATION_SUCCESS:
19880                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19881                        writeRuntimePermissions = true;
19882                        final int appId = ps.appId;
19883                        mHandler.post(new Runnable() {
19884                            @Override
19885                            public void run() {
19886                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19887                            }
19888                        });
19889                    } break;
19890                }
19891            }
19892        }
19893
19894        // Synchronously write as we are taking permissions away.
19895        if (writeRuntimePermissions) {
19896            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19897        }
19898
19899        // Synchronously write as we are taking permissions away.
19900        if (writeInstallPermissions) {
19901            mSettings.writeLPr();
19902        }
19903    }
19904
19905    /**
19906     * Remove entries from the keystore daemon. Will only remove it if the
19907     * {@code appId} is valid.
19908     */
19909    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19910        if (appId < 0) {
19911            return;
19912        }
19913
19914        final KeyStore keyStore = KeyStore.getInstance();
19915        if (keyStore != null) {
19916            if (userId == UserHandle.USER_ALL) {
19917                for (final int individual : sUserManager.getUserIds()) {
19918                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19919                }
19920            } else {
19921                keyStore.clearUid(UserHandle.getUid(userId, appId));
19922            }
19923        } else {
19924            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19925        }
19926    }
19927
19928    @Override
19929    public void deleteApplicationCacheFiles(final String packageName,
19930            final IPackageDataObserver observer) {
19931        final int userId = UserHandle.getCallingUserId();
19932        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19933    }
19934
19935    @Override
19936    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19937            final IPackageDataObserver observer) {
19938        final int callingUid = Binder.getCallingUid();
19939        mContext.enforceCallingOrSelfPermission(
19940                android.Manifest.permission.DELETE_CACHE_FILES, null);
19941        enforceCrossUserPermission(callingUid, userId,
19942                /* requireFullPermission= */ true, /* checkShell= */ false,
19943                "delete application cache files");
19944        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19945                android.Manifest.permission.ACCESS_INSTANT_APPS);
19946
19947        final PackageParser.Package pkg;
19948        synchronized (mPackages) {
19949            pkg = mPackages.get(packageName);
19950        }
19951
19952        // Queue up an async operation since the package deletion may take a little while.
19953        mHandler.post(new Runnable() {
19954            public void run() {
19955                final PackageSetting ps = (PackageSetting) pkg.mExtras;
19956                boolean doClearData = true;
19957                if (ps != null) {
19958                    final boolean targetIsInstantApp =
19959                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19960                    doClearData = !targetIsInstantApp
19961                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19962                }
19963                if (doClearData) {
19964                    synchronized (mInstallLock) {
19965                        final int flags = StorageManager.FLAG_STORAGE_DE
19966                                | StorageManager.FLAG_STORAGE_CE;
19967                        // We're only clearing cache files, so we don't care if the
19968                        // app is unfrozen and still able to run
19969                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19970                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19971                    }
19972                    clearExternalStorageDataSync(packageName, userId, false);
19973                }
19974                if (observer != null) {
19975                    try {
19976                        observer.onRemoveCompleted(packageName, true);
19977                    } catch (RemoteException e) {
19978                        Log.i(TAG, "Observer no longer exists.");
19979                    }
19980                }
19981            }
19982        });
19983    }
19984
19985    @Override
19986    public void getPackageSizeInfo(final String packageName, int userHandle,
19987            final IPackageStatsObserver observer) {
19988        throw new UnsupportedOperationException(
19989                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19990    }
19991
19992    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19993        final PackageSetting ps;
19994        synchronized (mPackages) {
19995            ps = mSettings.mPackages.get(packageName);
19996            if (ps == null) {
19997                Slog.w(TAG, "Failed to find settings for " + packageName);
19998                return false;
19999            }
20000        }
20001
20002        final String[] packageNames = { packageName };
20003        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20004        final String[] codePaths = { ps.codePathString };
20005
20006        try {
20007            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20008                    ps.appId, ceDataInodes, codePaths, stats);
20009
20010            // For now, ignore code size of packages on system partition
20011            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20012                stats.codeSize = 0;
20013            }
20014
20015            // External clients expect these to be tracked separately
20016            stats.dataSize -= stats.cacheSize;
20017
20018        } catch (InstallerException e) {
20019            Slog.w(TAG, String.valueOf(e));
20020            return false;
20021        }
20022
20023        return true;
20024    }
20025
20026    private int getUidTargetSdkVersionLockedLPr(int uid) {
20027        Object obj = mSettings.getUserIdLPr(uid);
20028        if (obj instanceof SharedUserSetting) {
20029            final SharedUserSetting sus = (SharedUserSetting) obj;
20030            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20031            final Iterator<PackageSetting> it = sus.packages.iterator();
20032            while (it.hasNext()) {
20033                final PackageSetting ps = it.next();
20034                if (ps.pkg != null) {
20035                    int v = ps.pkg.applicationInfo.targetSdkVersion;
20036                    if (v < vers) vers = v;
20037                }
20038            }
20039            return vers;
20040        } else if (obj instanceof PackageSetting) {
20041            final PackageSetting ps = (PackageSetting) obj;
20042            if (ps.pkg != null) {
20043                return ps.pkg.applicationInfo.targetSdkVersion;
20044            }
20045        }
20046        return Build.VERSION_CODES.CUR_DEVELOPMENT;
20047    }
20048
20049    @Override
20050    public void addPreferredActivity(IntentFilter filter, int match,
20051            ComponentName[] set, ComponentName activity, int userId) {
20052        addPreferredActivityInternal(filter, match, set, activity, true, userId,
20053                "Adding preferred");
20054    }
20055
20056    private void addPreferredActivityInternal(IntentFilter filter, int match,
20057            ComponentName[] set, ComponentName activity, boolean always, int userId,
20058            String opname) {
20059        // writer
20060        int callingUid = Binder.getCallingUid();
20061        enforceCrossUserPermission(callingUid, userId,
20062                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20063        if (filter.countActions() == 0) {
20064            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20065            return;
20066        }
20067        synchronized (mPackages) {
20068            if (mContext.checkCallingOrSelfPermission(
20069                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20070                    != PackageManager.PERMISSION_GRANTED) {
20071                if (getUidTargetSdkVersionLockedLPr(callingUid)
20072                        < Build.VERSION_CODES.FROYO) {
20073                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20074                            + callingUid);
20075                    return;
20076                }
20077                mContext.enforceCallingOrSelfPermission(
20078                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20079            }
20080
20081            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20082            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20083                    + userId + ":");
20084            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20085            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20086            scheduleWritePackageRestrictionsLocked(userId);
20087            postPreferredActivityChangedBroadcast(userId);
20088        }
20089    }
20090
20091    private void postPreferredActivityChangedBroadcast(int userId) {
20092        mHandler.post(() -> {
20093            final IActivityManager am = ActivityManager.getService();
20094            if (am == null) {
20095                return;
20096            }
20097
20098            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20099            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20100            try {
20101                am.broadcastIntent(null, intent, null, null,
20102                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
20103                        null, false, false, userId);
20104            } catch (RemoteException e) {
20105            }
20106        });
20107    }
20108
20109    @Override
20110    public void replacePreferredActivity(IntentFilter filter, int match,
20111            ComponentName[] set, ComponentName activity, int userId) {
20112        if (filter.countActions() != 1) {
20113            throw new IllegalArgumentException(
20114                    "replacePreferredActivity expects filter to have only 1 action.");
20115        }
20116        if (filter.countDataAuthorities() != 0
20117                || filter.countDataPaths() != 0
20118                || filter.countDataSchemes() > 1
20119                || filter.countDataTypes() != 0) {
20120            throw new IllegalArgumentException(
20121                    "replacePreferredActivity expects filter to have no data authorities, " +
20122                    "paths, or types; and at most one scheme.");
20123        }
20124
20125        final int callingUid = Binder.getCallingUid();
20126        enforceCrossUserPermission(callingUid, userId,
20127                true /* requireFullPermission */, false /* checkShell */,
20128                "replace preferred activity");
20129        synchronized (mPackages) {
20130            if (mContext.checkCallingOrSelfPermission(
20131                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20132                    != PackageManager.PERMISSION_GRANTED) {
20133                if (getUidTargetSdkVersionLockedLPr(callingUid)
20134                        < Build.VERSION_CODES.FROYO) {
20135                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20136                            + Binder.getCallingUid());
20137                    return;
20138                }
20139                mContext.enforceCallingOrSelfPermission(
20140                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20141            }
20142
20143            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20144            if (pir != null) {
20145                // Get all of the existing entries that exactly match this filter.
20146                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20147                if (existing != null && existing.size() == 1) {
20148                    PreferredActivity cur = existing.get(0);
20149                    if (DEBUG_PREFERRED) {
20150                        Slog.i(TAG, "Checking replace of preferred:");
20151                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20152                        if (!cur.mPref.mAlways) {
20153                            Slog.i(TAG, "  -- CUR; not mAlways!");
20154                        } else {
20155                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20156                            Slog.i(TAG, "  -- CUR: mSet="
20157                                    + Arrays.toString(cur.mPref.mSetComponents));
20158                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20159                            Slog.i(TAG, "  -- NEW: mMatch="
20160                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
20161                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20162                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20163                        }
20164                    }
20165                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20166                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20167                            && cur.mPref.sameSet(set)) {
20168                        // Setting the preferred activity to what it happens to be already
20169                        if (DEBUG_PREFERRED) {
20170                            Slog.i(TAG, "Replacing with same preferred activity "
20171                                    + cur.mPref.mShortComponent + " for user "
20172                                    + userId + ":");
20173                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20174                        }
20175                        return;
20176                    }
20177                }
20178
20179                if (existing != null) {
20180                    if (DEBUG_PREFERRED) {
20181                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
20182                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20183                    }
20184                    for (int i = 0; i < existing.size(); i++) {
20185                        PreferredActivity pa = existing.get(i);
20186                        if (DEBUG_PREFERRED) {
20187                            Slog.i(TAG, "Removing existing preferred activity "
20188                                    + pa.mPref.mComponent + ":");
20189                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20190                        }
20191                        pir.removeFilter(pa);
20192                    }
20193                }
20194            }
20195            addPreferredActivityInternal(filter, match, set, activity, true, userId,
20196                    "Replacing preferred");
20197        }
20198    }
20199
20200    @Override
20201    public void clearPackagePreferredActivities(String packageName) {
20202        final int callingUid = Binder.getCallingUid();
20203        if (getInstantAppPackageName(callingUid) != null) {
20204            return;
20205        }
20206        // writer
20207        synchronized (mPackages) {
20208            PackageParser.Package pkg = mPackages.get(packageName);
20209            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
20210                if (mContext.checkCallingOrSelfPermission(
20211                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20212                        != PackageManager.PERMISSION_GRANTED) {
20213                    if (getUidTargetSdkVersionLockedLPr(callingUid)
20214                            < Build.VERSION_CODES.FROYO) {
20215                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20216                                + callingUid);
20217                        return;
20218                    }
20219                    mContext.enforceCallingOrSelfPermission(
20220                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20221                }
20222            }
20223            final PackageSetting ps = mSettings.getPackageLPr(packageName);
20224            if (ps != null
20225                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20226                return;
20227            }
20228            int user = UserHandle.getCallingUserId();
20229            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
20230                scheduleWritePackageRestrictionsLocked(user);
20231            }
20232        }
20233    }
20234
20235    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20236    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
20237        ArrayList<PreferredActivity> removed = null;
20238        boolean changed = false;
20239        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20240            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20241            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20242            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20243                continue;
20244            }
20245            Iterator<PreferredActivity> it = pir.filterIterator();
20246            while (it.hasNext()) {
20247                PreferredActivity pa = it.next();
20248                // Mark entry for removal only if it matches the package name
20249                // and the entry is of type "always".
20250                if (packageName == null ||
20251                        (pa.mPref.mComponent.getPackageName().equals(packageName)
20252                                && pa.mPref.mAlways)) {
20253                    if (removed == null) {
20254                        removed = new ArrayList<PreferredActivity>();
20255                    }
20256                    removed.add(pa);
20257                }
20258            }
20259            if (removed != null) {
20260                for (int j=0; j<removed.size(); j++) {
20261                    PreferredActivity pa = removed.get(j);
20262                    pir.removeFilter(pa);
20263                }
20264                changed = true;
20265            }
20266        }
20267        if (changed) {
20268            postPreferredActivityChangedBroadcast(userId);
20269        }
20270        return changed;
20271    }
20272
20273    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20274    private void clearIntentFilterVerificationsLPw(int userId) {
20275        final int packageCount = mPackages.size();
20276        for (int i = 0; i < packageCount; i++) {
20277            PackageParser.Package pkg = mPackages.valueAt(i);
20278            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20279        }
20280    }
20281
20282    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20283    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20284        if (userId == UserHandle.USER_ALL) {
20285            if (mSettings.removeIntentFilterVerificationLPw(packageName,
20286                    sUserManager.getUserIds())) {
20287                for (int oneUserId : sUserManager.getUserIds()) {
20288                    scheduleWritePackageRestrictionsLocked(oneUserId);
20289                }
20290            }
20291        } else {
20292            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20293                scheduleWritePackageRestrictionsLocked(userId);
20294            }
20295        }
20296    }
20297
20298    /** Clears state for all users, and touches intent filter verification policy */
20299    void clearDefaultBrowserIfNeeded(String packageName) {
20300        for (int oneUserId : sUserManager.getUserIds()) {
20301            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20302        }
20303    }
20304
20305    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20306        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20307        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20308            if (packageName.equals(defaultBrowserPackageName)) {
20309                setDefaultBrowserPackageName(null, userId);
20310            }
20311        }
20312    }
20313
20314    @Override
20315    public void resetApplicationPreferences(int userId) {
20316        mContext.enforceCallingOrSelfPermission(
20317                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20318        final long identity = Binder.clearCallingIdentity();
20319        // writer
20320        try {
20321            synchronized (mPackages) {
20322                clearPackagePreferredActivitiesLPw(null, userId);
20323                mSettings.applyDefaultPreferredAppsLPw(this, userId);
20324                // TODO: We have to reset the default SMS and Phone. This requires
20325                // significant refactoring to keep all default apps in the package
20326                // manager (cleaner but more work) or have the services provide
20327                // callbacks to the package manager to request a default app reset.
20328                applyFactoryDefaultBrowserLPw(userId);
20329                clearIntentFilterVerificationsLPw(userId);
20330                primeDomainVerificationsLPw(userId);
20331                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20332                scheduleWritePackageRestrictionsLocked(userId);
20333            }
20334            resetNetworkPolicies(userId);
20335        } finally {
20336            Binder.restoreCallingIdentity(identity);
20337        }
20338    }
20339
20340    @Override
20341    public int getPreferredActivities(List<IntentFilter> outFilters,
20342            List<ComponentName> outActivities, String packageName) {
20343        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20344            return 0;
20345        }
20346        int num = 0;
20347        final int userId = UserHandle.getCallingUserId();
20348        // reader
20349        synchronized (mPackages) {
20350            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20351            if (pir != null) {
20352                final Iterator<PreferredActivity> it = pir.filterIterator();
20353                while (it.hasNext()) {
20354                    final PreferredActivity pa = it.next();
20355                    if (packageName == null
20356                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
20357                                    && pa.mPref.mAlways)) {
20358                        if (outFilters != null) {
20359                            outFilters.add(new IntentFilter(pa));
20360                        }
20361                        if (outActivities != null) {
20362                            outActivities.add(pa.mPref.mComponent);
20363                        }
20364                    }
20365                }
20366            }
20367        }
20368
20369        return num;
20370    }
20371
20372    @Override
20373    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20374            int userId) {
20375        int callingUid = Binder.getCallingUid();
20376        if (callingUid != Process.SYSTEM_UID) {
20377            throw new SecurityException(
20378                    "addPersistentPreferredActivity can only be run by the system");
20379        }
20380        if (filter.countActions() == 0) {
20381            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20382            return;
20383        }
20384        synchronized (mPackages) {
20385            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
20386                    ":");
20387            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20388            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20389                    new PersistentPreferredActivity(filter, activity));
20390            scheduleWritePackageRestrictionsLocked(userId);
20391            postPreferredActivityChangedBroadcast(userId);
20392        }
20393    }
20394
20395    @Override
20396    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20397        int callingUid = Binder.getCallingUid();
20398        if (callingUid != Process.SYSTEM_UID) {
20399            throw new SecurityException(
20400                    "clearPackagePersistentPreferredActivities can only be run by the system");
20401        }
20402        ArrayList<PersistentPreferredActivity> removed = null;
20403        boolean changed = false;
20404        synchronized (mPackages) {
20405            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20406                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20407                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20408                        .valueAt(i);
20409                if (userId != thisUserId) {
20410                    continue;
20411                }
20412                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20413                while (it.hasNext()) {
20414                    PersistentPreferredActivity ppa = it.next();
20415                    // Mark entry for removal only if it matches the package name.
20416                    if (ppa.mComponent.getPackageName().equals(packageName)) {
20417                        if (removed == null) {
20418                            removed = new ArrayList<PersistentPreferredActivity>();
20419                        }
20420                        removed.add(ppa);
20421                    }
20422                }
20423                if (removed != null) {
20424                    for (int j=0; j<removed.size(); j++) {
20425                        PersistentPreferredActivity ppa = removed.get(j);
20426                        ppir.removeFilter(ppa);
20427                    }
20428                    changed = true;
20429                }
20430            }
20431
20432            if (changed) {
20433                scheduleWritePackageRestrictionsLocked(userId);
20434                postPreferredActivityChangedBroadcast(userId);
20435            }
20436        }
20437    }
20438
20439    /**
20440     * Common machinery for picking apart a restored XML blob and passing
20441     * it to a caller-supplied functor to be applied to the running system.
20442     */
20443    private void restoreFromXml(XmlPullParser parser, int userId,
20444            String expectedStartTag, BlobXmlRestorer functor)
20445            throws IOException, XmlPullParserException {
20446        int type;
20447        while ((type = parser.next()) != XmlPullParser.START_TAG
20448                && type != XmlPullParser.END_DOCUMENT) {
20449        }
20450        if (type != XmlPullParser.START_TAG) {
20451            // oops didn't find a start tag?!
20452            if (DEBUG_BACKUP) {
20453                Slog.e(TAG, "Didn't find start tag during restore");
20454            }
20455            return;
20456        }
20457Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
20458        // this is supposed to be TAG_PREFERRED_BACKUP
20459        if (!expectedStartTag.equals(parser.getName())) {
20460            if (DEBUG_BACKUP) {
20461                Slog.e(TAG, "Found unexpected tag " + parser.getName());
20462            }
20463            return;
20464        }
20465
20466        // skip interfering stuff, then we're aligned with the backing implementation
20467        while ((type = parser.next()) == XmlPullParser.TEXT) { }
20468Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
20469        functor.apply(parser, userId);
20470    }
20471
20472    private interface BlobXmlRestorer {
20473        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20474    }
20475
20476    /**
20477     * Non-Binder method, support for the backup/restore mechanism: write the
20478     * full set of preferred activities in its canonical XML format.  Returns the
20479     * XML output as a byte array, or null if there is none.
20480     */
20481    @Override
20482    public byte[] getPreferredActivityBackup(int userId) {
20483        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20484            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20485        }
20486
20487        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20488        try {
20489            final XmlSerializer serializer = new FastXmlSerializer();
20490            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20491            serializer.startDocument(null, true);
20492            serializer.startTag(null, TAG_PREFERRED_BACKUP);
20493
20494            synchronized (mPackages) {
20495                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20496            }
20497
20498            serializer.endTag(null, TAG_PREFERRED_BACKUP);
20499            serializer.endDocument();
20500            serializer.flush();
20501        } catch (Exception e) {
20502            if (DEBUG_BACKUP) {
20503                Slog.e(TAG, "Unable to write preferred activities for backup", e);
20504            }
20505            return null;
20506        }
20507
20508        return dataStream.toByteArray();
20509    }
20510
20511    @Override
20512    public void restorePreferredActivities(byte[] backup, int userId) {
20513        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20514            throw new SecurityException("Only the system may call restorePreferredActivities()");
20515        }
20516
20517        try {
20518            final XmlPullParser parser = Xml.newPullParser();
20519            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20520            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20521                    new BlobXmlRestorer() {
20522                        @Override
20523                        public void apply(XmlPullParser parser, int userId)
20524                                throws XmlPullParserException, IOException {
20525                            synchronized (mPackages) {
20526                                mSettings.readPreferredActivitiesLPw(parser, userId);
20527                            }
20528                        }
20529                    } );
20530        } catch (Exception e) {
20531            if (DEBUG_BACKUP) {
20532                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20533            }
20534        }
20535    }
20536
20537    /**
20538     * Non-Binder method, support for the backup/restore mechanism: write the
20539     * default browser (etc) settings in its canonical XML format.  Returns the default
20540     * browser XML representation as a byte array, or null if there is none.
20541     */
20542    @Override
20543    public byte[] getDefaultAppsBackup(int userId) {
20544        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20545            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20546        }
20547
20548        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20549        try {
20550            final XmlSerializer serializer = new FastXmlSerializer();
20551            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20552            serializer.startDocument(null, true);
20553            serializer.startTag(null, TAG_DEFAULT_APPS);
20554
20555            synchronized (mPackages) {
20556                mSettings.writeDefaultAppsLPr(serializer, userId);
20557            }
20558
20559            serializer.endTag(null, TAG_DEFAULT_APPS);
20560            serializer.endDocument();
20561            serializer.flush();
20562        } catch (Exception e) {
20563            if (DEBUG_BACKUP) {
20564                Slog.e(TAG, "Unable to write default apps for backup", e);
20565            }
20566            return null;
20567        }
20568
20569        return dataStream.toByteArray();
20570    }
20571
20572    @Override
20573    public void restoreDefaultApps(byte[] backup, int userId) {
20574        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20575            throw new SecurityException("Only the system may call restoreDefaultApps()");
20576        }
20577
20578        try {
20579            final XmlPullParser parser = Xml.newPullParser();
20580            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20581            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20582                    new BlobXmlRestorer() {
20583                        @Override
20584                        public void apply(XmlPullParser parser, int userId)
20585                                throws XmlPullParserException, IOException {
20586                            synchronized (mPackages) {
20587                                mSettings.readDefaultAppsLPw(parser, userId);
20588                            }
20589                        }
20590                    } );
20591        } catch (Exception e) {
20592            if (DEBUG_BACKUP) {
20593                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20594            }
20595        }
20596    }
20597
20598    @Override
20599    public byte[] getIntentFilterVerificationBackup(int userId) {
20600        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20601            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20602        }
20603
20604        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20605        try {
20606            final XmlSerializer serializer = new FastXmlSerializer();
20607            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20608            serializer.startDocument(null, true);
20609            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20610
20611            synchronized (mPackages) {
20612                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20613            }
20614
20615            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20616            serializer.endDocument();
20617            serializer.flush();
20618        } catch (Exception e) {
20619            if (DEBUG_BACKUP) {
20620                Slog.e(TAG, "Unable to write default apps for backup", e);
20621            }
20622            return null;
20623        }
20624
20625        return dataStream.toByteArray();
20626    }
20627
20628    @Override
20629    public void restoreIntentFilterVerification(byte[] backup, int userId) {
20630        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20631            throw new SecurityException("Only the system may call restorePreferredActivities()");
20632        }
20633
20634        try {
20635            final XmlPullParser parser = Xml.newPullParser();
20636            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20637            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20638                    new BlobXmlRestorer() {
20639                        @Override
20640                        public void apply(XmlPullParser parser, int userId)
20641                                throws XmlPullParserException, IOException {
20642                            synchronized (mPackages) {
20643                                mSettings.readAllDomainVerificationsLPr(parser, userId);
20644                                mSettings.writeLPr();
20645                            }
20646                        }
20647                    } );
20648        } catch (Exception e) {
20649            if (DEBUG_BACKUP) {
20650                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20651            }
20652        }
20653    }
20654
20655    @Override
20656    public byte[] getPermissionGrantBackup(int userId) {
20657        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20658            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
20659        }
20660
20661        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20662        try {
20663            final XmlSerializer serializer = new FastXmlSerializer();
20664            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20665            serializer.startDocument(null, true);
20666            serializer.startTag(null, TAG_PERMISSION_BACKUP);
20667
20668            synchronized (mPackages) {
20669                serializeRuntimePermissionGrantsLPr(serializer, userId);
20670            }
20671
20672            serializer.endTag(null, TAG_PERMISSION_BACKUP);
20673            serializer.endDocument();
20674            serializer.flush();
20675        } catch (Exception e) {
20676            if (DEBUG_BACKUP) {
20677                Slog.e(TAG, "Unable to write default apps for backup", e);
20678            }
20679            return null;
20680        }
20681
20682        return dataStream.toByteArray();
20683    }
20684
20685    @Override
20686    public void restorePermissionGrants(byte[] backup, int userId) {
20687        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20688            throw new SecurityException("Only the system may call restorePermissionGrants()");
20689        }
20690
20691        try {
20692            final XmlPullParser parser = Xml.newPullParser();
20693            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20694            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20695                    new BlobXmlRestorer() {
20696                        @Override
20697                        public void apply(XmlPullParser parser, int userId)
20698                                throws XmlPullParserException, IOException {
20699                            synchronized (mPackages) {
20700                                processRestoredPermissionGrantsLPr(parser, userId);
20701                            }
20702                        }
20703                    } );
20704        } catch (Exception e) {
20705            if (DEBUG_BACKUP) {
20706                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20707            }
20708        }
20709    }
20710
20711    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20712            throws IOException {
20713        serializer.startTag(null, TAG_ALL_GRANTS);
20714
20715        final int N = mSettings.mPackages.size();
20716        for (int i = 0; i < N; i++) {
20717            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20718            boolean pkgGrantsKnown = false;
20719
20720            PermissionsState packagePerms = ps.getPermissionsState();
20721
20722            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20723                final int grantFlags = state.getFlags();
20724                // only look at grants that are not system/policy fixed
20725                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20726                    final boolean isGranted = state.isGranted();
20727                    // And only back up the user-twiddled state bits
20728                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20729                        final String packageName = mSettings.mPackages.keyAt(i);
20730                        if (!pkgGrantsKnown) {
20731                            serializer.startTag(null, TAG_GRANT);
20732                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20733                            pkgGrantsKnown = true;
20734                        }
20735
20736                        final boolean userSet =
20737                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20738                        final boolean userFixed =
20739                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20740                        final boolean revoke =
20741                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20742
20743                        serializer.startTag(null, TAG_PERMISSION);
20744                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20745                        if (isGranted) {
20746                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20747                        }
20748                        if (userSet) {
20749                            serializer.attribute(null, ATTR_USER_SET, "true");
20750                        }
20751                        if (userFixed) {
20752                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20753                        }
20754                        if (revoke) {
20755                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20756                        }
20757                        serializer.endTag(null, TAG_PERMISSION);
20758                    }
20759                }
20760            }
20761
20762            if (pkgGrantsKnown) {
20763                serializer.endTag(null, TAG_GRANT);
20764            }
20765        }
20766
20767        serializer.endTag(null, TAG_ALL_GRANTS);
20768    }
20769
20770    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20771            throws XmlPullParserException, IOException {
20772        String pkgName = null;
20773        int outerDepth = parser.getDepth();
20774        int type;
20775        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20776                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20777            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20778                continue;
20779            }
20780
20781            final String tagName = parser.getName();
20782            if (tagName.equals(TAG_GRANT)) {
20783                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20784                if (DEBUG_BACKUP) {
20785                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20786                }
20787            } else if (tagName.equals(TAG_PERMISSION)) {
20788
20789                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20790                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20791
20792                int newFlagSet = 0;
20793                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20794                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20795                }
20796                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20797                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20798                }
20799                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20800                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20801                }
20802                if (DEBUG_BACKUP) {
20803                    Slog.v(TAG, "  + Restoring grant: pkg=" + pkgName + " perm=" + permName
20804                            + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet));
20805                }
20806                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20807                if (ps != null) {
20808                    // Already installed so we apply the grant immediately
20809                    if (DEBUG_BACKUP) {
20810                        Slog.v(TAG, "        + already installed; applying");
20811                    }
20812                    PermissionsState perms = ps.getPermissionsState();
20813                    BasePermission bp = mSettings.mPermissions.get(permName);
20814                    if (bp != null) {
20815                        if (isGranted) {
20816                            perms.grantRuntimePermission(bp, userId);
20817                        }
20818                        if (newFlagSet != 0) {
20819                            perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20820                        }
20821                    }
20822                } else {
20823                    // Need to wait for post-restore install to apply the grant
20824                    if (DEBUG_BACKUP) {
20825                        Slog.v(TAG, "        - not yet installed; saving for later");
20826                    }
20827                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20828                            isGranted, newFlagSet, userId);
20829                }
20830            } else {
20831                PackageManagerService.reportSettingsProblem(Log.WARN,
20832                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20833                XmlUtils.skipCurrentTag(parser);
20834            }
20835        }
20836
20837        scheduleWriteSettingsLocked();
20838        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20839    }
20840
20841    @Override
20842    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20843            int sourceUserId, int targetUserId, int flags) {
20844        mContext.enforceCallingOrSelfPermission(
20845                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20846        int callingUid = Binder.getCallingUid();
20847        enforceOwnerRights(ownerPackage, callingUid);
20848        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20849        if (intentFilter.countActions() == 0) {
20850            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20851            return;
20852        }
20853        synchronized (mPackages) {
20854            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20855                    ownerPackage, targetUserId, flags);
20856            CrossProfileIntentResolver resolver =
20857                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20858            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20859            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20860            if (existing != null) {
20861                int size = existing.size();
20862                for (int i = 0; i < size; i++) {
20863                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20864                        return;
20865                    }
20866                }
20867            }
20868            resolver.addFilter(newFilter);
20869            scheduleWritePackageRestrictionsLocked(sourceUserId);
20870        }
20871    }
20872
20873    @Override
20874    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20875        mContext.enforceCallingOrSelfPermission(
20876                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20877        final int callingUid = Binder.getCallingUid();
20878        enforceOwnerRights(ownerPackage, callingUid);
20879        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20880        synchronized (mPackages) {
20881            CrossProfileIntentResolver resolver =
20882                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20883            ArraySet<CrossProfileIntentFilter> set =
20884                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20885            for (CrossProfileIntentFilter filter : set) {
20886                if (filter.getOwnerPackage().equals(ownerPackage)) {
20887                    resolver.removeFilter(filter);
20888                }
20889            }
20890            scheduleWritePackageRestrictionsLocked(sourceUserId);
20891        }
20892    }
20893
20894    // Enforcing that callingUid is owning pkg on userId
20895    private void enforceOwnerRights(String pkg, int callingUid) {
20896        // The system owns everything.
20897        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20898            return;
20899        }
20900        final int callingUserId = UserHandle.getUserId(callingUid);
20901        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20902        if (pi == null) {
20903            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20904                    + callingUserId);
20905        }
20906        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20907            throw new SecurityException("Calling uid " + callingUid
20908                    + " does not own package " + pkg);
20909        }
20910    }
20911
20912    @Override
20913    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20914        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20915            return null;
20916        }
20917        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20918    }
20919
20920    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20921        UserManagerService ums = UserManagerService.getInstance();
20922        if (ums != null) {
20923            final UserInfo parent = ums.getProfileParent(userId);
20924            final int launcherUid = (parent != null) ? parent.id : userId;
20925            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20926            if (launcherComponent != null) {
20927                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20928                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20929                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20930                        .setPackage(launcherComponent.getPackageName());
20931                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20932            }
20933        }
20934    }
20935
20936    /**
20937     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20938     * then reports the most likely home activity or null if there are more than one.
20939     */
20940    private ComponentName getDefaultHomeActivity(int userId) {
20941        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20942        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20943        if (cn != null) {
20944            return cn;
20945        }
20946
20947        // Find the launcher with the highest priority and return that component if there are no
20948        // other home activity with the same priority.
20949        int lastPriority = Integer.MIN_VALUE;
20950        ComponentName lastComponent = null;
20951        final int size = allHomeCandidates.size();
20952        for (int i = 0; i < size; i++) {
20953            final ResolveInfo ri = allHomeCandidates.get(i);
20954            if (ri.priority > lastPriority) {
20955                lastComponent = ri.activityInfo.getComponentName();
20956                lastPriority = ri.priority;
20957            } else if (ri.priority == lastPriority) {
20958                // Two components found with same priority.
20959                lastComponent = null;
20960            }
20961        }
20962        return lastComponent;
20963    }
20964
20965    private Intent getHomeIntent() {
20966        Intent intent = new Intent(Intent.ACTION_MAIN);
20967        intent.addCategory(Intent.CATEGORY_HOME);
20968        intent.addCategory(Intent.CATEGORY_DEFAULT);
20969        return intent;
20970    }
20971
20972    private IntentFilter getHomeFilter() {
20973        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20974        filter.addCategory(Intent.CATEGORY_HOME);
20975        filter.addCategory(Intent.CATEGORY_DEFAULT);
20976        return filter;
20977    }
20978
20979    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20980            int userId) {
20981        Intent intent  = getHomeIntent();
20982        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20983                PackageManager.GET_META_DATA, userId);
20984        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20985                true, false, false, userId);
20986
20987        allHomeCandidates.clear();
20988        if (list != null) {
20989            for (ResolveInfo ri : list) {
20990                allHomeCandidates.add(ri);
20991            }
20992        }
20993        return (preferred == null || preferred.activityInfo == null)
20994                ? null
20995                : new ComponentName(preferred.activityInfo.packageName,
20996                        preferred.activityInfo.name);
20997    }
20998
20999    @Override
21000    public void setHomeActivity(ComponentName comp, int userId) {
21001        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21002            return;
21003        }
21004        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21005        getHomeActivitiesAsUser(homeActivities, userId);
21006
21007        boolean found = false;
21008
21009        final int size = homeActivities.size();
21010        final ComponentName[] set = new ComponentName[size];
21011        for (int i = 0; i < size; i++) {
21012            final ResolveInfo candidate = homeActivities.get(i);
21013            final ActivityInfo info = candidate.activityInfo;
21014            final ComponentName activityName = new ComponentName(info.packageName, info.name);
21015            set[i] = activityName;
21016            if (!found && activityName.equals(comp)) {
21017                found = true;
21018            }
21019        }
21020        if (!found) {
21021            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21022                    + userId);
21023        }
21024        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21025                set, comp, userId);
21026    }
21027
21028    private @Nullable String getSetupWizardPackageName() {
21029        final Intent intent = new Intent(Intent.ACTION_MAIN);
21030        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21031
21032        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21033                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21034                        | MATCH_DISABLED_COMPONENTS,
21035                UserHandle.myUserId());
21036        if (matches.size() == 1) {
21037            return matches.get(0).getComponentInfo().packageName;
21038        } else {
21039            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21040                    + ": matches=" + matches);
21041            return null;
21042        }
21043    }
21044
21045    private @Nullable String getStorageManagerPackageName() {
21046        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21047
21048        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21049                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21050                        | MATCH_DISABLED_COMPONENTS,
21051                UserHandle.myUserId());
21052        if (matches.size() == 1) {
21053            return matches.get(0).getComponentInfo().packageName;
21054        } else {
21055            Slog.e(TAG, "There should probably be exactly one storage manager; found "
21056                    + matches.size() + ": matches=" + matches);
21057            return null;
21058        }
21059    }
21060
21061    @Override
21062    public void setApplicationEnabledSetting(String appPackageName,
21063            int newState, int flags, int userId, String callingPackage) {
21064        if (!sUserManager.exists(userId)) return;
21065        if (callingPackage == null) {
21066            callingPackage = Integer.toString(Binder.getCallingUid());
21067        }
21068        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21069    }
21070
21071    @Override
21072    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21073        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21074        synchronized (mPackages) {
21075            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21076            if (pkgSetting != null) {
21077                pkgSetting.setUpdateAvailable(updateAvailable);
21078            }
21079        }
21080    }
21081
21082    @Override
21083    public void setComponentEnabledSetting(ComponentName componentName,
21084            int newState, int flags, int userId) {
21085        if (!sUserManager.exists(userId)) return;
21086        setEnabledSetting(componentName.getPackageName(),
21087                componentName.getClassName(), newState, flags, userId, null);
21088    }
21089
21090    private void setEnabledSetting(final String packageName, String className, int newState,
21091            final int flags, int userId, String callingPackage) {
21092        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21093              || newState == COMPONENT_ENABLED_STATE_ENABLED
21094              || newState == COMPONENT_ENABLED_STATE_DISABLED
21095              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21096              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21097            throw new IllegalArgumentException("Invalid new component state: "
21098                    + newState);
21099        }
21100        PackageSetting pkgSetting;
21101        final int callingUid = Binder.getCallingUid();
21102        final int permission;
21103        if (callingUid == Process.SYSTEM_UID) {
21104            permission = PackageManager.PERMISSION_GRANTED;
21105        } else {
21106            permission = mContext.checkCallingOrSelfPermission(
21107                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21108        }
21109        enforceCrossUserPermission(callingUid, userId,
21110                false /* requireFullPermission */, true /* checkShell */, "set enabled");
21111        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21112        boolean sendNow = false;
21113        boolean isApp = (className == null);
21114        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21115        String componentName = isApp ? packageName : className;
21116        int packageUid = -1;
21117        ArrayList<String> components;
21118
21119        // reader
21120        synchronized (mPackages) {
21121            pkgSetting = mSettings.mPackages.get(packageName);
21122            if (pkgSetting == null) {
21123                if (!isCallerInstantApp) {
21124                    if (className == null) {
21125                        throw new IllegalArgumentException("Unknown package: " + packageName);
21126                    }
21127                    throw new IllegalArgumentException(
21128                            "Unknown component: " + packageName + "/" + className);
21129                } else {
21130                    // throw SecurityException to prevent leaking package information
21131                    throw new SecurityException(
21132                            "Attempt to change component state; "
21133                            + "pid=" + Binder.getCallingPid()
21134                            + ", uid=" + callingUid
21135                            + (className == null
21136                                    ? ", package=" + packageName
21137                                    : ", component=" + packageName + "/" + className));
21138                }
21139            }
21140        }
21141
21142        // Limit who can change which apps
21143        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21144            // Don't allow apps that don't have permission to modify other apps
21145            if (!allowedByPermission) {
21146                throw new SecurityException(
21147                        "Attempt to change component state; "
21148                        + "pid=" + Binder.getCallingPid()
21149                        + ", uid=" + callingUid
21150                        + (className == null
21151                                ? ", package=" + packageName
21152                                : ", component=" + packageName + "/" + className));
21153            }
21154            // Don't allow changing protected packages.
21155            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21156                throw new SecurityException("Cannot disable a protected package: " + packageName);
21157            }
21158        }
21159
21160        synchronized (mPackages) {
21161            if (callingUid == Process.SHELL_UID
21162                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21163                // Shell can only change whole packages between ENABLED and DISABLED_USER states
21164                // unless it is a test package.
21165                int oldState = pkgSetting.getEnabled(userId);
21166                if (className == null
21167                    &&
21168                    (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21169                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21170                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21171                    &&
21172                    (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21173                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
21174                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21175                    // ok
21176                } else {
21177                    throw new SecurityException(
21178                            "Shell cannot change component state for " + packageName + "/"
21179                            + className + " to " + newState);
21180                }
21181            }
21182            if (className == null) {
21183                // We're dealing with an application/package level state change
21184                if (pkgSetting.getEnabled(userId) == newState) {
21185                    // Nothing to do
21186                    return;
21187                }
21188                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21189                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21190                    // Don't care about who enables an app.
21191                    callingPackage = null;
21192                }
21193                pkgSetting.setEnabled(newState, userId, callingPackage);
21194                // pkgSetting.pkg.mSetEnabled = newState;
21195            } else {
21196                // We're dealing with a component level state change
21197                // First, verify that this is a valid class name.
21198                PackageParser.Package pkg = pkgSetting.pkg;
21199                if (pkg == null || !pkg.hasComponentClassName(className)) {
21200                    if (pkg != null &&
21201                            pkg.applicationInfo.targetSdkVersion >=
21202                                    Build.VERSION_CODES.JELLY_BEAN) {
21203                        throw new IllegalArgumentException("Component class " + className
21204                                + " does not exist in " + packageName);
21205                    } else {
21206                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21207                                + className + " does not exist in " + packageName);
21208                    }
21209                }
21210                switch (newState) {
21211                case COMPONENT_ENABLED_STATE_ENABLED:
21212                    if (!pkgSetting.enableComponentLPw(className, userId)) {
21213                        return;
21214                    }
21215                    break;
21216                case COMPONENT_ENABLED_STATE_DISABLED:
21217                    if (!pkgSetting.disableComponentLPw(className, userId)) {
21218                        return;
21219                    }
21220                    break;
21221                case COMPONENT_ENABLED_STATE_DEFAULT:
21222                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
21223                        return;
21224                    }
21225                    break;
21226                default:
21227                    Slog.e(TAG, "Invalid new component state: " + newState);
21228                    return;
21229                }
21230            }
21231            scheduleWritePackageRestrictionsLocked(userId);
21232            updateSequenceNumberLP(packageName, new int[] { userId });
21233            final long callingId = Binder.clearCallingIdentity();
21234            try {
21235                updateInstantAppInstallerLocked(packageName);
21236            } finally {
21237                Binder.restoreCallingIdentity(callingId);
21238            }
21239            components = mPendingBroadcasts.get(userId, packageName);
21240            final boolean newPackage = components == null;
21241            if (newPackage) {
21242                components = new ArrayList<String>();
21243            }
21244            if (!components.contains(componentName)) {
21245                components.add(componentName);
21246            }
21247            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21248                sendNow = true;
21249                // Purge entry from pending broadcast list if another one exists already
21250                // since we are sending one right away.
21251                mPendingBroadcasts.remove(userId, packageName);
21252            } else {
21253                if (newPackage) {
21254                    mPendingBroadcasts.put(userId, packageName, components);
21255                }
21256                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21257                    // Schedule a message
21258                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
21259                }
21260            }
21261        }
21262
21263        long callingId = Binder.clearCallingIdentity();
21264        try {
21265            if (sendNow) {
21266                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21267                sendPackageChangedBroadcast(packageName,
21268                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21269            }
21270        } finally {
21271            Binder.restoreCallingIdentity(callingId);
21272        }
21273    }
21274
21275    @Override
21276    public void flushPackageRestrictionsAsUser(int userId) {
21277        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21278            return;
21279        }
21280        if (!sUserManager.exists(userId)) {
21281            return;
21282        }
21283        enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21284                false /* checkShell */, "flushPackageRestrictions");
21285        synchronized (mPackages) {
21286            mSettings.writePackageRestrictionsLPr(userId);
21287            mDirtyUsers.remove(userId);
21288            if (mDirtyUsers.isEmpty()) {
21289                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21290            }
21291        }
21292    }
21293
21294    private void sendPackageChangedBroadcast(String packageName,
21295            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21296        if (DEBUG_INSTALL)
21297            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21298                    + componentNames);
21299        Bundle extras = new Bundle(4);
21300        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21301        String nameList[] = new String[componentNames.size()];
21302        componentNames.toArray(nameList);
21303        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21304        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21305        extras.putInt(Intent.EXTRA_UID, packageUid);
21306        // If this is not reporting a change of the overall package, then only send it
21307        // to registered receivers.  We don't want to launch a swath of apps for every
21308        // little component state change.
21309        final int flags = !componentNames.contains(packageName)
21310                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21311        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21312                new int[] {UserHandle.getUserId(packageUid)});
21313    }
21314
21315    @Override
21316    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21317        if (!sUserManager.exists(userId)) return;
21318        final int callingUid = Binder.getCallingUid();
21319        if (getInstantAppPackageName(callingUid) != null) {
21320            return;
21321        }
21322        final int permission = mContext.checkCallingOrSelfPermission(
21323                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21324        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21325        enforceCrossUserPermission(callingUid, userId,
21326                true /* requireFullPermission */, true /* checkShell */, "stop package");
21327        // writer
21328        synchronized (mPackages) {
21329            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21330                    allowedByPermission, callingUid, userId)) {
21331                scheduleWritePackageRestrictionsLocked(userId);
21332            }
21333        }
21334    }
21335
21336    @Override
21337    public String getInstallerPackageName(String packageName) {
21338        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21339            return null;
21340        }
21341        // reader
21342        synchronized (mPackages) {
21343            return mSettings.getInstallerPackageNameLPr(packageName);
21344        }
21345    }
21346
21347    public boolean isOrphaned(String packageName) {
21348        // reader
21349        synchronized (mPackages) {
21350            return mSettings.isOrphaned(packageName);
21351        }
21352    }
21353
21354    @Override
21355    public int getApplicationEnabledSetting(String packageName, int userId) {
21356        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21357        int callingUid = Binder.getCallingUid();
21358        enforceCrossUserPermission(callingUid, userId,
21359                false /* requireFullPermission */, false /* checkShell */, "get enabled");
21360        // reader
21361        synchronized (mPackages) {
21362            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21363                return COMPONENT_ENABLED_STATE_DISABLED;
21364            }
21365            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21366        }
21367    }
21368
21369    @Override
21370    public int getComponentEnabledSetting(ComponentName component, int userId) {
21371        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21372        int callingUid = Binder.getCallingUid();
21373        enforceCrossUserPermission(callingUid, userId,
21374                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21375        synchronized (mPackages) {
21376            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21377                    component, TYPE_UNKNOWN, userId)) {
21378                return COMPONENT_ENABLED_STATE_DISABLED;
21379            }
21380            return mSettings.getComponentEnabledSettingLPr(component, userId);
21381        }
21382    }
21383
21384    @Override
21385    public void enterSafeMode() {
21386        enforceSystemOrRoot("Only the system can request entering safe mode");
21387
21388        if (!mSystemReady) {
21389            mSafeMode = true;
21390        }
21391    }
21392
21393    @Override
21394    public void systemReady() {
21395        enforceSystemOrRoot("Only the system can claim the system is ready");
21396
21397        mSystemReady = true;
21398        final ContentResolver resolver = mContext.getContentResolver();
21399        ContentObserver co = new ContentObserver(mHandler) {
21400            @Override
21401            public void onChange(boolean selfChange) {
21402                mEphemeralAppsDisabled =
21403                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
21404                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
21405            }
21406        };
21407        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21408                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21409                false, co, UserHandle.USER_SYSTEM);
21410        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21411                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
21412        co.onChange(true);
21413
21414        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21415        // disabled after already being started.
21416        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21417                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21418
21419        // Read the compatibilty setting when the system is ready.
21420        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21421                mContext.getContentResolver(),
21422                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21423        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21424        if (DEBUG_SETTINGS) {
21425            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21426        }
21427
21428        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21429
21430        synchronized (mPackages) {
21431            // Verify that all of the preferred activity components actually
21432            // exist.  It is possible for applications to be updated and at
21433            // that point remove a previously declared activity component that
21434            // had been set as a preferred activity.  We try to clean this up
21435            // the next time we encounter that preferred activity, but it is
21436            // possible for the user flow to never be able to return to that
21437            // situation so here we do a sanity check to make sure we haven't
21438            // left any junk around.
21439            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
21440            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21441                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21442                removed.clear();
21443                for (PreferredActivity pa : pir.filterSet()) {
21444                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
21445                        removed.add(pa);
21446                    }
21447                }
21448                if (removed.size() > 0) {
21449                    for (int r=0; r<removed.size(); r++) {
21450                        PreferredActivity pa = removed.get(r);
21451                        Slog.w(TAG, "Removing dangling preferred activity: "
21452                                + pa.mPref.mComponent);
21453                        pir.removeFilter(pa);
21454                    }
21455                    mSettings.writePackageRestrictionsLPr(
21456                            mSettings.mPreferredActivities.keyAt(i));
21457                }
21458            }
21459
21460            for (int userId : UserManagerService.getInstance().getUserIds()) {
21461                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21462                    grantPermissionsUserIds = ArrayUtils.appendInt(
21463                            grantPermissionsUserIds, userId);
21464                }
21465            }
21466        }
21467        sUserManager.systemReady();
21468
21469        // If we upgraded grant all default permissions before kicking off.
21470        for (int userId : grantPermissionsUserIds) {
21471            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21472        }
21473
21474        // If we did not grant default permissions, we preload from this the
21475        // default permission exceptions lazily to ensure we don't hit the
21476        // disk on a new user creation.
21477        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21478            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21479        }
21480
21481        // Kick off any messages waiting for system ready
21482        if (mPostSystemReadyMessages != null) {
21483            for (Message msg : mPostSystemReadyMessages) {
21484                msg.sendToTarget();
21485            }
21486            mPostSystemReadyMessages = null;
21487        }
21488
21489        // Watch for external volumes that come and go over time
21490        final StorageManager storage = mContext.getSystemService(StorageManager.class);
21491        storage.registerListener(mStorageListener);
21492
21493        mInstallerService.systemReady();
21494        mPackageDexOptimizer.systemReady();
21495
21496        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
21497                StorageManagerInternal.class);
21498        StorageManagerInternal.addExternalStoragePolicy(
21499                new StorageManagerInternal.ExternalStorageMountPolicy() {
21500            @Override
21501            public int getMountMode(int uid, String packageName) {
21502                if (Process.isIsolated(uid)) {
21503                    return Zygote.MOUNT_EXTERNAL_NONE;
21504                }
21505                if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
21506                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21507                }
21508                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21509                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
21510                }
21511                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21512                    return Zygote.MOUNT_EXTERNAL_READ;
21513                }
21514                return Zygote.MOUNT_EXTERNAL_WRITE;
21515            }
21516
21517            @Override
21518            public boolean hasExternalStorage(int uid, String packageName) {
21519                return true;
21520            }
21521        });
21522
21523        // Now that we're mostly running, clean up stale users and apps
21524        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21525        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21526
21527        if (mPrivappPermissionsViolations != null) {
21528            Slog.wtf(TAG,"Signature|privileged permissions not in "
21529                    + "privapp-permissions whitelist: " + mPrivappPermissionsViolations);
21530            mPrivappPermissionsViolations = null;
21531        }
21532    }
21533
21534    public void waitForAppDataPrepared() {
21535        if (mPrepareAppDataFuture == null) {
21536            return;
21537        }
21538        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21539        mPrepareAppDataFuture = null;
21540    }
21541
21542    @Override
21543    public boolean isSafeMode() {
21544        // allow instant applications
21545        return mSafeMode;
21546    }
21547
21548    @Override
21549    public boolean hasSystemUidErrors() {
21550        // allow instant applications
21551        return mHasSystemUidErrors;
21552    }
21553
21554    static String arrayToString(int[] array) {
21555        StringBuffer buf = new StringBuffer(128);
21556        buf.append('[');
21557        if (array != null) {
21558            for (int i=0; i<array.length; i++) {
21559                if (i > 0) buf.append(", ");
21560                buf.append(array[i]);
21561            }
21562        }
21563        buf.append(']');
21564        return buf.toString();
21565    }
21566
21567    static class DumpState {
21568        public static final int DUMP_LIBS = 1 << 0;
21569        public static final int DUMP_FEATURES = 1 << 1;
21570        public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2;
21571        public static final int DUMP_SERVICE_RESOLVERS = 1 << 3;
21572        public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4;
21573        public static final int DUMP_CONTENT_RESOLVERS = 1 << 5;
21574        public static final int DUMP_PERMISSIONS = 1 << 6;
21575        public static final int DUMP_PACKAGES = 1 << 7;
21576        public static final int DUMP_SHARED_USERS = 1 << 8;
21577        public static final int DUMP_MESSAGES = 1 << 9;
21578        public static final int DUMP_PROVIDERS = 1 << 10;
21579        public static final int DUMP_VERIFIERS = 1 << 11;
21580        public static final int DUMP_PREFERRED = 1 << 12;
21581        public static final int DUMP_PREFERRED_XML = 1 << 13;
21582        public static final int DUMP_KEYSETS = 1 << 14;
21583        public static final int DUMP_VERSION = 1 << 15;
21584        public static final int DUMP_INSTALLS = 1 << 16;
21585        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17;
21586        public static final int DUMP_DOMAIN_PREFERRED = 1 << 18;
21587        public static final int DUMP_FROZEN = 1 << 19;
21588        public static final int DUMP_DEXOPT = 1 << 20;
21589        public static final int DUMP_COMPILER_STATS = 1 << 21;
21590        public static final int DUMP_ENABLED_OVERLAYS = 1 << 22;
21591        public static final int DUMP_CHANGES = 1 << 23;
21592
21593        public static final int OPTION_SHOW_FILTERS = 1 << 0;
21594
21595        private int mTypes;
21596
21597        private int mOptions;
21598
21599        private boolean mTitlePrinted;
21600
21601        private SharedUserSetting mSharedUser;
21602
21603        public boolean isDumping(int type) {
21604            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
21605                return true;
21606            }
21607
21608            return (mTypes & type) != 0;
21609        }
21610
21611        public void setDump(int type) {
21612            mTypes |= type;
21613        }
21614
21615        public boolean isOptionEnabled(int option) {
21616            return (mOptions & option) != 0;
21617        }
21618
21619        public void setOptionEnabled(int option) {
21620            mOptions |= option;
21621        }
21622
21623        public boolean onTitlePrinted() {
21624            final boolean printed = mTitlePrinted;
21625            mTitlePrinted = true;
21626            return printed;
21627        }
21628
21629        public boolean getTitlePrinted() {
21630            return mTitlePrinted;
21631        }
21632
21633        public void setTitlePrinted(boolean enabled) {
21634            mTitlePrinted = enabled;
21635        }
21636
21637        public SharedUserSetting getSharedUser() {
21638            return mSharedUser;
21639        }
21640
21641        public void setSharedUser(SharedUserSetting user) {
21642            mSharedUser = user;
21643        }
21644    }
21645
21646    @Override
21647    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21648            FileDescriptor err, String[] args, ShellCallback callback,
21649            ResultReceiver resultReceiver) {
21650        (new PackageManagerShellCommand(this)).exec(
21651                this, in, out, err, args, callback, resultReceiver);
21652    }
21653
21654    @Override
21655    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21656        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21657
21658        DumpState dumpState = new DumpState();
21659        boolean fullPreferred = false;
21660        boolean checkin = false;
21661
21662        String packageName = null;
21663        ArraySet<String> permissionNames = null;
21664
21665        int opti = 0;
21666        while (opti < args.length) {
21667            String opt = args[opti];
21668            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21669                break;
21670            }
21671            opti++;
21672
21673            if ("-a".equals(opt)) {
21674                // Right now we only know how to print all.
21675            } else if ("-h".equals(opt)) {
21676                pw.println("Package manager dump options:");
21677                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21678                pw.println("    --checkin: dump for a checkin");
21679                pw.println("    -f: print details of intent filters");
21680                pw.println("    -h: print this help");
21681                pw.println("  cmd may be one of:");
21682                pw.println("    l[ibraries]: list known shared libraries");
21683                pw.println("    f[eatures]: list device features");
21684                pw.println("    k[eysets]: print known keysets");
21685                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21686                pw.println("    perm[issions]: dump permissions");
21687                pw.println("    permission [name ...]: dump declaration and use of given permission");
21688                pw.println("    pref[erred]: print preferred package settings");
21689                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21690                pw.println("    prov[iders]: dump content providers");
21691                pw.println("    p[ackages]: dump installed packages");
21692                pw.println("    s[hared-users]: dump shared user IDs");
21693                pw.println("    m[essages]: print collected runtime messages");
21694                pw.println("    v[erifiers]: print package verifier info");
21695                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21696                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21697                pw.println("    version: print database version info");
21698                pw.println("    write: write current settings now");
21699                pw.println("    installs: details about install sessions");
21700                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21701                pw.println("    dexopt: dump dexopt state");
21702                pw.println("    compiler-stats: dump compiler statistics");
21703                pw.println("    enabled-overlays: dump list of enabled overlay packages");
21704                pw.println("    <package.name>: info about given package");
21705                return;
21706            } else if ("--checkin".equals(opt)) {
21707                checkin = true;
21708            } else if ("-f".equals(opt)) {
21709                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21710            } else if ("--proto".equals(opt)) {
21711                dumpProto(fd);
21712                return;
21713            } else {
21714                pw.println("Unknown argument: " + opt + "; use -h for help");
21715            }
21716        }
21717
21718        // Is the caller requesting to dump a particular piece of data?
21719        if (opti < args.length) {
21720            String cmd = args[opti];
21721            opti++;
21722            // Is this a package name?
21723            if ("android".equals(cmd) || cmd.contains(".")) {
21724                packageName = cmd;
21725                // When dumping a single package, we always dump all of its
21726                // filter information since the amount of data will be reasonable.
21727                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21728            } else if ("check-permission".equals(cmd)) {
21729                if (opti >= args.length) {
21730                    pw.println("Error: check-permission missing permission argument");
21731                    return;
21732                }
21733                String perm = args[opti];
21734                opti++;
21735                if (opti >= args.length) {
21736                    pw.println("Error: check-permission missing package argument");
21737                    return;
21738                }
21739
21740                String pkg = args[opti];
21741                opti++;
21742                int user = UserHandle.getUserId(Binder.getCallingUid());
21743                if (opti < args.length) {
21744                    try {
21745                        user = Integer.parseInt(args[opti]);
21746                    } catch (NumberFormatException e) {
21747                        pw.println("Error: check-permission user argument is not a number: "
21748                                + args[opti]);
21749                        return;
21750                    }
21751                }
21752
21753                // Normalize package name to handle renamed packages and static libs
21754                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21755
21756                pw.println(checkPermission(perm, pkg, user));
21757                return;
21758            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21759                dumpState.setDump(DumpState.DUMP_LIBS);
21760            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21761                dumpState.setDump(DumpState.DUMP_FEATURES);
21762            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21763                if (opti >= args.length) {
21764                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21765                            | DumpState.DUMP_SERVICE_RESOLVERS
21766                            | DumpState.DUMP_RECEIVER_RESOLVERS
21767                            | DumpState.DUMP_CONTENT_RESOLVERS);
21768                } else {
21769                    while (opti < args.length) {
21770                        String name = args[opti];
21771                        if ("a".equals(name) || "activity".equals(name)) {
21772                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21773                        } else if ("s".equals(name) || "service".equals(name)) {
21774                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21775                        } else if ("r".equals(name) || "receiver".equals(name)) {
21776                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21777                        } else if ("c".equals(name) || "content".equals(name)) {
21778                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21779                        } else {
21780                            pw.println("Error: unknown resolver table type: " + name);
21781                            return;
21782                        }
21783                        opti++;
21784                    }
21785                }
21786            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21787                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21788            } else if ("permission".equals(cmd)) {
21789                if (opti >= args.length) {
21790                    pw.println("Error: permission requires permission name");
21791                    return;
21792                }
21793                permissionNames = new ArraySet<>();
21794                while (opti < args.length) {
21795                    permissionNames.add(args[opti]);
21796                    opti++;
21797                }
21798                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21799                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21800            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21801                dumpState.setDump(DumpState.DUMP_PREFERRED);
21802            } else if ("preferred-xml".equals(cmd)) {
21803                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21804                if (opti < args.length && "--full".equals(args[opti])) {
21805                    fullPreferred = true;
21806                    opti++;
21807                }
21808            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21809                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21810            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21811                dumpState.setDump(DumpState.DUMP_PACKAGES);
21812            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21813                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21814            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21815                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21816            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21817                dumpState.setDump(DumpState.DUMP_MESSAGES);
21818            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21819                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21820            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21821                    || "intent-filter-verifiers".equals(cmd)) {
21822                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21823            } else if ("version".equals(cmd)) {
21824                dumpState.setDump(DumpState.DUMP_VERSION);
21825            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21826                dumpState.setDump(DumpState.DUMP_KEYSETS);
21827            } else if ("installs".equals(cmd)) {
21828                dumpState.setDump(DumpState.DUMP_INSTALLS);
21829            } else if ("frozen".equals(cmd)) {
21830                dumpState.setDump(DumpState.DUMP_FROZEN);
21831            } else if ("dexopt".equals(cmd)) {
21832                dumpState.setDump(DumpState.DUMP_DEXOPT);
21833            } else if ("compiler-stats".equals(cmd)) {
21834                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21835            } else if ("enabled-overlays".equals(cmd)) {
21836                dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS);
21837            } else if ("changes".equals(cmd)) {
21838                dumpState.setDump(DumpState.DUMP_CHANGES);
21839            } else if ("write".equals(cmd)) {
21840                synchronized (mPackages) {
21841                    mSettings.writeLPr();
21842                    pw.println("Settings written.");
21843                    return;
21844                }
21845            }
21846        }
21847
21848        if (checkin) {
21849            pw.println("vers,1");
21850        }
21851
21852        // reader
21853        synchronized (mPackages) {
21854            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21855                if (!checkin) {
21856                    if (dumpState.onTitlePrinted())
21857                        pw.println();
21858                    pw.println("Database versions:");
21859                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21860                }
21861            }
21862
21863            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21864                if (!checkin) {
21865                    if (dumpState.onTitlePrinted())
21866                        pw.println();
21867                    pw.println("Verifiers:");
21868                    pw.print("  Required: ");
21869                    pw.print(mRequiredVerifierPackage);
21870                    pw.print(" (uid=");
21871                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21872                            UserHandle.USER_SYSTEM));
21873                    pw.println(")");
21874                } else if (mRequiredVerifierPackage != null) {
21875                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21876                    pw.print(",");
21877                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21878                            UserHandle.USER_SYSTEM));
21879                }
21880            }
21881
21882            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21883                    packageName == null) {
21884                if (mIntentFilterVerifierComponent != null) {
21885                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21886                    if (!checkin) {
21887                        if (dumpState.onTitlePrinted())
21888                            pw.println();
21889                        pw.println("Intent Filter Verifier:");
21890                        pw.print("  Using: ");
21891                        pw.print(verifierPackageName);
21892                        pw.print(" (uid=");
21893                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21894                                UserHandle.USER_SYSTEM));
21895                        pw.println(")");
21896                    } else if (verifierPackageName != null) {
21897                        pw.print("ifv,"); pw.print(verifierPackageName);
21898                        pw.print(",");
21899                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21900                                UserHandle.USER_SYSTEM));
21901                    }
21902                } else {
21903                    pw.println();
21904                    pw.println("No Intent Filter Verifier available!");
21905                }
21906            }
21907
21908            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21909                boolean printedHeader = false;
21910                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21911                while (it.hasNext()) {
21912                    String libName = it.next();
21913                    SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21914                    if (versionedLib == null) {
21915                        continue;
21916                    }
21917                    final int versionCount = versionedLib.size();
21918                    for (int i = 0; i < versionCount; i++) {
21919                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21920                        if (!checkin) {
21921                            if (!printedHeader) {
21922                                if (dumpState.onTitlePrinted())
21923                                    pw.println();
21924                                pw.println("Libraries:");
21925                                printedHeader = true;
21926                            }
21927                            pw.print("  ");
21928                        } else {
21929                            pw.print("lib,");
21930                        }
21931                        pw.print(libEntry.info.getName());
21932                        if (libEntry.info.isStatic()) {
21933                            pw.print(" version=" + libEntry.info.getVersion());
21934                        }
21935                        if (!checkin) {
21936                            pw.print(" -> ");
21937                        }
21938                        if (libEntry.path != null) {
21939                            pw.print(" (jar) ");
21940                            pw.print(libEntry.path);
21941                        } else {
21942                            pw.print(" (apk) ");
21943                            pw.print(libEntry.apk);
21944                        }
21945                        pw.println();
21946                    }
21947                }
21948            }
21949
21950            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21951                if (dumpState.onTitlePrinted())
21952                    pw.println();
21953                if (!checkin) {
21954                    pw.println("Features:");
21955                }
21956
21957                synchronized (mAvailableFeatures) {
21958                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21959                        if (checkin) {
21960                            pw.print("feat,");
21961                            pw.print(feat.name);
21962                            pw.print(",");
21963                            pw.println(feat.version);
21964                        } else {
21965                            pw.print("  ");
21966                            pw.print(feat.name);
21967                            if (feat.version > 0) {
21968                                pw.print(" version=");
21969                                pw.print(feat.version);
21970                            }
21971                            pw.println();
21972                        }
21973                    }
21974                }
21975            }
21976
21977            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21978                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21979                        : "Activity Resolver Table:", "  ", packageName,
21980                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21981                    dumpState.setTitlePrinted(true);
21982                }
21983            }
21984            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21985                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21986                        : "Receiver Resolver Table:", "  ", packageName,
21987                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21988                    dumpState.setTitlePrinted(true);
21989                }
21990            }
21991            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21992                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21993                        : "Service Resolver Table:", "  ", packageName,
21994                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21995                    dumpState.setTitlePrinted(true);
21996                }
21997            }
21998            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21999                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
22000                        : "Provider Resolver Table:", "  ", packageName,
22001                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
22002                    dumpState.setTitlePrinted(true);
22003                }
22004            }
22005
22006            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22007                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22008                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22009                    int user = mSettings.mPreferredActivities.keyAt(i);
22010                    if (pir.dump(pw,
22011                            dumpState.getTitlePrinted()
22012                                ? "\nPreferred Activities User " + user + ":"
22013                                : "Preferred Activities User " + user + ":", "  ",
22014                            packageName, true, false)) {
22015                        dumpState.setTitlePrinted(true);
22016                    }
22017                }
22018            }
22019
22020            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22021                pw.flush();
22022                FileOutputStream fout = new FileOutputStream(fd);
22023                BufferedOutputStream str = new BufferedOutputStream(fout);
22024                XmlSerializer serializer = new FastXmlSerializer();
22025                try {
22026                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
22027                    serializer.startDocument(null, true);
22028                    serializer.setFeature(
22029                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22030                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22031                    serializer.endDocument();
22032                    serializer.flush();
22033                } catch (IllegalArgumentException e) {
22034                    pw.println("Failed writing: " + e);
22035                } catch (IllegalStateException e) {
22036                    pw.println("Failed writing: " + e);
22037                } catch (IOException e) {
22038                    pw.println("Failed writing: " + e);
22039                }
22040            }
22041
22042            if (!checkin
22043                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22044                    && packageName == null) {
22045                pw.println();
22046                int count = mSettings.mPackages.size();
22047                if (count == 0) {
22048                    pw.println("No applications!");
22049                    pw.println();
22050                } else {
22051                    final String prefix = "  ";
22052                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22053                    if (allPackageSettings.size() == 0) {
22054                        pw.println("No domain preferred apps!");
22055                        pw.println();
22056                    } else {
22057                        pw.println("App verification status:");
22058                        pw.println();
22059                        count = 0;
22060                        for (PackageSetting ps : allPackageSettings) {
22061                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22062                            if (ivi == null || ivi.getPackageName() == null) continue;
22063                            pw.println(prefix + "Package: " + ivi.getPackageName());
22064                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
22065                            pw.println(prefix + "Status:  " + ivi.getStatusString());
22066                            pw.println();
22067                            count++;
22068                        }
22069                        if (count == 0) {
22070                            pw.println(prefix + "No app verification established.");
22071                            pw.println();
22072                        }
22073                        for (int userId : sUserManager.getUserIds()) {
22074                            pw.println("App linkages for user " + userId + ":");
22075                            pw.println();
22076                            count = 0;
22077                            for (PackageSetting ps : allPackageSettings) {
22078                                final long status = ps.getDomainVerificationStatusForUser(userId);
22079                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22080                                        && !DEBUG_DOMAIN_VERIFICATION) {
22081                                    continue;
22082                                }
22083                                pw.println(prefix + "Package: " + ps.name);
22084                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22085                                String statusStr = IntentFilterVerificationInfo.
22086                                        getStatusStringFromValue(status);
22087                                pw.println(prefix + "Status:  " + statusStr);
22088                                pw.println();
22089                                count++;
22090                            }
22091                            if (count == 0) {
22092                                pw.println(prefix + "No configured app linkages.");
22093                                pw.println();
22094                            }
22095                        }
22096                    }
22097                }
22098            }
22099
22100            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22101                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22102                if (packageName == null && permissionNames == null) {
22103                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
22104                        if (iperm == 0) {
22105                            if (dumpState.onTitlePrinted())
22106                                pw.println();
22107                            pw.println("AppOp Permissions:");
22108                        }
22109                        pw.print("  AppOp Permission ");
22110                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
22111                        pw.println(":");
22112                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
22113                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
22114                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
22115                        }
22116                    }
22117                }
22118            }
22119
22120            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22121                boolean printedSomething = false;
22122                for (PackageParser.Provider p : mProviders.mProviders.values()) {
22123                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22124                        continue;
22125                    }
22126                    if (!printedSomething) {
22127                        if (dumpState.onTitlePrinted())
22128                            pw.println();
22129                        pw.println("Registered ContentProviders:");
22130                        printedSomething = true;
22131                    }
22132                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
22133                    pw.print("    "); pw.println(p.toString());
22134                }
22135                printedSomething = false;
22136                for (Map.Entry<String, PackageParser.Provider> entry :
22137                        mProvidersByAuthority.entrySet()) {
22138                    PackageParser.Provider p = entry.getValue();
22139                    if (packageName != null && !packageName.equals(p.info.packageName)) {
22140                        continue;
22141                    }
22142                    if (!printedSomething) {
22143                        if (dumpState.onTitlePrinted())
22144                            pw.println();
22145                        pw.println("ContentProvider Authorities:");
22146                        printedSomething = true;
22147                    }
22148                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
22149                    pw.print("    "); pw.println(p.toString());
22150                    if (p.info != null && p.info.applicationInfo != null) {
22151                        final String appInfo = p.info.applicationInfo.toString();
22152                        pw.print("      applicationInfo="); pw.println(appInfo);
22153                    }
22154                }
22155            }
22156
22157            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22158                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22159            }
22160
22161            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22162                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22163            }
22164
22165            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22166                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22167            }
22168
22169            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22170                if (dumpState.onTitlePrinted()) pw.println();
22171                pw.println("Package Changes:");
22172                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22173                final int K = mChangedPackages.size();
22174                for (int i = 0; i < K; i++) {
22175                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
22176                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22177                    final int N = changes.size();
22178                    if (N == 0) {
22179                        pw.print("    "); pw.println("No packages changed");
22180                    } else {
22181                        for (int j = 0; j < N; j++) {
22182                            final String pkgName = changes.valueAt(j);
22183                            final int sequenceNumber = changes.keyAt(j);
22184                            pw.print("    ");
22185                            pw.print("seq=");
22186                            pw.print(sequenceNumber);
22187                            pw.print(", package=");
22188                            pw.println(pkgName);
22189                        }
22190                    }
22191                }
22192            }
22193
22194            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
22195                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
22196            }
22197
22198            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22199                // XXX should handle packageName != null by dumping only install data that
22200                // the given package is involved with.
22201                if (dumpState.onTitlePrinted()) pw.println();
22202
22203                final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22204                ipw.println();
22205                ipw.println("Frozen packages:");
22206                ipw.increaseIndent();
22207                if (mFrozenPackages.size() == 0) {
22208                    ipw.println("(none)");
22209                } else {
22210                    for (int i = 0; i < mFrozenPackages.size(); i++) {
22211                        ipw.println(mFrozenPackages.valueAt(i));
22212                    }
22213                }
22214                ipw.decreaseIndent();
22215            }
22216
22217            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22218                if (dumpState.onTitlePrinted()) pw.println();
22219                dumpDexoptStateLPr(pw, packageName);
22220            }
22221
22222            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22223                if (dumpState.onTitlePrinted()) pw.println();
22224                dumpCompilerStatsLPr(pw, packageName);
22225            }
22226
22227            if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) {
22228                if (dumpState.onTitlePrinted()) pw.println();
22229                dumpEnabledOverlaysLPr(pw);
22230            }
22231
22232            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22233                if (dumpState.onTitlePrinted()) pw.println();
22234                mSettings.dumpReadMessagesLPr(pw, dumpState);
22235
22236                pw.println();
22237                pw.println("Package warning messages:");
22238                BufferedReader in = null;
22239                String line = null;
22240                try {
22241                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22242                    while ((line = in.readLine()) != null) {
22243                        if (line.contains("ignored: updated version")) continue;
22244                        pw.println(line);
22245                    }
22246                } catch (IOException ignored) {
22247                } finally {
22248                    IoUtils.closeQuietly(in);
22249                }
22250            }
22251
22252            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22253                BufferedReader in = null;
22254                String line = null;
22255                try {
22256                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22257                    while ((line = in.readLine()) != null) {
22258                        if (line.contains("ignored: updated version")) continue;
22259                        pw.print("msg,");
22260                        pw.println(line);
22261                    }
22262                } catch (IOException ignored) {
22263                } finally {
22264                    IoUtils.closeQuietly(in);
22265                }
22266            }
22267        }
22268
22269        // PackageInstaller should be called outside of mPackages lock
22270        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22271            // XXX should handle packageName != null by dumping only install data that
22272            // the given package is involved with.
22273            if (dumpState.onTitlePrinted()) pw.println();
22274            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22275        }
22276    }
22277
22278    private void dumpProto(FileDescriptor fd) {
22279        final ProtoOutputStream proto = new ProtoOutputStream(fd);
22280
22281        synchronized (mPackages) {
22282            final long requiredVerifierPackageToken =
22283                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22284            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22285            proto.write(
22286                    PackageServiceDumpProto.PackageShortProto.UID,
22287                    getPackageUid(
22288                            mRequiredVerifierPackage,
22289                            MATCH_DEBUG_TRIAGED_MISSING,
22290                            UserHandle.USER_SYSTEM));
22291            proto.end(requiredVerifierPackageToken);
22292
22293            if (mIntentFilterVerifierComponent != null) {
22294                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22295                final long verifierPackageToken =
22296                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22297                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22298                proto.write(
22299                        PackageServiceDumpProto.PackageShortProto.UID,
22300                        getPackageUid(
22301                                verifierPackageName,
22302                                MATCH_DEBUG_TRIAGED_MISSING,
22303                                UserHandle.USER_SYSTEM));
22304                proto.end(verifierPackageToken);
22305            }
22306
22307            dumpSharedLibrariesProto(proto);
22308            dumpFeaturesProto(proto);
22309            mSettings.dumpPackagesProto(proto);
22310            mSettings.dumpSharedUsersProto(proto);
22311            dumpMessagesProto(proto);
22312        }
22313        proto.flush();
22314    }
22315
22316    private void dumpMessagesProto(ProtoOutputStream proto) {
22317        BufferedReader in = null;
22318        String line = null;
22319        try {
22320            in = new BufferedReader(new FileReader(getSettingsProblemFile()));
22321            while ((line = in.readLine()) != null) {
22322                if (line.contains("ignored: updated version")) continue;
22323                proto.write(PackageServiceDumpProto.MESSAGES, line);
22324            }
22325        } catch (IOException ignored) {
22326        } finally {
22327            IoUtils.closeQuietly(in);
22328        }
22329    }
22330
22331    private void dumpFeaturesProto(ProtoOutputStream proto) {
22332        synchronized (mAvailableFeatures) {
22333            final int count = mAvailableFeatures.size();
22334            for (int i = 0; i < count; i++) {
22335                final FeatureInfo feat = mAvailableFeatures.valueAt(i);
22336                final long featureToken = proto.start(PackageServiceDumpProto.FEATURES);
22337                proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name);
22338                proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version);
22339                proto.end(featureToken);
22340            }
22341        }
22342    }
22343
22344    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22345        final int count = mSharedLibraries.size();
22346        for (int i = 0; i < count; i++) {
22347            final String libName = mSharedLibraries.keyAt(i);
22348            SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
22349            if (versionedLib == null) {
22350                continue;
22351            }
22352            final int versionCount = versionedLib.size();
22353            for (int j = 0; j < versionCount; j++) {
22354                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
22355                final long sharedLibraryToken =
22356                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22357                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
22358                final boolean isJar = (libEntry.path != null);
22359                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22360                if (isJar) {
22361                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
22362                } else {
22363                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
22364                }
22365                proto.end(sharedLibraryToken);
22366            }
22367        }
22368    }
22369
22370    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22371        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22372        ipw.println();
22373        ipw.println("Dexopt state:");
22374        ipw.increaseIndent();
22375        Collection<PackageParser.Package> packages = null;
22376        if (packageName != null) {
22377            PackageParser.Package targetPackage = mPackages.get(packageName);
22378            if (targetPackage != null) {
22379                packages = Collections.singletonList(targetPackage);
22380            } else {
22381                ipw.println("Unable to find package: " + packageName);
22382                return;
22383            }
22384        } else {
22385            packages = mPackages.values();
22386        }
22387
22388        for (PackageParser.Package pkg : packages) {
22389            ipw.println("[" + pkg.packageName + "]");
22390            ipw.increaseIndent();
22391            mPackageDexOptimizer.dumpDexoptState(ipw, pkg);
22392            ipw.decreaseIndent();
22393        }
22394    }
22395
22396    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22397        final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22398        ipw.println();
22399        ipw.println("Compiler stats:");
22400        ipw.increaseIndent();
22401        Collection<PackageParser.Package> packages = null;
22402        if (packageName != null) {
22403            PackageParser.Package targetPackage = mPackages.get(packageName);
22404            if (targetPackage != null) {
22405                packages = Collections.singletonList(targetPackage);
22406            } else {
22407                ipw.println("Unable to find package: " + packageName);
22408                return;
22409            }
22410        } else {
22411            packages = mPackages.values();
22412        }
22413
22414        for (PackageParser.Package pkg : packages) {
22415            ipw.println("[" + pkg.packageName + "]");
22416            ipw.increaseIndent();
22417
22418            CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22419            if (stats == null) {
22420                ipw.println("(No recorded stats)");
22421            } else {
22422                stats.dump(ipw);
22423            }
22424            ipw.decreaseIndent();
22425        }
22426    }
22427
22428    private void dumpEnabledOverlaysLPr(PrintWriter pw) {
22429        pw.println("Enabled overlay paths:");
22430        final int N = mEnabledOverlayPaths.size();
22431        for (int i = 0; i < N; i++) {
22432            final int userId = mEnabledOverlayPaths.keyAt(i);
22433            pw.println(String.format("    User %d:", userId));
22434            final ArrayMap<String, ArrayList<String>> userSpecificOverlays =
22435                mEnabledOverlayPaths.valueAt(i);
22436            final int M = userSpecificOverlays.size();
22437            for (int j = 0; j < M; j++) {
22438                final String targetPackageName = userSpecificOverlays.keyAt(j);
22439                final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j);
22440                pw.println(String.format("        %s: %s", targetPackageName, overlayPackagePaths));
22441            }
22442        }
22443    }
22444
22445    private String dumpDomainString(String packageName) {
22446        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22447                .getList();
22448        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22449
22450        ArraySet<String> result = new ArraySet<>();
22451        if (iviList.size() > 0) {
22452            for (IntentFilterVerificationInfo ivi : iviList) {
22453                for (String host : ivi.getDomains()) {
22454                    result.add(host);
22455                }
22456            }
22457        }
22458        if (filters != null && filters.size() > 0) {
22459            for (IntentFilter filter : filters) {
22460                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22461                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22462                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22463                    result.addAll(filter.getHostsList());
22464                }
22465            }
22466        }
22467
22468        StringBuilder sb = new StringBuilder(result.size() * 16);
22469        for (String domain : result) {
22470            if (sb.length() > 0) sb.append(" ");
22471            sb.append(domain);
22472        }
22473        return sb.toString();
22474    }
22475
22476    // ------- apps on sdcard specific code -------
22477    static final boolean DEBUG_SD_INSTALL = false;
22478
22479    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22480
22481    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22482
22483    private boolean mMediaMounted = false;
22484
22485    static String getEncryptKey() {
22486        try {
22487            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22488                    SD_ENCRYPTION_KEYSTORE_NAME);
22489            if (sdEncKey == null) {
22490                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22491                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22492                if (sdEncKey == null) {
22493                    Slog.e(TAG, "Failed to create encryption keys");
22494                    return null;
22495                }
22496            }
22497            return sdEncKey;
22498        } catch (NoSuchAlgorithmException nsae) {
22499            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22500            return null;
22501        } catch (IOException ioe) {
22502            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22503            return null;
22504        }
22505    }
22506
22507    /*
22508     * Update media status on PackageManager.
22509     */
22510    @Override
22511    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
22512        enforceSystemOrRoot("Media status can only be updated by the system");
22513        // reader; this apparently protects mMediaMounted, but should probably
22514        // be a different lock in that case.
22515        synchronized (mPackages) {
22516            Log.i(TAG, "Updating external media status from "
22517                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
22518                    + (mediaStatus ? "mounted" : "unmounted"));
22519            if (DEBUG_SD_INSTALL)
22520                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
22521                        + ", mMediaMounted=" + mMediaMounted);
22522            if (mediaStatus == mMediaMounted) {
22523                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
22524                        : 0, -1);
22525                mHandler.sendMessage(msg);
22526                return;
22527            }
22528            mMediaMounted = mediaStatus;
22529        }
22530        // Queue up an async operation since the package installation may take a
22531        // little while.
22532        mHandler.post(new Runnable() {
22533            public void run() {
22534                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
22535            }
22536        });
22537    }
22538
22539    /**
22540     * Called by StorageManagerService when the initial ASECs to scan are available.
22541     * Should block until all the ASEC containers are finished being scanned.
22542     */
22543    public void scanAvailableAsecs() {
22544        updateExternalMediaStatusInner(true, false, false);
22545    }
22546
22547    /*
22548     * Collect information of applications on external media, map them against
22549     * existing containers and update information based on current mount status.
22550     * Please note that we always have to report status if reportStatus has been
22551     * set to true especially when unloading packages.
22552     */
22553    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
22554            boolean externalStorage) {
22555        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
22556        int[] uidArr = EmptyArray.INT;
22557
22558        final String[] list = PackageHelper.getSecureContainerList();
22559        if (ArrayUtils.isEmpty(list)) {
22560            Log.i(TAG, "No secure containers found");
22561        } else {
22562            // Process list of secure containers and categorize them
22563            // as active or stale based on their package internal state.
22564
22565            // reader
22566            synchronized (mPackages) {
22567                for (String cid : list) {
22568                    // Leave stages untouched for now; installer service owns them
22569                    if (PackageInstallerService.isStageName(cid)) continue;
22570
22571                    if (DEBUG_SD_INSTALL)
22572                        Log.i(TAG, "Processing container " + cid);
22573                    String pkgName = getAsecPackageName(cid);
22574                    if (pkgName == null) {
22575                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
22576                        continue;
22577                    }
22578                    if (DEBUG_SD_INSTALL)
22579                        Log.i(TAG, "Looking for pkg : " + pkgName);
22580
22581                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
22582                    if (ps == null) {
22583                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
22584                        continue;
22585                    }
22586
22587                    /*
22588                     * Skip packages that are not external if we're unmounting
22589                     * external storage.
22590                     */
22591                    if (externalStorage && !isMounted && !isExternal(ps)) {
22592                        continue;
22593                    }
22594
22595                    final AsecInstallArgs args = new AsecInstallArgs(cid,
22596                            getAppDexInstructionSets(ps), ps.isForwardLocked());
22597                    // The package status is changed only if the code path
22598                    // matches between settings and the container id.
22599                    if (ps.codePathString != null
22600                            && ps.codePathString.startsWith(args.getCodePath())) {
22601                        if (DEBUG_SD_INSTALL) {
22602                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
22603                                    + " at code path: " + ps.codePathString);
22604                        }
22605
22606                        // We do have a valid package installed on sdcard
22607                        processCids.put(args, ps.codePathString);
22608                        final int uid = ps.appId;
22609                        if (uid != -1) {
22610                            uidArr = ArrayUtils.appendInt(uidArr, uid);
22611                        }
22612                    } else {
22613                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
22614                                + ps.codePathString);
22615                    }
22616                }
22617            }
22618
22619            Arrays.sort(uidArr);
22620        }
22621
22622        // Process packages with valid entries.
22623        if (isMounted) {
22624            if (DEBUG_SD_INSTALL)
22625                Log.i(TAG, "Loading packages");
22626            loadMediaPackages(processCids, uidArr, externalStorage);
22627            startCleaningPackages();
22628            mInstallerService.onSecureContainersAvailable();
22629        } else {
22630            if (DEBUG_SD_INSTALL)
22631                Log.i(TAG, "Unloading packages");
22632            unloadMediaPackages(processCids, uidArr, reportStatus);
22633        }
22634    }
22635
22636    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22637            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22638        final int size = infos.size();
22639        final String[] packageNames = new String[size];
22640        final int[] packageUids = new int[size];
22641        for (int i = 0; i < size; i++) {
22642            final ApplicationInfo info = infos.get(i);
22643            packageNames[i] = info.packageName;
22644            packageUids[i] = info.uid;
22645        }
22646        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22647                finishedReceiver);
22648    }
22649
22650    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22651            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22652        sendResourcesChangedBroadcast(mediaStatus, replacing,
22653                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22654    }
22655
22656    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22657            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22658        int size = pkgList.length;
22659        if (size > 0) {
22660            // Send broadcasts here
22661            Bundle extras = new Bundle();
22662            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22663            if (uidArr != null) {
22664                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22665            }
22666            if (replacing) {
22667                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22668            }
22669            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22670                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22671            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null);
22672        }
22673    }
22674
22675   /*
22676     * Look at potentially valid container ids from processCids If package
22677     * information doesn't match the one on record or package scanning fails,
22678     * the cid is added to list of removeCids. We currently don't delete stale
22679     * containers.
22680     */
22681    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr,
22682            boolean externalStorage) {
22683        ArrayList<String> pkgList = new ArrayList<String>();
22684        Set<AsecInstallArgs> keys = processCids.keySet();
22685
22686        for (AsecInstallArgs args : keys) {
22687            String codePath = processCids.get(args);
22688            if (DEBUG_SD_INSTALL)
22689                Log.i(TAG, "Loading container : " + args.cid);
22690            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
22691            try {
22692                // Make sure there are no container errors first.
22693                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
22694                    Slog.e(TAG, "Failed to mount cid : " + args.cid
22695                            + " when installing from sdcard");
22696                    continue;
22697                }
22698                // Check code path here.
22699                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
22700                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
22701                            + " does not match one in settings " + codePath);
22702                    continue;
22703                }
22704                // Parse package
22705                int parseFlags = mDefParseFlags;
22706                if (args.isExternalAsec()) {
22707                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
22708                }
22709                if (args.isFwdLocked()) {
22710                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
22711                }
22712
22713                synchronized (mInstallLock) {
22714                    PackageParser.Package pkg = null;
22715                    try {
22716                        // Sadly we don't know the package name yet to freeze it
22717                        pkg = scanPackageTracedLI(new File(codePath), parseFlags,
22718                                SCAN_IGNORE_FROZEN, 0, null);
22719                    } catch (PackageManagerException e) {
22720                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
22721                    }
22722                    // Scan the package
22723                    if (pkg != null) {
22724                        /*
22725                         * TODO why is the lock being held? doPostInstall is
22726                         * called in other places without the lock. This needs
22727                         * to be straightened out.
22728                         */
22729                        // writer
22730                        synchronized (mPackages) {
22731                            retCode = PackageManager.INSTALL_SUCCEEDED;
22732                            pkgList.add(pkg.packageName);
22733                            // Post process args
22734                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
22735                                    pkg.applicationInfo.uid);
22736                        }
22737                    } else {
22738                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
22739                    }
22740                }
22741
22742            } finally {
22743                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
22744                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
22745                }
22746            }
22747        }
22748        // writer
22749        synchronized (mPackages) {
22750            // If the platform SDK has changed since the last time we booted,
22751            // we need to re-grant app permission to catch any new ones that
22752            // appear. This is really a hack, and means that apps can in some
22753            // cases get permissions that the user didn't initially explicitly
22754            // allow... it would be nice to have some better way to handle
22755            // this situation.
22756            final VersionInfo ver = externalStorage ? mSettings.getExternalVersion()
22757                    : mSettings.getInternalVersion();
22758            final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL
22759                    : StorageManager.UUID_PRIVATE_INTERNAL;
22760
22761            int updateFlags = UPDATE_PERMISSIONS_ALL;
22762            if (ver.sdkVersion != mSdkVersion) {
22763                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22764                        + mSdkVersion + "; regranting permissions for external");
22765                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22766            }
22767            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22768
22769            // Yay, everything is now upgraded
22770            ver.forceCurrent();
22771
22772            // can downgrade to reader
22773            // Persist settings
22774            mSettings.writeLPr();
22775        }
22776        // Send a broadcast to let everyone know we are done processing
22777        if (pkgList.size() > 0) {
22778            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
22779        }
22780    }
22781
22782   /*
22783     * Utility method to unload a list of specified containers
22784     */
22785    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
22786        // Just unmount all valid containers.
22787        for (AsecInstallArgs arg : cidArgs) {
22788            synchronized (mInstallLock) {
22789                arg.doPostDeleteLI(false);
22790           }
22791       }
22792   }
22793
22794    /*
22795     * Unload packages mounted on external media. This involves deleting package
22796     * data from internal structures, sending broadcasts about disabled packages,
22797     * gc'ing to free up references, unmounting all secure containers
22798     * corresponding to packages on external media, and posting a
22799     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
22800     * that we always have to post this message if status has been requested no
22801     * matter what.
22802     */
22803    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
22804            final boolean reportStatus) {
22805        if (DEBUG_SD_INSTALL)
22806            Log.i(TAG, "unloading media packages");
22807        ArrayList<String> pkgList = new ArrayList<String>();
22808        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
22809        final Set<AsecInstallArgs> keys = processCids.keySet();
22810        for (AsecInstallArgs args : keys) {
22811            String pkgName = args.getPackageName();
22812            if (DEBUG_SD_INSTALL)
22813                Log.i(TAG, "Trying to unload pkg : " + pkgName);
22814            // Delete package internally
22815            PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22816            synchronized (mInstallLock) {
22817                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22818                final boolean res;
22819                try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags,
22820                        "unloadMediaPackages")) {
22821                    res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false,
22822                            null);
22823                }
22824                if (res) {
22825                    pkgList.add(pkgName);
22826                } else {
22827                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
22828                    failedList.add(args);
22829                }
22830            }
22831        }
22832
22833        // reader
22834        synchronized (mPackages) {
22835            // We didn't update the settings after removing each package;
22836            // write them now for all packages.
22837            mSettings.writeLPr();
22838        }
22839
22840        // We have to absolutely send UPDATED_MEDIA_STATUS only
22841        // after confirming that all the receivers processed the ordered
22842        // broadcast when packages get disabled, force a gc to clean things up.
22843        // and unload all the containers.
22844        if (pkgList.size() > 0) {
22845            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
22846                    new IIntentReceiver.Stub() {
22847                public void performReceive(Intent intent, int resultCode, String data,
22848                        Bundle extras, boolean ordered, boolean sticky,
22849                        int sendingUser) throws RemoteException {
22850                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
22851                            reportStatus ? 1 : 0, 1, keys);
22852                    mHandler.sendMessage(msg);
22853                }
22854            });
22855        } else {
22856            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
22857                    keys);
22858            mHandler.sendMessage(msg);
22859        }
22860    }
22861
22862    private void loadPrivatePackages(final VolumeInfo vol) {
22863        mHandler.post(new Runnable() {
22864            @Override
22865            public void run() {
22866                loadPrivatePackagesInner(vol);
22867            }
22868        });
22869    }
22870
22871    private void loadPrivatePackagesInner(VolumeInfo vol) {
22872        final String volumeUuid = vol.fsUuid;
22873        if (TextUtils.isEmpty(volumeUuid)) {
22874            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22875            return;
22876        }
22877
22878        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22879        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22880        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22881
22882        final VersionInfo ver;
22883        final List<PackageSetting> packages;
22884        synchronized (mPackages) {
22885            ver = mSettings.findOrCreateVersion(volumeUuid);
22886            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22887        }
22888
22889        for (PackageSetting ps : packages) {
22890            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22891            synchronized (mInstallLock) {
22892                final PackageParser.Package pkg;
22893                try {
22894                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22895                    loaded.add(pkg.applicationInfo);
22896
22897                } catch (PackageManagerException e) {
22898                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22899                }
22900
22901                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22902                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
22903                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
22904                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22905                }
22906            }
22907        }
22908
22909        // Reconcile app data for all started/unlocked users
22910        final StorageManager sm = mContext.getSystemService(StorageManager.class);
22911        final UserManager um = mContext.getSystemService(UserManager.class);
22912        UserManagerInternal umInternal = getUserManagerInternal();
22913        for (UserInfo user : um.getUsers()) {
22914            final int flags;
22915            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22916                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22917            } else if (umInternal.isUserRunning(user.id)) {
22918                flags = StorageManager.FLAG_STORAGE_DE;
22919            } else {
22920                continue;
22921            }
22922
22923            try {
22924                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22925                synchronized (mInstallLock) {
22926                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22927                }
22928            } catch (IllegalStateException e) {
22929                // Device was probably ejected, and we'll process that event momentarily
22930                Slog.w(TAG, "Failed to prepare storage: " + e);
22931            }
22932        }
22933
22934        synchronized (mPackages) {
22935            int updateFlags = UPDATE_PERMISSIONS_ALL;
22936            if (ver.sdkVersion != mSdkVersion) {
22937                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22938                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
22939                updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
22940            }
22941            updatePermissionsLPw(null, null, volumeUuid, updateFlags);
22942
22943            // Yay, everything is now upgraded
22944            ver.forceCurrent();
22945
22946            mSettings.writeLPr();
22947        }
22948
22949        for (PackageFreezer freezer : freezers) {
22950            freezer.close();
22951        }
22952
22953        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22954        sendResourcesChangedBroadcast(true, false, loaded, null);
22955    }
22956
22957    private void unloadPrivatePackages(final VolumeInfo vol) {
22958        mHandler.post(new Runnable() {
22959            @Override
22960            public void run() {
22961                unloadPrivatePackagesInner(vol);
22962            }
22963        });
22964    }
22965
22966    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22967        final String volumeUuid = vol.fsUuid;
22968        if (TextUtils.isEmpty(volumeUuid)) {
22969            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22970            return;
22971        }
22972
22973        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22974        synchronized (mInstallLock) {
22975        synchronized (mPackages) {
22976            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22977            for (PackageSetting ps : packages) {
22978                if (ps.pkg == null) continue;
22979
22980                final ApplicationInfo info = ps.pkg.applicationInfo;
22981                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22982                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22983
22984                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22985                        "unloadPrivatePackagesInner")) {
22986                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22987                            false, null)) {
22988                        unloaded.add(info);
22989                    } else {
22990                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22991                    }
22992                }
22993
22994                // Try very hard to release any references to this package
22995                // so we don't risk the system server being killed due to
22996                // open FDs
22997                AttributeCache.instance().removePackage(ps.name);
22998            }
22999
23000            mSettings.writeLPr();
23001        }
23002        }
23003
23004        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
23005        sendResourcesChangedBroadcast(false, false, unloaded, null);
23006
23007        // Try very hard to release any references to this path so we don't risk
23008        // the system server being killed due to open FDs
23009        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
23010
23011        for (int i = 0; i < 3; i++) {
23012            System.gc();
23013            System.runFinalization();
23014        }
23015    }
23016
23017    private void assertPackageKnown(String volumeUuid, String packageName)
23018            throws PackageManagerException {
23019        synchronized (mPackages) {
23020            // Normalize package name to handle renamed packages
23021            packageName = normalizePackageNameLPr(packageName);
23022
23023            final PackageSetting ps = mSettings.mPackages.get(packageName);
23024            if (ps == null) {
23025                throw new PackageManagerException("Package " + packageName + " is unknown");
23026            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23027                throw new PackageManagerException(
23028                        "Package " + packageName + " found on unknown volume " + volumeUuid
23029                                + "; expected volume " + ps.volumeUuid);
23030            }
23031        }
23032    }
23033
23034    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
23035            throws PackageManagerException {
23036        synchronized (mPackages) {
23037            // Normalize package name to handle renamed packages
23038            packageName = normalizePackageNameLPr(packageName);
23039
23040            final PackageSetting ps = mSettings.mPackages.get(packageName);
23041            if (ps == null) {
23042                throw new PackageManagerException("Package " + packageName + " is unknown");
23043            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
23044                throw new PackageManagerException(
23045                        "Package " + packageName + " found on unknown volume " + volumeUuid
23046                                + "; expected volume " + ps.volumeUuid);
23047            } else if (!ps.getInstalled(userId)) {
23048                throw new PackageManagerException(
23049                        "Package " + packageName + " not installed for user " + userId);
23050            }
23051        }
23052    }
23053
23054    private List<String> collectAbsoluteCodePaths() {
23055        synchronized (mPackages) {
23056            List<String> codePaths = new ArrayList<>();
23057            final int packageCount = mSettings.mPackages.size();
23058            for (int i = 0; i < packageCount; i++) {
23059                final PackageSetting ps = mSettings.mPackages.valueAt(i);
23060                codePaths.add(ps.codePath.getAbsolutePath());
23061            }
23062            return codePaths;
23063        }
23064    }
23065
23066    /**
23067     * Examine all apps present on given mounted volume, and destroy apps that
23068     * aren't expected, either due to uninstallation or reinstallation on
23069     * another volume.
23070     */
23071    private void reconcileApps(String volumeUuid) {
23072        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
23073        List<File> filesToDelete = null;
23074
23075        final File[] files = FileUtils.listFilesOrEmpty(
23076                Environment.getDataAppDirectory(volumeUuid));
23077        for (File file : files) {
23078            final boolean isPackage = (isApkFile(file) || file.isDirectory())
23079                    && !PackageInstallerService.isStageName(file.getName());
23080            if (!isPackage) {
23081                // Ignore entries which are not packages
23082                continue;
23083            }
23084
23085            String absolutePath = file.getAbsolutePath();
23086
23087            boolean pathValid = false;
23088            final int absoluteCodePathCount = absoluteCodePaths.size();
23089            for (int i = 0; i < absoluteCodePathCount; i++) {
23090                String absoluteCodePath = absoluteCodePaths.get(i);
23091                if (absolutePath.startsWith(absoluteCodePath)) {
23092                    pathValid = true;
23093                    break;
23094                }
23095            }
23096
23097            if (!pathValid) {
23098                if (filesToDelete == null) {
23099                    filesToDelete = new ArrayList<>();
23100                }
23101                filesToDelete.add(file);
23102            }
23103        }
23104
23105        if (filesToDelete != null) {
23106            final int fileToDeleteCount = filesToDelete.size();
23107            for (int i = 0; i < fileToDeleteCount; i++) {
23108                File fileToDelete = filesToDelete.get(i);
23109                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
23110                synchronized (mInstallLock) {
23111                    removeCodePathLI(fileToDelete);
23112                }
23113            }
23114        }
23115    }
23116
23117    /**
23118     * Reconcile all app data for the given user.
23119     * <p>
23120     * Verifies that directories exist and that ownership and labeling is
23121     * correct for all installed apps on all mounted volumes.
23122     */
23123    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
23124        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23125        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
23126            final String volumeUuid = vol.getFsUuid();
23127            synchronized (mInstallLock) {
23128                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
23129            }
23130        }
23131    }
23132
23133    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23134            boolean migrateAppData) {
23135        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
23136    }
23137
23138    /**
23139     * Reconcile all app data on given mounted volume.
23140     * <p>
23141     * Destroys app data that isn't expected, either due to uninstallation or
23142     * reinstallation on another volume.
23143     * <p>
23144     * Verifies that directories exist and that ownership and labeling is
23145     * correct for all installed apps.
23146     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
23147     */
23148    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
23149            boolean migrateAppData, boolean onlyCoreApps) {
23150        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
23151                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
23152        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
23153
23154        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
23155        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
23156
23157        // First look for stale data that doesn't belong, and check if things
23158        // have changed since we did our last restorecon
23159        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23160            if (StorageManager.isFileEncryptedNativeOrEmulated()
23161                    && !StorageManager.isUserKeyUnlocked(userId)) {
23162                throw new RuntimeException(
23163                        "Yikes, someone asked us to reconcile CE storage while " + userId
23164                                + " was still locked; this would have caused massive data loss!");
23165            }
23166
23167            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
23168            for (File file : files) {
23169                final String packageName = file.getName();
23170                try {
23171                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23172                } catch (PackageManagerException e) {
23173                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23174                    try {
23175                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23176                                StorageManager.FLAG_STORAGE_CE, 0);
23177                    } catch (InstallerException e2) {
23178                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23179                    }
23180                }
23181            }
23182        }
23183        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
23184            final File[] files = FileUtils.listFilesOrEmpty(deDir);
23185            for (File file : files) {
23186                final String packageName = file.getName();
23187                try {
23188                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
23189                } catch (PackageManagerException e) {
23190                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
23191                    try {
23192                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
23193                                StorageManager.FLAG_STORAGE_DE, 0);
23194                    } catch (InstallerException e2) {
23195                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
23196                    }
23197                }
23198            }
23199        }
23200
23201        // Ensure that data directories are ready to roll for all packages
23202        // installed for this volume and user
23203        final List<PackageSetting> packages;
23204        synchronized (mPackages) {
23205            packages = mSettings.getVolumePackagesLPr(volumeUuid);
23206        }
23207        int preparedCount = 0;
23208        for (PackageSetting ps : packages) {
23209            final String packageName = ps.name;
23210            if (ps.pkg == null) {
23211                Slog.w(TAG, "Odd, missing scanned package " + packageName);
23212                // TODO: might be due to legacy ASEC apps; we should circle back
23213                // and reconcile again once they're scanned
23214                continue;
23215            }
23216            // Skip non-core apps if requested
23217            if (onlyCoreApps && !ps.pkg.coreApp) {
23218                result.add(packageName);
23219                continue;
23220            }
23221
23222            if (ps.getInstalled(userId)) {
23223                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
23224                preparedCount++;
23225            }
23226        }
23227
23228        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
23229        return result;
23230    }
23231
23232    /**
23233     * Prepare app data for the given app just after it was installed or
23234     * upgraded. This method carefully only touches users that it's installed
23235     * for, and it forces a restorecon to handle any seinfo changes.
23236     * <p>
23237     * Verifies that directories exist and that ownership and labeling is
23238     * correct for all installed apps. If there is an ownership mismatch, it
23239     * will try recovering system apps by wiping data; third-party app data is
23240     * left intact.
23241     * <p>
23242     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
23243     */
23244    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
23245        final PackageSetting ps;
23246        synchronized (mPackages) {
23247            ps = mSettings.mPackages.get(pkg.packageName);
23248            mSettings.writeKernelMappingLPr(ps);
23249        }
23250
23251        final UserManager um = mContext.getSystemService(UserManager.class);
23252        UserManagerInternal umInternal = getUserManagerInternal();
23253        for (UserInfo user : um.getUsers()) {
23254            final int flags;
23255            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
23256                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
23257            } else if (umInternal.isUserRunning(user.id)) {
23258                flags = StorageManager.FLAG_STORAGE_DE;
23259            } else {
23260                continue;
23261            }
23262
23263            if (ps.getInstalled(user.id)) {
23264                // TODO: when user data is locked, mark that we're still dirty
23265                prepareAppDataLIF(pkg, user.id, flags);
23266            }
23267        }
23268    }
23269
23270    /**
23271     * Prepare app data for the given app.
23272     * <p>
23273     * Verifies that directories exist and that ownership and labeling is
23274     * correct for all installed apps. If there is an ownership mismatch, this
23275     * will try recovering system apps by wiping data; third-party app data is
23276     * left intact.
23277     */
23278    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
23279        if (pkg == null) {
23280            Slog.wtf(TAG, "Package was null!", new Throwable());
23281            return;
23282        }
23283        prepareAppDataLeafLIF(pkg, userId, flags);
23284        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23285        for (int i = 0; i < childCount; i++) {
23286            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
23287        }
23288    }
23289
23290    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
23291            boolean maybeMigrateAppData) {
23292        prepareAppDataLIF(pkg, userId, flags);
23293
23294        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
23295            // We may have just shuffled around app data directories, so
23296            // prepare them one more time
23297            prepareAppDataLIF(pkg, userId, flags);
23298        }
23299    }
23300
23301    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23302        if (DEBUG_APP_DATA) {
23303            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
23304                    + Integer.toHexString(flags));
23305        }
23306
23307        final String volumeUuid = pkg.volumeUuid;
23308        final String packageName = pkg.packageName;
23309        final ApplicationInfo app = pkg.applicationInfo;
23310        final int appId = UserHandle.getAppId(app.uid);
23311
23312        Preconditions.checkNotNull(app.seInfo);
23313
23314        long ceDataInode = -1;
23315        try {
23316            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23317                    appId, app.seInfo, app.targetSdkVersion);
23318        } catch (InstallerException e) {
23319            if (app.isSystemApp()) {
23320                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23321                        + ", but trying to recover: " + e);
23322                destroyAppDataLeafLIF(pkg, userId, flags);
23323                try {
23324                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23325                            appId, app.seInfo, app.targetSdkVersion);
23326                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23327                } catch (InstallerException e2) {
23328                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
23329                }
23330            } else {
23331                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23332            }
23333        }
23334
23335        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23336            // TODO: mark this structure as dirty so we persist it!
23337            synchronized (mPackages) {
23338                final PackageSetting ps = mSettings.mPackages.get(packageName);
23339                if (ps != null) {
23340                    ps.setCeDataInode(ceDataInode, userId);
23341                }
23342            }
23343        }
23344
23345        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23346    }
23347
23348    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23349        if (pkg == null) {
23350            Slog.wtf(TAG, "Package was null!", new Throwable());
23351            return;
23352        }
23353        prepareAppDataContentsLeafLIF(pkg, userId, flags);
23354        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23355        for (int i = 0; i < childCount; i++) {
23356            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23357        }
23358    }
23359
23360    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23361        final String volumeUuid = pkg.volumeUuid;
23362        final String packageName = pkg.packageName;
23363        final ApplicationInfo app = pkg.applicationInfo;
23364
23365        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23366            // Create a native library symlink only if we have native libraries
23367            // and if the native libraries are 32 bit libraries. We do not provide
23368            // this symlink for 64 bit libraries.
23369            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23370                final String nativeLibPath = app.nativeLibraryDir;
23371                try {
23372                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23373                            nativeLibPath, userId);
23374                } catch (InstallerException e) {
23375                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23376                }
23377            }
23378        }
23379    }
23380
23381    /**
23382     * For system apps on non-FBE devices, this method migrates any existing
23383     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23384     * requested by the app.
23385     */
23386    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23387        if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated()
23388                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23389            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23390                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23391            try {
23392                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23393                        storageTarget);
23394            } catch (InstallerException e) {
23395                logCriticalInfo(Log.WARN,
23396                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23397            }
23398            return true;
23399        } else {
23400            return false;
23401        }
23402    }
23403
23404    public PackageFreezer freezePackage(String packageName, String killReason) {
23405        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23406    }
23407
23408    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23409        return new PackageFreezer(packageName, userId, killReason);
23410    }
23411
23412    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23413            String killReason) {
23414        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23415    }
23416
23417    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23418            String killReason) {
23419        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23420            return new PackageFreezer();
23421        } else {
23422            return freezePackage(packageName, userId, killReason);
23423        }
23424    }
23425
23426    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23427            String killReason) {
23428        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23429    }
23430
23431    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23432            String killReason) {
23433        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23434            return new PackageFreezer();
23435        } else {
23436            return freezePackage(packageName, userId, killReason);
23437        }
23438    }
23439
23440    /**
23441     * Class that freezes and kills the given package upon creation, and
23442     * unfreezes it upon closing. This is typically used when doing surgery on
23443     * app code/data to prevent the app from running while you're working.
23444     */
23445    private class PackageFreezer implements AutoCloseable {
23446        private final String mPackageName;
23447        private final PackageFreezer[] mChildren;
23448
23449        private final boolean mWeFroze;
23450
23451        private final AtomicBoolean mClosed = new AtomicBoolean();
23452        private final CloseGuard mCloseGuard = CloseGuard.get();
23453
23454        /**
23455         * Create and return a stub freezer that doesn't actually do anything,
23456         * typically used when someone requested
23457         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23458         * {@link PackageManager#DELETE_DONT_KILL_APP}.
23459         */
23460        public PackageFreezer() {
23461            mPackageName = null;
23462            mChildren = null;
23463            mWeFroze = false;
23464            mCloseGuard.open("close");
23465        }
23466
23467        public PackageFreezer(String packageName, int userId, String killReason) {
23468            synchronized (mPackages) {
23469                mPackageName = packageName;
23470                mWeFroze = mFrozenPackages.add(mPackageName);
23471
23472                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23473                if (ps != null) {
23474                    killApplication(ps.name, ps.appId, userId, killReason);
23475                }
23476
23477                final PackageParser.Package p = mPackages.get(packageName);
23478                if (p != null && p.childPackages != null) {
23479                    final int N = p.childPackages.size();
23480                    mChildren = new PackageFreezer[N];
23481                    for (int i = 0; i < N; i++) {
23482                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23483                                userId, killReason);
23484                    }
23485                } else {
23486                    mChildren = null;
23487                }
23488            }
23489            mCloseGuard.open("close");
23490        }
23491
23492        @Override
23493        protected void finalize() throws Throwable {
23494            try {
23495                mCloseGuard.warnIfOpen();
23496                close();
23497            } finally {
23498                super.finalize();
23499            }
23500        }
23501
23502        @Override
23503        public void close() {
23504            mCloseGuard.close();
23505            if (mClosed.compareAndSet(false, true)) {
23506                synchronized (mPackages) {
23507                    if (mWeFroze) {
23508                        mFrozenPackages.remove(mPackageName);
23509                    }
23510
23511                    if (mChildren != null) {
23512                        for (PackageFreezer freezer : mChildren) {
23513                            freezer.close();
23514                        }
23515                    }
23516                }
23517            }
23518        }
23519    }
23520
23521    /**
23522     * Verify that given package is currently frozen.
23523     */
23524    private void checkPackageFrozen(String packageName) {
23525        synchronized (mPackages) {
23526            if (!mFrozenPackages.contains(packageName)) {
23527                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23528            }
23529        }
23530    }
23531
23532    @Override
23533    public int movePackage(final String packageName, final String volumeUuid) {
23534        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23535
23536        final int callingUid = Binder.getCallingUid();
23537        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23538        final int moveId = mNextMoveId.getAndIncrement();
23539        mHandler.post(new Runnable() {
23540            @Override
23541            public void run() {
23542                try {
23543                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23544                } catch (PackageManagerException e) {
23545                    Slog.w(TAG, "Failed to move " + packageName, e);
23546                    mMoveCallbacks.notifyStatusChanged(moveId,
23547                            PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23548                }
23549            }
23550        });
23551        return moveId;
23552    }
23553
23554    private void movePackageInternal(final String packageName, final String volumeUuid,
23555            final int moveId, final int callingUid, UserHandle user)
23556                    throws PackageManagerException {
23557        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23558        final PackageManager pm = mContext.getPackageManager();
23559
23560        final boolean currentAsec;
23561        final String currentVolumeUuid;
23562        final File codeFile;
23563        final String installerPackageName;
23564        final String packageAbiOverride;
23565        final int appId;
23566        final String seinfo;
23567        final String label;
23568        final int targetSdkVersion;
23569        final PackageFreezer freezer;
23570        final int[] installedUserIds;
23571
23572        // reader
23573        synchronized (mPackages) {
23574            final PackageParser.Package pkg = mPackages.get(packageName);
23575            final PackageSetting ps = mSettings.mPackages.get(packageName);
23576            if (pkg == null
23577                    || ps == null
23578                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23579                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23580            }
23581            if (pkg.applicationInfo.isSystemApp()) {
23582                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23583                        "Cannot move system application");
23584            }
23585
23586            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23587            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23588                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23589            if (isInternalStorage && !allow3rdPartyOnInternal) {
23590                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23591                        "3rd party apps are not allowed on internal storage");
23592            }
23593
23594            if (pkg.applicationInfo.isExternalAsec()) {
23595                currentAsec = true;
23596                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
23597            } else if (pkg.applicationInfo.isForwardLocked()) {
23598                currentAsec = true;
23599                currentVolumeUuid = "forward_locked";
23600            } else {
23601                currentAsec = false;
23602                currentVolumeUuid = ps.volumeUuid;
23603
23604                final File probe = new File(pkg.codePath);
23605                final File probeOat = new File(probe, "oat");
23606                if (!probe.isDirectory() || !probeOat.isDirectory()) {
23607                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23608                            "Move only supported for modern cluster style installs");
23609                }
23610            }
23611
23612            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23613                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23614                        "Package already moved to " + volumeUuid);
23615            }
23616            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23617                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23618                        "Device admin cannot be moved");
23619            }
23620
23621            if (mFrozenPackages.contains(packageName)) {
23622                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23623                        "Failed to move already frozen package");
23624            }
23625
23626            codeFile = new File(pkg.codePath);
23627            installerPackageName = ps.installerPackageName;
23628            packageAbiOverride = ps.cpuAbiOverrideString;
23629            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23630            seinfo = pkg.applicationInfo.seInfo;
23631            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23632            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23633            freezer = freezePackage(packageName, "movePackageInternal");
23634            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23635        }
23636
23637        final Bundle extras = new Bundle();
23638        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23639        extras.putString(Intent.EXTRA_TITLE, label);
23640        mMoveCallbacks.notifyCreated(moveId, extras);
23641
23642        int installFlags;
23643        final boolean moveCompleteApp;
23644        final File measurePath;
23645
23646        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23647            installFlags = INSTALL_INTERNAL;
23648            moveCompleteApp = !currentAsec;
23649            measurePath = Environment.getDataAppDirectory(volumeUuid);
23650        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23651            installFlags = INSTALL_EXTERNAL;
23652            moveCompleteApp = false;
23653            measurePath = storage.getPrimaryPhysicalVolume().getPath();
23654        } else {
23655            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23656            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23657                    || !volume.isMountedWritable()) {
23658                freezer.close();
23659                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23660                        "Move location not mounted private volume");
23661            }
23662
23663            Preconditions.checkState(!currentAsec);
23664
23665            installFlags = INSTALL_INTERNAL;
23666            moveCompleteApp = true;
23667            measurePath = Environment.getDataAppDirectory(volumeUuid);
23668        }
23669
23670        final PackageStats stats = new PackageStats(null, -1);
23671        synchronized (mInstaller) {
23672            for (int userId : installedUserIds) {
23673                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23674                    freezer.close();
23675                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23676                            "Failed to measure package size");
23677                }
23678            }
23679        }
23680
23681        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23682                + stats.dataSize);
23683
23684        final long startFreeBytes = measurePath.getUsableSpace();
23685        final long sizeBytes;
23686        if (moveCompleteApp) {
23687            sizeBytes = stats.codeSize + stats.dataSize;
23688        } else {
23689            sizeBytes = stats.codeSize;
23690        }
23691
23692        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23693            freezer.close();
23694            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23695                    "Not enough free space to move");
23696        }
23697
23698        mMoveCallbacks.notifyStatusChanged(moveId, 10);
23699
23700        final CountDownLatch installedLatch = new CountDownLatch(1);
23701        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23702            @Override
23703            public void onUserActionRequired(Intent intent) throws RemoteException {
23704                throw new IllegalStateException();
23705            }
23706
23707            @Override
23708            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23709                    Bundle extras) throws RemoteException {
23710                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23711                        + PackageManager.installStatusToString(returnCode, msg));
23712
23713                installedLatch.countDown();
23714                freezer.close();
23715
23716                final int status = PackageManager.installStatusToPublicStatus(returnCode);
23717                switch (status) {
23718                    case PackageInstaller.STATUS_SUCCESS:
23719                        mMoveCallbacks.notifyStatusChanged(moveId,
23720                                PackageManager.MOVE_SUCCEEDED);
23721                        break;
23722                    case PackageInstaller.STATUS_FAILURE_STORAGE:
23723                        mMoveCallbacks.notifyStatusChanged(moveId,
23724                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23725                        break;
23726                    default:
23727                        mMoveCallbacks.notifyStatusChanged(moveId,
23728                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23729                        break;
23730                }
23731            }
23732        };
23733
23734        final MoveInfo move;
23735        if (moveCompleteApp) {
23736            // Kick off a thread to report progress estimates
23737            new Thread() {
23738                @Override
23739                public void run() {
23740                    while (true) {
23741                        try {
23742                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
23743                                break;
23744                            }
23745                        } catch (InterruptedException ignored) {
23746                        }
23747
23748                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23749                        final int progress = 10 + (int) MathUtils.constrain(
23750                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23751                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
23752                    }
23753                }
23754            }.start();
23755
23756            final String dataAppName = codeFile.getName();
23757            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23758                    dataAppName, appId, seinfo, targetSdkVersion);
23759        } else {
23760            move = null;
23761        }
23762
23763        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23764
23765        final Message msg = mHandler.obtainMessage(INIT_COPY);
23766        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23767        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23768                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23769                packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/,
23770                PackageManager.INSTALL_REASON_UNKNOWN);
23771        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23772        msg.obj = params;
23773
23774        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23775                System.identityHashCode(msg.obj));
23776        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23777                System.identityHashCode(msg.obj));
23778
23779        mHandler.sendMessage(msg);
23780    }
23781
23782    @Override
23783    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23784        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23785
23786        final int realMoveId = mNextMoveId.getAndIncrement();
23787        final Bundle extras = new Bundle();
23788        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23789        mMoveCallbacks.notifyCreated(realMoveId, extras);
23790
23791        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23792            @Override
23793            public void onCreated(int moveId, Bundle extras) {
23794                // Ignored
23795            }
23796
23797            @Override
23798            public void onStatusChanged(int moveId, int status, long estMillis) {
23799                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23800            }
23801        };
23802
23803        final StorageManager storage = mContext.getSystemService(StorageManager.class);
23804        storage.setPrimaryStorageUuid(volumeUuid, callback);
23805        return realMoveId;
23806    }
23807
23808    @Override
23809    public int getMoveStatus(int moveId) {
23810        mContext.enforceCallingOrSelfPermission(
23811                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23812        return mMoveCallbacks.mLastStatus.get(moveId);
23813    }
23814
23815    @Override
23816    public void registerMoveCallback(IPackageMoveObserver callback) {
23817        mContext.enforceCallingOrSelfPermission(
23818                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23819        mMoveCallbacks.register(callback);
23820    }
23821
23822    @Override
23823    public void unregisterMoveCallback(IPackageMoveObserver callback) {
23824        mContext.enforceCallingOrSelfPermission(
23825                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23826        mMoveCallbacks.unregister(callback);
23827    }
23828
23829    @Override
23830    public boolean setInstallLocation(int loc) {
23831        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23832                null);
23833        if (getInstallLocation() == loc) {
23834            return true;
23835        }
23836        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23837                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23838            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23839                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23840            return true;
23841        }
23842        return false;
23843   }
23844
23845    @Override
23846    public int getInstallLocation() {
23847        // allow instant app access
23848        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23849                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23850                PackageHelper.APP_INSTALL_AUTO);
23851    }
23852
23853    /** Called by UserManagerService */
23854    void cleanUpUser(UserManagerService userManager, int userHandle) {
23855        synchronized (mPackages) {
23856            mDirtyUsers.remove(userHandle);
23857            mUserNeedsBadging.delete(userHandle);
23858            mSettings.removeUserLPw(userHandle);
23859            mPendingBroadcasts.remove(userHandle);
23860            mInstantAppRegistry.onUserRemovedLPw(userHandle);
23861            removeUnusedPackagesLPw(userManager, userHandle);
23862        }
23863    }
23864
23865    /**
23866     * We're removing userHandle and would like to remove any downloaded packages
23867     * that are no longer in use by any other user.
23868     * @param userHandle the user being removed
23869     */
23870    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23871        final boolean DEBUG_CLEAN_APKS = false;
23872        int [] users = userManager.getUserIds();
23873        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23874        while (psit.hasNext()) {
23875            PackageSetting ps = psit.next();
23876            if (ps.pkg == null) {
23877                continue;
23878            }
23879            final String packageName = ps.pkg.packageName;
23880            // Skip over if system app
23881            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23882                continue;
23883            }
23884            if (DEBUG_CLEAN_APKS) {
23885                Slog.i(TAG, "Checking package " + packageName);
23886            }
23887            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23888            if (keep) {
23889                if (DEBUG_CLEAN_APKS) {
23890                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23891                }
23892            } else {
23893                for (int i = 0; i < users.length; i++) {
23894                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
23895                        keep = true;
23896                        if (DEBUG_CLEAN_APKS) {
23897                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
23898                                    + users[i]);
23899                        }
23900                        break;
23901                    }
23902                }
23903            }
23904            if (!keep) {
23905                if (DEBUG_CLEAN_APKS) {
23906                    Slog.i(TAG, "  Removing package " + packageName);
23907                }
23908                mHandler.post(new Runnable() {
23909                    public void run() {
23910                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23911                                userHandle, 0);
23912                    } //end run
23913                });
23914            }
23915        }
23916    }
23917
23918    /** Called by UserManagerService */
23919    void createNewUser(int userId, String[] disallowedPackages) {
23920        synchronized (mInstallLock) {
23921            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23922        }
23923        synchronized (mPackages) {
23924            scheduleWritePackageRestrictionsLocked(userId);
23925            scheduleWritePackageListLocked(userId);
23926            applyFactoryDefaultBrowserLPw(userId);
23927            primeDomainVerificationsLPw(userId);
23928        }
23929    }
23930
23931    void onNewUserCreated(final int userId) {
23932        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23933        // If permission review for legacy apps is required, we represent
23934        // dagerous permissions for such apps as always granted runtime
23935        // permissions to keep per user flag state whether review is needed.
23936        // Hence, if a new user is added we have to propagate dangerous
23937        // permission grants for these legacy apps.
23938        if (mPermissionReviewRequired) {
23939            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
23940                    | UPDATE_PERMISSIONS_REPLACE_ALL);
23941        }
23942    }
23943
23944    @Override
23945    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23946        mContext.enforceCallingOrSelfPermission(
23947                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23948                "Only package verification agents can read the verifier device identity");
23949
23950        synchronized (mPackages) {
23951            return mSettings.getVerifierDeviceIdentityLPw();
23952        }
23953    }
23954
23955    @Override
23956    public void setPermissionEnforced(String permission, boolean enforced) {
23957        // TODO: Now that we no longer change GID for storage, this should to away.
23958        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23959                "setPermissionEnforced");
23960        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23961            synchronized (mPackages) {
23962                if (mSettings.mReadExternalStorageEnforced == null
23963                        || mSettings.mReadExternalStorageEnforced != enforced) {
23964                    mSettings.mReadExternalStorageEnforced = enforced;
23965                    mSettings.writeLPr();
23966                }
23967            }
23968            // kill any non-foreground processes so we restart them and
23969            // grant/revoke the GID.
23970            final IActivityManager am = ActivityManager.getService();
23971            if (am != null) {
23972                final long token = Binder.clearCallingIdentity();
23973                try {
23974                    am.killProcessesBelowForeground("setPermissionEnforcement");
23975                } catch (RemoteException e) {
23976                } finally {
23977                    Binder.restoreCallingIdentity(token);
23978                }
23979            }
23980        } else {
23981            throw new IllegalArgumentException("No selective enforcement for " + permission);
23982        }
23983    }
23984
23985    @Override
23986    @Deprecated
23987    public boolean isPermissionEnforced(String permission) {
23988        // allow instant applications
23989        return true;
23990    }
23991
23992    @Override
23993    public boolean isStorageLow() {
23994        // allow instant applications
23995        final long token = Binder.clearCallingIdentity();
23996        try {
23997            final DeviceStorageMonitorInternal
23998                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23999            if (dsm != null) {
24000                return dsm.isMemoryLow();
24001            } else {
24002                return false;
24003            }
24004        } finally {
24005            Binder.restoreCallingIdentity(token);
24006        }
24007    }
24008
24009    @Override
24010    public IPackageInstaller getPackageInstaller() {
24011        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24012            return null;
24013        }
24014        return mInstallerService;
24015    }
24016
24017    private boolean userNeedsBadging(int userId) {
24018        int index = mUserNeedsBadging.indexOfKey(userId);
24019        if (index < 0) {
24020            final UserInfo userInfo;
24021            final long token = Binder.clearCallingIdentity();
24022            try {
24023                userInfo = sUserManager.getUserInfo(userId);
24024            } finally {
24025                Binder.restoreCallingIdentity(token);
24026            }
24027            final boolean b;
24028            if (userInfo != null && userInfo.isManagedProfile()) {
24029                b = true;
24030            } else {
24031                b = false;
24032            }
24033            mUserNeedsBadging.put(userId, b);
24034            return b;
24035        }
24036        return mUserNeedsBadging.valueAt(index);
24037    }
24038
24039    @Override
24040    public KeySet getKeySetByAlias(String packageName, String alias) {
24041        if (packageName == null || alias == null) {
24042            return null;
24043        }
24044        synchronized(mPackages) {
24045            final PackageParser.Package pkg = mPackages.get(packageName);
24046            if (pkg == null) {
24047                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24048                throw new IllegalArgumentException("Unknown package: " + packageName);
24049            }
24050            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24051            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
24052                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
24053                throw new IllegalArgumentException("Unknown package: " + packageName);
24054            }
24055            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24056            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
24057        }
24058    }
24059
24060    @Override
24061    public KeySet getSigningKeySet(String packageName) {
24062        if (packageName == null) {
24063            return null;
24064        }
24065        synchronized(mPackages) {
24066            final int callingUid = Binder.getCallingUid();
24067            final int callingUserId = UserHandle.getUserId(callingUid);
24068            final PackageParser.Package pkg = mPackages.get(packageName);
24069            if (pkg == null) {
24070                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24071                throw new IllegalArgumentException("Unknown package: " + packageName);
24072            }
24073            final PackageSetting ps = (PackageSetting) pkg.mExtras;
24074            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
24075                // filter and pretend the package doesn't exist
24076                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
24077                        + ", uid:" + callingUid);
24078                throw new IllegalArgumentException("Unknown package: " + packageName);
24079            }
24080            if (pkg.applicationInfo.uid != callingUid
24081                    && Process.SYSTEM_UID != callingUid) {
24082                throw new SecurityException("May not access signing KeySet of other apps.");
24083            }
24084            KeySetManagerService ksms = mSettings.mKeySetManagerService;
24085            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
24086        }
24087    }
24088
24089    @Override
24090    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
24091        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24092            return false;
24093        }
24094        if (packageName == null || ks == null) {
24095            return false;
24096        }
24097        synchronized(mPackages) {
24098            final PackageParser.Package pkg = mPackages.get(packageName);
24099            if (pkg == null) {
24100                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24101                throw new IllegalArgumentException("Unknown package: " + packageName);
24102            }
24103            IBinder ksh = ks.getToken();
24104            if (ksh instanceof KeySetHandle) {
24105                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24106                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
24107            }
24108            return false;
24109        }
24110    }
24111
24112    @Override
24113    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
24114        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24115            return false;
24116        }
24117        if (packageName == null || ks == null) {
24118            return false;
24119        }
24120        synchronized(mPackages) {
24121            final PackageParser.Package pkg = mPackages.get(packageName);
24122            if (pkg == null) {
24123                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
24124                throw new IllegalArgumentException("Unknown package: " + packageName);
24125            }
24126            IBinder ksh = ks.getToken();
24127            if (ksh instanceof KeySetHandle) {
24128                KeySetManagerService ksms = mSettings.mKeySetManagerService;
24129                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
24130            }
24131            return false;
24132        }
24133    }
24134
24135    private void deletePackageIfUnusedLPr(final String packageName) {
24136        PackageSetting ps = mSettings.mPackages.get(packageName);
24137        if (ps == null) {
24138            return;
24139        }
24140        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
24141            // TODO Implement atomic delete if package is unused
24142            // It is currently possible that the package will be deleted even if it is installed
24143            // after this method returns.
24144            mHandler.post(new Runnable() {
24145                public void run() {
24146                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
24147                            0, PackageManager.DELETE_ALL_USERS);
24148                }
24149            });
24150        }
24151    }
24152
24153    /**
24154     * Check and throw if the given before/after packages would be considered a
24155     * downgrade.
24156     */
24157    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
24158            throws PackageManagerException {
24159        if (after.versionCode < before.mVersionCode) {
24160            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24161                    "Update version code " + after.versionCode + " is older than current "
24162                    + before.mVersionCode);
24163        } else if (after.versionCode == before.mVersionCode) {
24164            if (after.baseRevisionCode < before.baseRevisionCode) {
24165                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24166                        "Update base revision code " + after.baseRevisionCode
24167                        + " is older than current " + before.baseRevisionCode);
24168            }
24169
24170            if (!ArrayUtils.isEmpty(after.splitNames)) {
24171                for (int i = 0; i < after.splitNames.length; i++) {
24172                    final String splitName = after.splitNames[i];
24173                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
24174                    if (j != -1) {
24175                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
24176                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
24177                                    "Update split " + splitName + " revision code "
24178                                    + after.splitRevisionCodes[i] + " is older than current "
24179                                    + before.splitRevisionCodes[j]);
24180                        }
24181                    }
24182                }
24183            }
24184        }
24185    }
24186
24187    private static class MoveCallbacks extends Handler {
24188        private static final int MSG_CREATED = 1;
24189        private static final int MSG_STATUS_CHANGED = 2;
24190
24191        private final RemoteCallbackList<IPackageMoveObserver>
24192                mCallbacks = new RemoteCallbackList<>();
24193
24194        private final SparseIntArray mLastStatus = new SparseIntArray();
24195
24196        public MoveCallbacks(Looper looper) {
24197            super(looper);
24198        }
24199
24200        public void register(IPackageMoveObserver callback) {
24201            mCallbacks.register(callback);
24202        }
24203
24204        public void unregister(IPackageMoveObserver callback) {
24205            mCallbacks.unregister(callback);
24206        }
24207
24208        @Override
24209        public void handleMessage(Message msg) {
24210            final SomeArgs args = (SomeArgs) msg.obj;
24211            final int n = mCallbacks.beginBroadcast();
24212            for (int i = 0; i < n; i++) {
24213                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
24214                try {
24215                    invokeCallback(callback, msg.what, args);
24216                } catch (RemoteException ignored) {
24217                }
24218            }
24219            mCallbacks.finishBroadcast();
24220            args.recycle();
24221        }
24222
24223        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
24224                throws RemoteException {
24225            switch (what) {
24226                case MSG_CREATED: {
24227                    callback.onCreated(args.argi1, (Bundle) args.arg2);
24228                    break;
24229                }
24230                case MSG_STATUS_CHANGED: {
24231                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
24232                    break;
24233                }
24234            }
24235        }
24236
24237        private void notifyCreated(int moveId, Bundle extras) {
24238            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
24239
24240            final SomeArgs args = SomeArgs.obtain();
24241            args.argi1 = moveId;
24242            args.arg2 = extras;
24243            obtainMessage(MSG_CREATED, args).sendToTarget();
24244        }
24245
24246        private void notifyStatusChanged(int moveId, int status) {
24247            notifyStatusChanged(moveId, status, -1);
24248        }
24249
24250        private void notifyStatusChanged(int moveId, int status, long estMillis) {
24251            Slog.v(TAG, "Move " + moveId + " status " + status);
24252
24253            final SomeArgs args = SomeArgs.obtain();
24254            args.argi1 = moveId;
24255            args.argi2 = status;
24256            args.arg3 = estMillis;
24257            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24258
24259            synchronized (mLastStatus) {
24260                mLastStatus.put(moveId, status);
24261            }
24262        }
24263    }
24264
24265    private final static class OnPermissionChangeListeners extends Handler {
24266        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24267
24268        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24269                new RemoteCallbackList<>();
24270
24271        public OnPermissionChangeListeners(Looper looper) {
24272            super(looper);
24273        }
24274
24275        @Override
24276        public void handleMessage(Message msg) {
24277            switch (msg.what) {
24278                case MSG_ON_PERMISSIONS_CHANGED: {
24279                    final int uid = msg.arg1;
24280                    handleOnPermissionsChanged(uid);
24281                } break;
24282            }
24283        }
24284
24285        public void addListenerLocked(IOnPermissionsChangeListener listener) {
24286            mPermissionListeners.register(listener);
24287
24288        }
24289
24290        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24291            mPermissionListeners.unregister(listener);
24292        }
24293
24294        public void onPermissionsChanged(int uid) {
24295            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24296                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24297            }
24298        }
24299
24300        private void handleOnPermissionsChanged(int uid) {
24301            final int count = mPermissionListeners.beginBroadcast();
24302            try {
24303                for (int i = 0; i < count; i++) {
24304                    IOnPermissionsChangeListener callback = mPermissionListeners
24305                            .getBroadcastItem(i);
24306                    try {
24307                        callback.onPermissionsChanged(uid);
24308                    } catch (RemoteException e) {
24309                        Log.e(TAG, "Permission listener is dead", e);
24310                    }
24311                }
24312            } finally {
24313                mPermissionListeners.finishBroadcast();
24314            }
24315        }
24316    }
24317
24318    private class PackageManagerInternalImpl extends PackageManagerInternal {
24319        @Override
24320        public void setLocationPackagesProvider(PackagesProvider provider) {
24321            synchronized (mPackages) {
24322                mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider);
24323            }
24324        }
24325
24326        @Override
24327        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24328            synchronized (mPackages) {
24329                mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider);
24330            }
24331        }
24332
24333        @Override
24334        public void setSmsAppPackagesProvider(PackagesProvider provider) {
24335            synchronized (mPackages) {
24336                mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider);
24337            }
24338        }
24339
24340        @Override
24341        public void setDialerAppPackagesProvider(PackagesProvider provider) {
24342            synchronized (mPackages) {
24343                mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider);
24344            }
24345        }
24346
24347        @Override
24348        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
24349            synchronized (mPackages) {
24350                mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider);
24351            }
24352        }
24353
24354        @Override
24355        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24356            synchronized (mPackages) {
24357                mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider);
24358            }
24359        }
24360
24361        @Override
24362        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
24363            synchronized (mPackages) {
24364                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr(
24365                        packageName, userId);
24366            }
24367        }
24368
24369        @Override
24370        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
24371            synchronized (mPackages) {
24372                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
24373                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr(
24374                        packageName, userId);
24375            }
24376        }
24377
24378        @Override
24379        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
24380            synchronized (mPackages) {
24381                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr(
24382                        packageName, userId);
24383            }
24384        }
24385
24386        @Override
24387        public void setKeepUninstalledPackages(final List<String> packageList) {
24388            Preconditions.checkNotNull(packageList);
24389            List<String> removedFromList = null;
24390            synchronized (mPackages) {
24391                if (mKeepUninstalledPackages != null) {
24392                    final int packagesCount = mKeepUninstalledPackages.size();
24393                    for (int i = 0; i < packagesCount; i++) {
24394                        String oldPackage = mKeepUninstalledPackages.get(i);
24395                        if (packageList != null && packageList.contains(oldPackage)) {
24396                            continue;
24397                        }
24398                        if (removedFromList == null) {
24399                            removedFromList = new ArrayList<>();
24400                        }
24401                        removedFromList.add(oldPackage);
24402                    }
24403                }
24404                mKeepUninstalledPackages = new ArrayList<>(packageList);
24405                if (removedFromList != null) {
24406                    final int removedCount = removedFromList.size();
24407                    for (int i = 0; i < removedCount; i++) {
24408                        deletePackageIfUnusedLPr(removedFromList.get(i));
24409                    }
24410                }
24411            }
24412        }
24413
24414        @Override
24415        public boolean isPermissionsReviewRequired(String packageName, int userId) {
24416            synchronized (mPackages) {
24417                // If we do not support permission review, done.
24418                if (!mPermissionReviewRequired) {
24419                    return false;
24420                }
24421
24422                PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24423                if (packageSetting == null) {
24424                    return false;
24425                }
24426
24427                // Permission review applies only to apps not supporting the new permission model.
24428                if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) {
24429                    return false;
24430                }
24431
24432                // Legacy apps have the permission and get user consent on launch.
24433                PermissionsState permissionsState = packageSetting.getPermissionsState();
24434                return permissionsState.isPermissionReviewRequired(userId);
24435            }
24436        }
24437
24438        @Override
24439        public PackageInfo getPackageInfo(
24440                String packageName, int flags, int filterCallingUid, int userId) {
24441            return PackageManagerService.this
24442                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24443                            flags, filterCallingUid, userId);
24444        }
24445
24446        @Override
24447        public ApplicationInfo getApplicationInfo(
24448                String packageName, int flags, int filterCallingUid, int userId) {
24449            return PackageManagerService.this
24450                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24451        }
24452
24453        @Override
24454        public ActivityInfo getActivityInfo(
24455                ComponentName component, int flags, int filterCallingUid, int userId) {
24456            return PackageManagerService.this
24457                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24458        }
24459
24460        @Override
24461        public List<ResolveInfo> queryIntentActivities(
24462                Intent intent, int flags, int filterCallingUid, int userId) {
24463            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24464            return PackageManagerService.this
24465                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24466                            userId, false /*resolveForStart*/);
24467        }
24468
24469        @Override
24470        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24471                int userId) {
24472            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24473        }
24474
24475        @Override
24476        public void setDeviceAndProfileOwnerPackages(
24477                int deviceOwnerUserId, String deviceOwnerPackage,
24478                SparseArray<String> profileOwnerPackages) {
24479            mProtectedPackages.setDeviceAndProfileOwnerPackages(
24480                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24481        }
24482
24483        @Override
24484        public boolean isPackageDataProtected(int userId, String packageName) {
24485            return mProtectedPackages.isPackageDataProtected(userId, packageName);
24486        }
24487
24488        @Override
24489        public boolean isPackageEphemeral(int userId, String packageName) {
24490            synchronized (mPackages) {
24491                final PackageSetting ps = mSettings.mPackages.get(packageName);
24492                return ps != null ? ps.getInstantApp(userId) : false;
24493            }
24494        }
24495
24496        @Override
24497        public boolean wasPackageEverLaunched(String packageName, int userId) {
24498            synchronized (mPackages) {
24499                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24500            }
24501        }
24502
24503        @Override
24504        public void grantRuntimePermission(String packageName, String name, int userId,
24505                boolean overridePolicy) {
24506            PackageManagerService.this.grantRuntimePermission(packageName, name, userId,
24507                    overridePolicy);
24508        }
24509
24510        @Override
24511        public void revokeRuntimePermission(String packageName, String name, int userId,
24512                boolean overridePolicy) {
24513            PackageManagerService.this.revokeRuntimePermission(packageName, name, userId,
24514                    overridePolicy);
24515        }
24516
24517        @Override
24518        public String getNameForUid(int uid) {
24519            return PackageManagerService.this.getNameForUid(uid);
24520        }
24521
24522        @Override
24523        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24524                Intent origIntent, String resolvedType, String callingPackage,
24525                Bundle verificationBundle, int userId) {
24526            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24527                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24528                    userId);
24529        }
24530
24531        @Override
24532        public void grantEphemeralAccess(int userId, Intent intent,
24533                int targetAppId, int ephemeralAppId) {
24534            synchronized (mPackages) {
24535                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24536                        targetAppId, ephemeralAppId);
24537            }
24538        }
24539
24540        @Override
24541        public boolean isInstantAppInstallerComponent(ComponentName component) {
24542            synchronized (mPackages) {
24543                return mInstantAppInstallerActivity != null
24544                        && mInstantAppInstallerActivity.getComponentName().equals(component);
24545            }
24546        }
24547
24548        @Override
24549        public void pruneInstantApps() {
24550            mInstantAppRegistry.pruneInstantApps();
24551        }
24552
24553        @Override
24554        public String getSetupWizardPackageName() {
24555            return mSetupWizardPackage;
24556        }
24557
24558        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24559            if (policy != null) {
24560                mExternalSourcesPolicy = policy;
24561            }
24562        }
24563
24564        @Override
24565        public boolean isPackagePersistent(String packageName) {
24566            synchronized (mPackages) {
24567                PackageParser.Package pkg = mPackages.get(packageName);
24568                return pkg != null
24569                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24570                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
24571                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24572                        : false;
24573            }
24574        }
24575
24576        @Override
24577        public List<PackageInfo> getOverlayPackages(int userId) {
24578            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24579            synchronized (mPackages) {
24580                for (PackageParser.Package p : mPackages.values()) {
24581                    if (p.mOverlayTarget != null) {
24582                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24583                        if (pkg != null) {
24584                            overlayPackages.add(pkg);
24585                        }
24586                    }
24587                }
24588            }
24589            return overlayPackages;
24590        }
24591
24592        @Override
24593        public List<String> getTargetPackageNames(int userId) {
24594            List<String> targetPackages = new ArrayList<>();
24595            synchronized (mPackages) {
24596                for (PackageParser.Package p : mPackages.values()) {
24597                    if (p.mOverlayTarget == null) {
24598                        targetPackages.add(p.packageName);
24599                    }
24600                }
24601            }
24602            return targetPackages;
24603        }
24604
24605        @Override
24606        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24607                @Nullable List<String> overlayPackageNames) {
24608            synchronized (mPackages) {
24609                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24610                    Slog.e(TAG, "failed to find package " + targetPackageName);
24611                    return false;
24612                }
24613
24614                ArrayList<String> paths = null;
24615                if (overlayPackageNames != null) {
24616                    final int N = overlayPackageNames.size();
24617                    paths = new ArrayList<>(N);
24618                    for (int i = 0; i < N; i++) {
24619                        final String packageName = overlayPackageNames.get(i);
24620                        final PackageParser.Package pkg = mPackages.get(packageName);
24621                        if (pkg == null) {
24622                            Slog.e(TAG, "failed to find package " + packageName);
24623                            return false;
24624                        }
24625                        paths.add(pkg.baseCodePath);
24626                    }
24627                }
24628
24629                ArrayMap<String, ArrayList<String>> userSpecificOverlays =
24630                    mEnabledOverlayPaths.get(userId);
24631                if (userSpecificOverlays == null) {
24632                    userSpecificOverlays = new ArrayMap<>();
24633                    mEnabledOverlayPaths.put(userId, userSpecificOverlays);
24634                }
24635
24636                if (paths != null && paths.size() > 0) {
24637                    userSpecificOverlays.put(targetPackageName, paths);
24638                } else {
24639                    userSpecificOverlays.remove(targetPackageName);
24640                }
24641                return true;
24642            }
24643        }
24644
24645        @Override
24646        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24647                int flags, int userId) {
24648            return resolveIntentInternal(
24649                    intent, resolvedType, flags, userId, true /*resolveForStart*/);
24650        }
24651
24652        @Override
24653        public ResolveInfo resolveService(Intent intent, String resolvedType,
24654                int flags, int userId, int callingUid) {
24655            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24656        }
24657
24658        @Override
24659        public void addIsolatedUid(int isolatedUid, int ownerUid) {
24660            synchronized (mPackages) {
24661                mIsolatedOwners.put(isolatedUid, ownerUid);
24662            }
24663        }
24664
24665        @Override
24666        public void removeIsolatedUid(int isolatedUid) {
24667            synchronized (mPackages) {
24668                mIsolatedOwners.delete(isolatedUid);
24669            }
24670        }
24671
24672        @Override
24673        public int getUidTargetSdkVersion(int uid) {
24674            synchronized (mPackages) {
24675                return getUidTargetSdkVersionLockedLPr(uid);
24676            }
24677        }
24678
24679        @Override
24680        public boolean canAccessInstantApps(int callingUid, int userId) {
24681            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24682        }
24683    }
24684
24685    @Override
24686    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
24687        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
24688        synchronized (mPackages) {
24689            final long identity = Binder.clearCallingIdentity();
24690            try {
24691                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr(
24692                        packageNames, userId);
24693            } finally {
24694                Binder.restoreCallingIdentity(identity);
24695            }
24696        }
24697    }
24698
24699    @Override
24700    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
24701        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
24702        synchronized (mPackages) {
24703            final long identity = Binder.clearCallingIdentity();
24704            try {
24705                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr(
24706                        packageNames, userId);
24707            } finally {
24708                Binder.restoreCallingIdentity(identity);
24709            }
24710        }
24711    }
24712
24713    private static void enforceSystemOrPhoneCaller(String tag) {
24714        int callingUid = Binder.getCallingUid();
24715        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
24716            throw new SecurityException(
24717                    "Cannot call " + tag + " from UID " + callingUid);
24718        }
24719    }
24720
24721    boolean isHistoricalPackageUsageAvailable() {
24722        return mPackageUsage.isHistoricalPackageUsageAvailable();
24723    }
24724
24725    /**
24726     * Return a <b>copy</b> of the collection of packages known to the package manager.
24727     * @return A copy of the values of mPackages.
24728     */
24729    Collection<PackageParser.Package> getPackages() {
24730        synchronized (mPackages) {
24731            return new ArrayList<>(mPackages.values());
24732        }
24733    }
24734
24735    /**
24736     * Logs process start information (including base APK hash) to the security log.
24737     * @hide
24738     */
24739    @Override
24740    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24741            String apkFile, int pid) {
24742        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24743            return;
24744        }
24745        if (!SecurityLog.isLoggingEnabled()) {
24746            return;
24747        }
24748        Bundle data = new Bundle();
24749        data.putLong("startTimestamp", System.currentTimeMillis());
24750        data.putString("processName", processName);
24751        data.putInt("uid", uid);
24752        data.putString("seinfo", seinfo);
24753        data.putString("apkFile", apkFile);
24754        data.putInt("pid", pid);
24755        Message msg = mProcessLoggingHandler.obtainMessage(
24756                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24757        msg.setData(data);
24758        mProcessLoggingHandler.sendMessage(msg);
24759    }
24760
24761    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24762        return mCompilerStats.getPackageStats(pkgName);
24763    }
24764
24765    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24766        return getOrCreateCompilerPackageStats(pkg.packageName);
24767    }
24768
24769    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24770        return mCompilerStats.getOrCreatePackageStats(pkgName);
24771    }
24772
24773    public void deleteCompilerPackageStats(String pkgName) {
24774        mCompilerStats.deletePackageStats(pkgName);
24775    }
24776
24777    @Override
24778    public int getInstallReason(String packageName, int userId) {
24779        final int callingUid = Binder.getCallingUid();
24780        enforceCrossUserPermission(callingUid, userId,
24781                true /* requireFullPermission */, false /* checkShell */,
24782                "get install reason");
24783        synchronized (mPackages) {
24784            final PackageSetting ps = mSettings.mPackages.get(packageName);
24785            if (filterAppAccessLPr(ps, callingUid, userId)) {
24786                return PackageManager.INSTALL_REASON_UNKNOWN;
24787            }
24788            if (ps != null) {
24789                return ps.getInstallReason(userId);
24790            }
24791        }
24792        return PackageManager.INSTALL_REASON_UNKNOWN;
24793    }
24794
24795    @Override
24796    public boolean canRequestPackageInstalls(String packageName, int userId) {
24797        return canRequestPackageInstallsInternal(packageName, 0, userId,
24798                true /* throwIfPermNotDeclared*/);
24799    }
24800
24801    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24802            boolean throwIfPermNotDeclared) {
24803        int callingUid = Binder.getCallingUid();
24804        int uid = getPackageUid(packageName, 0, userId);
24805        if (callingUid != uid && callingUid != Process.ROOT_UID
24806                && callingUid != Process.SYSTEM_UID) {
24807            throw new SecurityException(
24808                    "Caller uid " + callingUid + " does not own package " + packageName);
24809        }
24810        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24811        if (info == null) {
24812            return false;
24813        }
24814        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24815            return false;
24816        }
24817        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24818        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24819        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24820            if (throwIfPermNotDeclared) {
24821                throw new SecurityException("Need to declare " + appOpPermission
24822                        + " to call this api");
24823            } else {
24824                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24825                return false;
24826            }
24827        }
24828        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24829            return false;
24830        }
24831        if (mExternalSourcesPolicy != null) {
24832            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24833            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24834                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24835            }
24836        }
24837        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24838    }
24839
24840    @Override
24841    public ComponentName getInstantAppResolverSettingsComponent() {
24842        return mInstantAppResolverSettingsComponent;
24843    }
24844
24845    @Override
24846    public ComponentName getInstantAppInstallerComponent() {
24847        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24848            return null;
24849        }
24850        return mInstantAppInstallerActivity == null
24851                ? null : mInstantAppInstallerActivity.getComponentName();
24852    }
24853
24854    @Override
24855    public String getInstantAppAndroidId(String packageName, int userId) {
24856        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24857                "getInstantAppAndroidId");
24858        enforceCrossUserPermission(Binder.getCallingUid(), userId,
24859                true /* requireFullPermission */, false /* checkShell */,
24860                "getInstantAppAndroidId");
24861        // Make sure the target is an Instant App.
24862        if (!isInstantApp(packageName, userId)) {
24863            return null;
24864        }
24865        synchronized (mPackages) {
24866            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24867        }
24868    }
24869}
24870
24871interface PackageSender {
24872    void sendPackageBroadcast(final String action, final String pkg,
24873        final Bundle extras, final int flags, final String targetPkg,
24874        final IIntentReceiver finishedReceiver, final int[] userIds);
24875    void sendPackageAddedForNewUsers(String packageName, boolean isSystem,
24876        int appId, int... userIds);
24877}
24878