PackageManagerService.java revision 021b57ab8df0927aa1f78a2f3bb01d5e70594b1a
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.SET_HARMFUL_APP_WARNINGS;
21import static android.Manifest.permission.INSTALL_PACKAGES;
22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
23import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
25import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
26import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
27import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
33import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
34import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
35import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
36import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
38import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
39import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
41import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
42import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
43import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
44import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
46import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
47import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
48import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
49import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
51import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
52import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
53import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
54import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
55import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
56import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
57import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
58import static android.content.pm.PackageManager.INSTALL_INTERNAL;
59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
65import static android.content.pm.PackageManager.MATCH_ALL;
66import static android.content.pm.PackageManager.MATCH_ANY_USER;
67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
79import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
80import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
81import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
82import static android.content.pm.PackageManager.PERMISSION_DENIED;
83import static android.content.pm.PackageManager.PERMISSION_GRANTED;
84import static android.content.pm.PackageParser.isApkFile;
85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
86import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
87import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
88import static android.system.OsConstants.O_CREAT;
89import static android.system.OsConstants.O_RDWR;
90import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
92import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
93import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
94import static com.android.internal.util.ArrayUtils.appendInt;
95import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
98import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
99import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
101import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
102import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
103import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
104import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
105import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
106import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
107import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
108import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
109import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
110import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE;
111import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS;
112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
113
114import android.Manifest;
115import android.annotation.IntDef;
116import android.annotation.NonNull;
117import android.annotation.Nullable;
118import android.app.ActivityManager;
119import android.app.ActivityManagerInternal;
120import android.app.AppOpsManager;
121import android.app.IActivityManager;
122import android.app.ResourcesManager;
123import android.app.admin.IDevicePolicyManager;
124import android.app.admin.SecurityLog;
125import android.app.backup.IBackupManager;
126import android.content.BroadcastReceiver;
127import android.content.ComponentName;
128import android.content.ContentResolver;
129import android.content.Context;
130import android.content.IIntentReceiver;
131import android.content.Intent;
132import android.content.IntentFilter;
133import android.content.IntentSender;
134import android.content.IntentSender.SendIntentException;
135import android.content.ServiceConnection;
136import android.content.pm.ActivityInfo;
137import android.content.pm.ApplicationInfo;
138import android.content.pm.AppsQueryHelper;
139import android.content.pm.AuxiliaryResolveInfo;
140import android.content.pm.ChangedPackages;
141import android.content.pm.ComponentInfo;
142import android.content.pm.FallbackCategoryProvider;
143import android.content.pm.FeatureInfo;
144import android.content.pm.IDexModuleRegisterCallback;
145import android.content.pm.IOnPermissionsChangeListener;
146import android.content.pm.IPackageDataObserver;
147import android.content.pm.IPackageDeleteObserver;
148import android.content.pm.IPackageDeleteObserver2;
149import android.content.pm.IPackageInstallObserver2;
150import android.content.pm.IPackageInstaller;
151import android.content.pm.IPackageManager;
152import android.content.pm.IPackageManagerNative;
153import android.content.pm.IPackageMoveObserver;
154import android.content.pm.IPackageStatsObserver;
155import android.content.pm.InstantAppInfo;
156import android.content.pm.InstantAppRequest;
157import android.content.pm.InstantAppResolveInfo;
158import android.content.pm.InstrumentationInfo;
159import android.content.pm.IntentFilterVerificationInfo;
160import android.content.pm.KeySet;
161import android.content.pm.PackageCleanItem;
162import android.content.pm.PackageInfo;
163import android.content.pm.PackageInfoLite;
164import android.content.pm.PackageInstaller;
165import android.content.pm.PackageList;
166import android.content.pm.PackageManager;
167import android.content.pm.PackageManagerInternal;
168import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
169import android.content.pm.PackageManagerInternal.PackageListObserver;
170import android.content.pm.PackageParser;
171import android.content.pm.PackageParser.ActivityIntentInfo;
172import android.content.pm.PackageParser.Package;
173import android.content.pm.PackageParser.PackageLite;
174import android.content.pm.PackageParser.PackageParserException;
175import android.content.pm.PackageParser.ParseFlags;
176import android.content.pm.PackageParser.ServiceIntentInfo;
177import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
178import android.content.pm.PackageStats;
179import android.content.pm.PackageUserState;
180import android.content.pm.ParceledListSlice;
181import android.content.pm.PermissionGroupInfo;
182import android.content.pm.PermissionInfo;
183import android.content.pm.ProviderInfo;
184import android.content.pm.ResolveInfo;
185import android.content.pm.ServiceInfo;
186import android.content.pm.SharedLibraryInfo;
187import android.content.pm.Signature;
188import android.content.pm.UserInfo;
189import android.content.pm.VerifierDeviceIdentity;
190import android.content.pm.VerifierInfo;
191import android.content.pm.VersionedPackage;
192import android.content.pm.dex.ArtManager;
193import android.content.pm.dex.DexMetadataHelper;
194import android.content.pm.dex.IArtManager;
195import android.content.res.Resources;
196import android.database.ContentObserver;
197import android.graphics.Bitmap;
198import android.hardware.display.DisplayManager;
199import android.net.Uri;
200import android.os.Binder;
201import android.os.Build;
202import android.os.Bundle;
203import android.os.Debug;
204import android.os.Environment;
205import android.os.Environment.UserEnvironment;
206import android.os.FileUtils;
207import android.os.Handler;
208import android.os.IBinder;
209import android.os.Looper;
210import android.os.Message;
211import android.os.Parcel;
212import android.os.ParcelFileDescriptor;
213import android.os.PatternMatcher;
214import android.os.PersistableBundle;
215import android.os.Process;
216import android.os.RemoteCallbackList;
217import android.os.RemoteException;
218import android.os.ResultReceiver;
219import android.os.SELinux;
220import android.os.ServiceManager;
221import android.os.ShellCallback;
222import android.os.SystemClock;
223import android.os.SystemProperties;
224import android.os.Trace;
225import android.os.UserHandle;
226import android.os.UserManager;
227import android.os.UserManagerInternal;
228import android.os.storage.IStorageManager;
229import android.os.storage.StorageEventListener;
230import android.os.storage.StorageManager;
231import android.os.storage.StorageManagerInternal;
232import android.os.storage.VolumeInfo;
233import android.os.storage.VolumeRecord;
234import android.provider.Settings.Global;
235import android.provider.Settings.Secure;
236import android.security.KeyStore;
237import android.security.SystemKeyStore;
238import android.service.pm.PackageServiceDumpProto;
239import android.system.ErrnoException;
240import android.system.Os;
241import android.text.TextUtils;
242import android.text.format.DateUtils;
243import android.util.ArrayMap;
244import android.util.ArraySet;
245import android.util.Base64;
246import android.util.ByteStringUtils;
247import android.util.DisplayMetrics;
248import android.util.EventLog;
249import android.util.ExceptionUtils;
250import android.util.Log;
251import android.util.LogPrinter;
252import android.util.LongSparseArray;
253import android.util.LongSparseLongArray;
254import android.util.MathUtils;
255import android.util.PackageUtils;
256import android.util.Pair;
257import android.util.PrintStreamPrinter;
258import android.util.Slog;
259import android.util.SparseArray;
260import android.util.SparseBooleanArray;
261import android.util.SparseIntArray;
262import android.util.TimingsTraceLog;
263import android.util.Xml;
264import android.util.jar.StrictJarFile;
265import android.util.proto.ProtoOutputStream;
266import android.view.Display;
267
268import com.android.internal.R;
269import com.android.internal.annotations.GuardedBy;
270import com.android.internal.app.IMediaContainerService;
271import com.android.internal.app.ResolverActivity;
272import com.android.internal.content.NativeLibraryHelper;
273import com.android.internal.content.PackageHelper;
274import com.android.internal.logging.MetricsLogger;
275import com.android.internal.os.IParcelFileDescriptorFactory;
276import com.android.internal.os.SomeArgs;
277import com.android.internal.os.Zygote;
278import com.android.internal.telephony.CarrierAppUtils;
279import com.android.internal.util.ArrayUtils;
280import com.android.internal.util.ConcurrentUtils;
281import com.android.internal.util.DumpUtils;
282import com.android.internal.util.FastXmlSerializer;
283import com.android.internal.util.IndentingPrintWriter;
284import com.android.internal.util.Preconditions;
285import com.android.internal.util.XmlUtils;
286import com.android.server.AttributeCache;
287import com.android.server.DeviceIdleController;
288import com.android.server.EventLogTags;
289import com.android.server.FgThread;
290import com.android.server.IntentResolver;
291import com.android.server.LocalServices;
292import com.android.server.LockGuard;
293import com.android.server.ServiceThread;
294import com.android.server.SystemConfig;
295import com.android.server.SystemServerInitThreadPool;
296import com.android.server.Watchdog;
297import com.android.server.net.NetworkPolicyManagerInternal;
298import com.android.server.pm.Installer.InstallerException;
299import com.android.server.pm.Settings.DatabaseVersion;
300import com.android.server.pm.Settings.VersionInfo;
301import com.android.server.pm.dex.ArtManagerService;
302import com.android.server.pm.dex.DexLogger;
303import com.android.server.pm.dex.DexManager;
304import com.android.server.pm.dex.DexoptOptions;
305import com.android.server.pm.dex.PackageDexUsage;
306import com.android.server.pm.permission.BasePermission;
307import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
308import com.android.server.pm.permission.PermissionManagerService;
309import com.android.server.pm.permission.PermissionManagerInternal;
310import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback;
311import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback;
312import com.android.server.pm.permission.PermissionsState;
313import com.android.server.pm.permission.PermissionsState.PermissionState;
314import com.android.server.security.VerityUtils;
315import com.android.server.storage.DeviceStorageMonitorInternal;
316
317import dalvik.system.CloseGuard;
318import dalvik.system.VMRuntime;
319
320import libcore.io.IoUtils;
321
322import org.xmlpull.v1.XmlPullParser;
323import org.xmlpull.v1.XmlPullParserException;
324import org.xmlpull.v1.XmlSerializer;
325
326import java.io.BufferedOutputStream;
327import java.io.ByteArrayInputStream;
328import java.io.ByteArrayOutputStream;
329import java.io.File;
330import java.io.FileDescriptor;
331import java.io.FileInputStream;
332import java.io.FileOutputStream;
333import java.io.FilenameFilter;
334import java.io.IOException;
335import java.io.PrintWriter;
336import java.lang.annotation.Retention;
337import java.lang.annotation.RetentionPolicy;
338import java.nio.charset.StandardCharsets;
339import java.security.DigestException;
340import java.security.DigestInputStream;
341import java.security.MessageDigest;
342import java.security.NoSuchAlgorithmException;
343import java.security.PublicKey;
344import java.security.SecureRandom;
345import java.security.cert.CertificateException;
346import java.util.ArrayList;
347import java.util.Arrays;
348import java.util.Collection;
349import java.util.Collections;
350import java.util.Comparator;
351import java.util.HashMap;
352import java.util.HashSet;
353import java.util.Iterator;
354import java.util.LinkedHashSet;
355import java.util.List;
356import java.util.Map;
357import java.util.Objects;
358import java.util.Set;
359import java.util.concurrent.CountDownLatch;
360import java.util.concurrent.Future;
361import java.util.concurrent.TimeUnit;
362import java.util.concurrent.atomic.AtomicBoolean;
363import java.util.concurrent.atomic.AtomicInteger;
364
365/**
366 * Keep track of all those APKs everywhere.
367 * <p>
368 * Internally there are two important locks:
369 * <ul>
370 * <li>{@link #mPackages} is used to guard all in-memory parsed package details
371 * and other related state. It is a fine-grained lock that should only be held
372 * momentarily, as it's one of the most contended locks in the system.
373 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
374 * operations typically involve heavy lifting of application data on disk. Since
375 * {@code installd} is single-threaded, and it's operations can often be slow,
376 * this lock should never be acquired while already holding {@link #mPackages}.
377 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
378 * holding {@link #mInstallLock}.
379 * </ul>
380 * Many internal methods rely on the caller to hold the appropriate locks, and
381 * this contract is expressed through method name suffixes:
382 * <ul>
383 * <li>fooLI(): the caller must hold {@link #mInstallLock}
384 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
385 * being modified must be frozen
386 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
387 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
388 * </ul>
389 * <p>
390 * Because this class is very central to the platform's security; please run all
391 * CTS and unit tests whenever making modifications:
392 *
393 * <pre>
394 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
395 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
396 * </pre>
397 */
398public class PackageManagerService extends IPackageManager.Stub
399        implements PackageSender {
400    static final String TAG = "PackageManager";
401    public static final boolean DEBUG_SETTINGS = false;
402    static final boolean DEBUG_PREFERRED = false;
403    static final boolean DEBUG_UPGRADE = false;
404    static final boolean DEBUG_DOMAIN_VERIFICATION = false;
405    private static final boolean DEBUG_BACKUP = false;
406    public static final boolean DEBUG_INSTALL = false;
407    public static final boolean DEBUG_REMOVE = true;
408    private static final boolean DEBUG_BROADCASTS = false;
409    private static final boolean DEBUG_SHOW_INFO = false;
410    private static final boolean DEBUG_PACKAGE_INFO = false;
411    private static final boolean DEBUG_INTENT_MATCHING = false;
412    public static final boolean DEBUG_PACKAGE_SCANNING = false;
413    private static final boolean DEBUG_VERIFY = false;
414    private static final boolean DEBUG_FILTERS = false;
415    public static final boolean DEBUG_PERMISSIONS = false;
416    private static final boolean DEBUG_SHARED_LIBRARIES = false;
417    public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
418
419    // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
420    // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
421    // user, but by default initialize to this.
422    public static final boolean DEBUG_DEXOPT = false;
423
424    private static final boolean DEBUG_ABI_SELECTION = false;
425    private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
426    private static final boolean DEBUG_TRIAGED_MISSING = false;
427    private static final boolean DEBUG_APP_DATA = false;
428
429    /** REMOVE. According to Svet, this was only used to reset permissions during development. */
430    static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
431
432    private static final boolean HIDE_EPHEMERAL_APIS = false;
433
434    private static final boolean ENABLE_FREE_CACHE_V2 =
435            SystemProperties.getBoolean("fw.free_cache_v2", true);
436
437    private static final int RADIO_UID = Process.PHONE_UID;
438    private static final int LOG_UID = Process.LOG_UID;
439    private static final int NFC_UID = Process.NFC_UID;
440    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
441    private static final int SHELL_UID = Process.SHELL_UID;
442    private static final int SE_UID = Process.SE_UID;
443
444    // Suffix used during package installation when copying/moving
445    // package apks to install directory.
446    private static final String INSTALL_PACKAGE_SUFFIX = "-";
447
448    static final int SCAN_NO_DEX = 1<<0;
449    static final int SCAN_UPDATE_SIGNATURE = 1<<1;
450    static final int SCAN_NEW_INSTALL = 1<<2;
451    static final int SCAN_UPDATE_TIME = 1<<3;
452    static final int SCAN_BOOTING = 1<<4;
453    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6;
454    static final int SCAN_REQUIRE_KNOWN = 1<<7;
455    static final int SCAN_MOVE = 1<<8;
456    static final int SCAN_INITIAL = 1<<9;
457    static final int SCAN_CHECK_ONLY = 1<<10;
458    static final int SCAN_DONT_KILL_APP = 1<<11;
459    static final int SCAN_IGNORE_FROZEN = 1<<12;
460    static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13;
461    static final int SCAN_AS_INSTANT_APP = 1<<14;
462    static final int SCAN_AS_FULL_APP = 1<<15;
463    static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16;
464    static final int SCAN_AS_SYSTEM = 1<<17;
465    static final int SCAN_AS_PRIVILEGED = 1<<18;
466    static final int SCAN_AS_OEM = 1<<19;
467    static final int SCAN_AS_VENDOR = 1<<20;
468    static final int SCAN_AS_PRODUCT = 1<<21;
469
470    @IntDef(flag = true, prefix = { "SCAN_" }, value = {
471            SCAN_NO_DEX,
472            SCAN_UPDATE_SIGNATURE,
473            SCAN_NEW_INSTALL,
474            SCAN_UPDATE_TIME,
475            SCAN_BOOTING,
476            SCAN_DELETE_DATA_ON_FAILURES,
477            SCAN_REQUIRE_KNOWN,
478            SCAN_MOVE,
479            SCAN_INITIAL,
480            SCAN_CHECK_ONLY,
481            SCAN_DONT_KILL_APP,
482            SCAN_IGNORE_FROZEN,
483            SCAN_FIRST_BOOT_OR_UPGRADE,
484            SCAN_AS_INSTANT_APP,
485            SCAN_AS_FULL_APP,
486            SCAN_AS_VIRTUAL_PRELOAD,
487    })
488    @Retention(RetentionPolicy.SOURCE)
489    public @interface ScanFlags {}
490
491    private static final String STATIC_SHARED_LIB_DELIMITER = "_";
492    /** Extension of the compressed packages */
493    public final static String COMPRESSED_EXTENSION = ".gz";
494    /** Suffix of stub packages on the system partition */
495    public final static String STUB_SUFFIX = "-Stub";
496
497    private static final int[] EMPTY_INT_ARRAY = new int[0];
498
499    private static final int TYPE_UNKNOWN = 0;
500    private static final int TYPE_ACTIVITY = 1;
501    private static final int TYPE_RECEIVER = 2;
502    private static final int TYPE_SERVICE = 3;
503    private static final int TYPE_PROVIDER = 4;
504    @IntDef(prefix = { "TYPE_" }, value = {
505            TYPE_UNKNOWN,
506            TYPE_ACTIVITY,
507            TYPE_RECEIVER,
508            TYPE_SERVICE,
509            TYPE_PROVIDER,
510    })
511    @Retention(RetentionPolicy.SOURCE)
512    public @interface ComponentType {}
513
514    /**
515     * Timeout (in milliseconds) after which the watchdog should declare that
516     * our handler thread is wedged.  The usual default for such things is one
517     * minute but we sometimes do very lengthy I/O operations on this thread,
518     * such as installing multi-gigabyte applications, so ours needs to be longer.
519     */
520    static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
521
522    /**
523     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
524     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
525     * settings entry if available, otherwise we use the hardcoded default.  If it's been
526     * more than this long since the last fstrim, we force one during the boot sequence.
527     *
528     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
529     * one gets run at the next available charging+idle time.  This final mandatory
530     * no-fstrim check kicks in only of the other scheduling criteria is never met.
531     */
532    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
533
534    /**
535     * Whether verification is enabled by default.
536     */
537    private static final boolean DEFAULT_VERIFY_ENABLE = true;
538
539    /**
540     * The default maximum time to wait for the verification agent to return in
541     * milliseconds.
542     */
543    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
544
545    /**
546     * The default response for package verification timeout.
547     *
548     * This can be either PackageManager.VERIFICATION_ALLOW or
549     * PackageManager.VERIFICATION_REJECT.
550     */
551    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
552
553    public static final String PLATFORM_PACKAGE_NAME = "android";
554
555    public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
556
557    public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
558            DEFAULT_CONTAINER_PACKAGE,
559            "com.android.defcontainer.DefaultContainerService");
560
561    private static final String KILL_APP_REASON_GIDS_CHANGED =
562            "permission grant or revoke changed gids";
563
564    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
565            "permissions revoked";
566
567    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
568
569    private static final String PACKAGE_SCHEME = "package";
570
571    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
572
573    private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
574
575    private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob";
576
577    /** Canonical intent used to identify what counts as a "web browser" app */
578    private static final Intent sBrowserIntent;
579    static {
580        sBrowserIntent = new Intent();
581        sBrowserIntent.setAction(Intent.ACTION_VIEW);
582        sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
583        sBrowserIntent.setData(Uri.parse("http:"));
584        sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
585    }
586
587    /**
588     * The set of all protected actions [i.e. those actions for which a high priority
589     * intent filter is disallowed].
590     */
591    private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>();
592    static {
593        PROTECTED_ACTIONS.add(Intent.ACTION_SEND);
594        PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO);
595        PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE);
596        PROTECTED_ACTIONS.add(Intent.ACTION_VIEW);
597    }
598
599    // Compilation reasons.
600    public static final int REASON_UNKNOWN = -1;
601    public static final int REASON_FIRST_BOOT = 0;
602    public static final int REASON_BOOT = 1;
603    public static final int REASON_INSTALL = 2;
604    public static final int REASON_BACKGROUND_DEXOPT = 3;
605    public static final int REASON_AB_OTA = 4;
606    public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
607    public static final int REASON_SHARED = 6;
608
609    public static final int REASON_LAST = REASON_SHARED;
610
611    /**
612     * Version number for the package parser cache. Increment this whenever the format or
613     * extent of cached data changes. See {@code PackageParser#setCacheDir}.
614     */
615    private static final String PACKAGE_PARSER_CACHE_VERSION = "1";
616
617    /**
618     * Whether the package parser cache is enabled.
619     */
620    private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
621
622    /**
623     * Permissions required in order to receive instant application lifecycle broadcasts.
624     */
625    private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
626            new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
627
628    final ServiceThread mHandlerThread;
629
630    final PackageHandler mHandler;
631
632    private final ProcessLoggingHandler mProcessLoggingHandler;
633
634    /**
635     * Messages for {@link #mHandler} that need to wait for system ready before
636     * being dispatched.
637     */
638    private ArrayList<Message> mPostSystemReadyMessages;
639
640    final int mSdkVersion = Build.VERSION.SDK_INT;
641
642    final Context mContext;
643    final boolean mFactoryTest;
644    final boolean mOnlyCore;
645    final DisplayMetrics mMetrics;
646    final int mDefParseFlags;
647    final String[] mSeparateProcesses;
648    final boolean mIsUpgrade;
649    final boolean mIsPreNUpgrade;
650    final boolean mIsPreNMR1Upgrade;
651
652    // Have we told the Activity Manager to whitelist the default container service by uid yet?
653    @GuardedBy("mPackages")
654    boolean mDefaultContainerWhitelisted = false;
655
656    @GuardedBy("mPackages")
657    private boolean mDexOptDialogShown;
658
659    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
660    // LOCK HELD.  Can be called with mInstallLock held.
661    @GuardedBy("mInstallLock")
662    final Installer mInstaller;
663
664    /** Directory where installed applications are stored */
665    private static final File sAppInstallDir =
666            new File(Environment.getDataDirectory(), "app");
667    /** Directory where installed application's 32-bit native libraries are copied. */
668    private static final File sAppLib32InstallDir =
669            new File(Environment.getDataDirectory(), "app-lib");
670    /** Directory where code and non-resource assets of forward-locked applications are stored */
671    private static final File sDrmAppPrivateInstallDir =
672            new File(Environment.getDataDirectory(), "app-private");
673
674    // ----------------------------------------------------------------
675
676    // Lock for state used when installing and doing other long running
677    // operations.  Methods that must be called with this lock held have
678    // the suffix "LI".
679    final Object mInstallLock = new Object();
680
681    // ----------------------------------------------------------------
682
683    // Keys are String (package name), values are Package.  This also serves
684    // as the lock for the global state.  Methods that must be called with
685    // this lock held have the prefix "LP".
686    @GuardedBy("mPackages")
687    final ArrayMap<String, PackageParser.Package> mPackages =
688            new ArrayMap<String, PackageParser.Package>();
689
690    final ArrayMap<String, Set<String>> mKnownCodebase =
691            new ArrayMap<String, Set<String>>();
692
693    // Keys are isolated uids and values are the uid of the application
694    // that created the isolated proccess.
695    @GuardedBy("mPackages")
696    final SparseIntArray mIsolatedOwners = new SparseIntArray();
697
698    /**
699     * Tracks new system packages [received in an OTA] that we expect to
700     * find updated user-installed versions. Keys are package name, values
701     * are package location.
702     */
703    final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
704    /**
705     * Tracks high priority intent filters for protected actions. During boot, certain
706     * filter actions are protected and should never be allowed to have a high priority
707     * intent filter for them. However, there is one, and only one exception -- the
708     * setup wizard. It must be able to define a high priority intent filter for these
709     * actions to ensure there are no escapes from the wizard. We need to delay processing
710     * of these during boot as we need to look at all of the system packages in order
711     * to know which component is the setup wizard.
712     */
713    private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>();
714    /**
715     * Whether or not processing protected filters should be deferred.
716     */
717    private boolean mDeferProtectedFilters = true;
718
719    /**
720     * Tracks existing system packages prior to receiving an OTA. Keys are package name.
721     */
722    final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
723    /**
724     * Whether or not system app permissions should be promoted from install to runtime.
725     */
726    boolean mPromoteSystemApps;
727
728    @GuardedBy("mPackages")
729    final Settings mSettings;
730
731    /**
732     * Set of package names that are currently "frozen", which means active
733     * surgery is being done on the code/data for that package. The platform
734     * will refuse to launch frozen packages to avoid race conditions.
735     *
736     * @see PackageFreezer
737     */
738    @GuardedBy("mPackages")
739    final ArraySet<String> mFrozenPackages = new ArraySet<>();
740
741    final ProtectedPackages mProtectedPackages;
742
743    @GuardedBy("mLoadedVolumes")
744    final ArraySet<String> mLoadedVolumes = new ArraySet<>();
745
746    boolean mFirstBoot;
747
748    PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
749
750    @GuardedBy("mAvailableFeatures")
751    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
752
753    private final InstantAppRegistry mInstantAppRegistry;
754
755    @GuardedBy("mPackages")
756    int mChangedPackagesSequenceNumber;
757    /**
758     * List of changed [installed, removed or updated] packages.
759     * mapping from user id -> sequence number -> package name
760     */
761    @GuardedBy("mPackages")
762    final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
763    /**
764     * The sequence number of the last change to a package.
765     * mapping from user id -> package name -> sequence number
766     */
767    @GuardedBy("mPackages")
768    final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
769
770    @GuardedBy("mPackages")
771    final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
772
773    class PackageParserCallback implements PackageParser.Callback {
774        @Override public final boolean hasFeature(String feature) {
775            return PackageManagerService.this.hasSystemFeature(feature, 0);
776        }
777
778        final List<PackageParser.Package> getStaticOverlayPackagesLocked(
779                Collection<PackageParser.Package> allPackages, String targetPackageName) {
780            List<PackageParser.Package> overlayPackages = null;
781            for (PackageParser.Package p : allPackages) {
782                if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
783                    if (overlayPackages == null) {
784                        overlayPackages = new ArrayList<PackageParser.Package>();
785                    }
786                    overlayPackages.add(p);
787                }
788            }
789            if (overlayPackages != null) {
790                Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
791                    public int compare(PackageParser.Package p1, PackageParser.Package p2) {
792                        return p1.mOverlayPriority - p2.mOverlayPriority;
793                    }
794                };
795                Collections.sort(overlayPackages, cmp);
796            }
797            return overlayPackages;
798        }
799
800        @GuardedBy("mInstallLock")
801        final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages,
802                String targetPackageName, String targetPath) {
803            if ("android".equals(targetPackageName)) {
804                // Static RROs targeting to "android", ie framework-res.apk, are already applied by
805                // native AssetManager.
806                return null;
807            }
808            List<PackageParser.Package> overlayPackages =
809                    getStaticOverlayPackagesLocked(allPackages, targetPackageName);
810            if (overlayPackages == null || overlayPackages.isEmpty()) {
811                return null;
812            }
813            List<String> overlayPathList = null;
814            for (PackageParser.Package overlayPackage : overlayPackages) {
815                if (targetPath == null) {
816                    if (overlayPathList == null) {
817                        overlayPathList = new ArrayList<String>();
818                    }
819                    overlayPathList.add(overlayPackage.baseCodePath);
820                    continue;
821                }
822
823                try {
824                    // Creates idmaps for system to parse correctly the Android manifest of the
825                    // target package.
826                    //
827                    // OverlayManagerService will update each of them with a correct gid from its
828                    // target package app id.
829                    mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
830                            UserHandle.getSharedAppGid(
831                                    UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
832                    if (overlayPathList == null) {
833                        overlayPathList = new ArrayList<String>();
834                    }
835                    overlayPathList.add(overlayPackage.baseCodePath);
836                } catch (InstallerException e) {
837                    Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
838                            overlayPackage.baseCodePath);
839                }
840            }
841            return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
842        }
843
844        String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
845            synchronized (mPackages) {
846                return getStaticOverlayPathsLocked(
847                        mPackages.values(), targetPackageName, targetPath);
848            }
849        }
850
851        @Override public final String[] getOverlayApks(String targetPackageName) {
852            return getStaticOverlayPaths(targetPackageName, null);
853        }
854
855        @Override public final String[] getOverlayPaths(String targetPackageName,
856                String targetPath) {
857            return getStaticOverlayPaths(targetPackageName, targetPath);
858        }
859    }
860
861    class ParallelPackageParserCallback extends PackageParserCallback {
862        List<PackageParser.Package> mOverlayPackages = null;
863
864        void findStaticOverlayPackages() {
865            synchronized (mPackages) {
866                for (PackageParser.Package p : mPackages.values()) {
867                    if (p.mOverlayIsStatic) {
868                        if (mOverlayPackages == null) {
869                            mOverlayPackages = new ArrayList<PackageParser.Package>();
870                        }
871                        mOverlayPackages.add(p);
872                    }
873                }
874            }
875        }
876
877        @Override
878        synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
879            // We can trust mOverlayPackages without holding mPackages because package uninstall
880            // can't happen while running parallel parsing.
881            // Moreover holding mPackages on each parsing thread causes dead-lock.
882            return mOverlayPackages == null ? null :
883                    getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath);
884        }
885    }
886
887    final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
888    final ParallelPackageParserCallback mParallelPackageParserCallback =
889            new ParallelPackageParserCallback();
890
891    public static final class SharedLibraryEntry {
892        public final @Nullable String path;
893        public final @Nullable String apk;
894        public final @NonNull SharedLibraryInfo info;
895
896        SharedLibraryEntry(String _path, String _apk, String name, long version, int type,
897                String declaringPackageName, long declaringPackageVersionCode) {
898            path = _path;
899            apk = _apk;
900            info = new SharedLibraryInfo(name, version, type, new VersionedPackage(
901                    declaringPackageName, declaringPackageVersionCode), null);
902        }
903    }
904
905    // Currently known shared libraries.
906    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>();
907    final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage =
908            new ArrayMap<>();
909
910    // All available activities, for your resolving pleasure.
911    final ActivityIntentResolver mActivities =
912            new ActivityIntentResolver();
913
914    // All available receivers, for your resolving pleasure.
915    final ActivityIntentResolver mReceivers =
916            new ActivityIntentResolver();
917
918    // All available services, for your resolving pleasure.
919    final ServiceIntentResolver mServices = new ServiceIntentResolver();
920
921    // All available providers, for your resolving pleasure.
922    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
923
924    // Mapping from provider base names (first directory in content URI codePath)
925    // to the provider information.
926    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
927            new ArrayMap<String, PackageParser.Provider>();
928
929    // Mapping from instrumentation class names to info about them.
930    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
931            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
932
933    // Packages whose data we have transfered into another package, thus
934    // should no longer exist.
935    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
936
937    // Broadcast actions that are only available to the system.
938    @GuardedBy("mProtectedBroadcasts")
939    final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
940
941    /** List of packages waiting for verification. */
942    final SparseArray<PackageVerificationState> mPendingVerification
943            = new SparseArray<PackageVerificationState>();
944
945    final PackageInstallerService mInstallerService;
946
947    final ArtManagerService mArtManagerService;
948
949    private final PackageDexOptimizer mPackageDexOptimizer;
950    // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
951    // is used by other apps).
952    private final DexManager mDexManager;
953
954    private AtomicInteger mNextMoveId = new AtomicInteger();
955    private final MoveCallbacks mMoveCallbacks;
956
957    private final OnPermissionChangeListeners mOnPermissionChangeListeners;
958
959    // Cache of users who need badging.
960    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
961
962    /** Token for keys in mPendingVerification. */
963    private int mPendingVerificationToken = 0;
964
965    volatile boolean mSystemReady;
966    volatile boolean mSafeMode;
967    volatile boolean mHasSystemUidErrors;
968    private volatile boolean mWebInstantAppsDisabled;
969
970    ApplicationInfo mAndroidApplication;
971    final ActivityInfo mResolveActivity = new ActivityInfo();
972    final ResolveInfo mResolveInfo = new ResolveInfo();
973    ComponentName mResolveComponentName;
974    PackageParser.Package mPlatformPackage;
975    ComponentName mCustomResolverComponentName;
976
977    boolean mResolverReplaced = false;
978
979    private final @Nullable ComponentName mIntentFilterVerifierComponent;
980    private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
981
982    private int mIntentFilterVerificationToken = 0;
983
984    /** The service connection to the ephemeral resolver */
985    final InstantAppResolverConnection mInstantAppResolverConnection;
986    /** Component used to show resolver settings for Instant Apps */
987    final ComponentName mInstantAppResolverSettingsComponent;
988
989    /** Activity used to install instant applications */
990    ActivityInfo mInstantAppInstallerActivity;
991    final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
992
993    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
994            = new SparseArray<IntentFilterVerificationState>();
995
996    // TODO remove this and go through mPermissonManager directly
997    final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
998    private final PermissionManagerInternal mPermissionManager;
999
1000    // List of packages names to keep cached, even if they are uninstalled for all users
1001    private List<String> mKeepUninstalledPackages;
1002
1003    private UserManagerInternal mUserManagerInternal;
1004    private ActivityManagerInternal mActivityManagerInternal;
1005
1006    private DeviceIdleController.LocalService mDeviceIdleController;
1007
1008    private File mCacheDir;
1009
1010    private Future<?> mPrepareAppDataFuture;
1011
1012    private static class IFVerificationParams {
1013        PackageParser.Package pkg;
1014        boolean replacing;
1015        int userId;
1016        int verifierUid;
1017
1018        public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
1019                int _userId, int _verifierUid) {
1020            pkg = _pkg;
1021            replacing = _replacing;
1022            userId = _userId;
1023            replacing = _replacing;
1024            verifierUid = _verifierUid;
1025        }
1026    }
1027
1028    private interface IntentFilterVerifier<T extends IntentFilter> {
1029        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
1030                                               T filter, String packageName);
1031        void startVerifications(int userId);
1032        void receiveVerificationResponse(int verificationId);
1033    }
1034
1035    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1036        private Context mContext;
1037        private ComponentName mIntentFilterVerifierComponent;
1038        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
1039
1040        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1041            mContext = context;
1042            mIntentFilterVerifierComponent = verifierComponent;
1043        }
1044
1045        private String getDefaultScheme() {
1046            return IntentFilter.SCHEME_HTTPS;
1047        }
1048
1049        @Override
1050        public void startVerifications(int userId) {
1051            // Launch verifications requests
1052            int count = mCurrentIntentFilterVerifications.size();
1053            for (int n=0; n<count; n++) {
1054                int verificationId = mCurrentIntentFilterVerifications.get(n);
1055                final IntentFilterVerificationState ivs =
1056                        mIntentFilterVerificationStates.get(verificationId);
1057
1058                String packageName = ivs.getPackageName();
1059
1060                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1061                final int filterCount = filters.size();
1062                ArraySet<String> domainsSet = new ArraySet<>();
1063                for (int m=0; m<filterCount; m++) {
1064                    PackageParser.ActivityIntentInfo filter = filters.get(m);
1065                    domainsSet.addAll(filter.getHostsList());
1066                }
1067                synchronized (mPackages) {
1068                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
1069                            packageName, domainsSet) != null) {
1070                        scheduleWriteSettingsLocked();
1071                    }
1072                }
1073                sendVerificationRequest(verificationId, ivs);
1074            }
1075            mCurrentIntentFilterVerifications.clear();
1076        }
1077
1078        private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1079            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1080            verificationIntent.putExtra(
1081                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1082                    verificationId);
1083            verificationIntent.putExtra(
1084                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1085                    getDefaultScheme());
1086            verificationIntent.putExtra(
1087                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1088                    ivs.getHostsString());
1089            verificationIntent.putExtra(
1090                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1091                    ivs.getPackageName());
1092            verificationIntent.setComponent(mIntentFilterVerifierComponent);
1093            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1094
1095            DeviceIdleController.LocalService idleController = getDeviceIdleController();
1096            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1097                    mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(),
1098                    UserHandle.USER_SYSTEM, true, "intent filter verifier");
1099
1100            mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM);
1101            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1102                    "Sending IntentFilter verification broadcast");
1103        }
1104
1105        public void receiveVerificationResponse(int verificationId) {
1106            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1107
1108            final boolean verified = ivs.isVerified();
1109
1110            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1111            final int count = filters.size();
1112            if (DEBUG_DOMAIN_VERIFICATION) {
1113                Slog.i(TAG, "Received verification response " + verificationId
1114                        + " for " + count + " filters, verified=" + verified);
1115            }
1116            for (int n=0; n<count; n++) {
1117                PackageParser.ActivityIntentInfo filter = filters.get(n);
1118                filter.setVerified(verified);
1119
1120                if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1121                        + " verified with result:" + verified + " and hosts:"
1122                        + ivs.getHostsString());
1123            }
1124
1125            mIntentFilterVerificationStates.remove(verificationId);
1126
1127            final String packageName = ivs.getPackageName();
1128            IntentFilterVerificationInfo ivi = null;
1129
1130            synchronized (mPackages) {
1131                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1132            }
1133            if (ivi == null) {
1134                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1135                        + verificationId + " packageName:" + packageName);
1136                return;
1137            }
1138            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1139                    "Updating IntentFilterVerificationInfo for package " + packageName
1140                            +" verificationId:" + verificationId);
1141
1142            synchronized (mPackages) {
1143                if (verified) {
1144                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1145                } else {
1146                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1147                }
1148                scheduleWriteSettingsLocked();
1149
1150                final int userId = ivs.getUserId();
1151                if (userId != UserHandle.USER_ALL) {
1152                    final int userStatus =
1153                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1154
1155                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1156                    boolean needUpdate = false;
1157
1158                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
1159                    // already been set by the User thru the Disambiguation dialog
1160                    switch (userStatus) {
1161                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1162                            if (verified) {
1163                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1164                            } else {
1165                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
1166                            }
1167                            needUpdate = true;
1168                            break;
1169
1170                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1171                            if (verified) {
1172                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1173                                needUpdate = true;
1174                            }
1175                            break;
1176
1177                        default:
1178                            // Nothing to do
1179                    }
1180
1181                    if (needUpdate) {
1182                        mSettings.updateIntentFilterVerificationStatusLPw(
1183                                packageName, updatedStatus, userId);
1184                        scheduleWritePackageRestrictionsLocked(userId);
1185                    }
1186                }
1187            }
1188        }
1189
1190        @Override
1191        public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1192                    ActivityIntentInfo filter, String packageName) {
1193            if (!hasValidDomains(filter)) {
1194                return false;
1195            }
1196            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1197            if (ivs == null) {
1198                ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1199                        packageName);
1200            }
1201            if (DEBUG_DOMAIN_VERIFICATION) {
1202                Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1203            }
1204            ivs.addFilter(filter);
1205            return true;
1206        }
1207
1208        private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1209                int userId, int verificationId, String packageName) {
1210            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1211                    verifierUid, userId, packageName);
1212            ivs.setPendingState();
1213            synchronized (mPackages) {
1214                mIntentFilterVerificationStates.append(verificationId, ivs);
1215                mCurrentIntentFilterVerifications.add(verificationId);
1216            }
1217            return ivs;
1218        }
1219    }
1220
1221    private static boolean hasValidDomains(ActivityIntentInfo filter) {
1222        return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1223                && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1224                        filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1225    }
1226
1227    // Set of pending broadcasts for aggregating enable/disable of components.
1228    static class PendingPackageBroadcasts {
1229        // for each user id, a map of <package name -> components within that package>
1230        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1231
1232        public PendingPackageBroadcasts() {
1233            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
1234        }
1235
1236        public ArrayList<String> get(int userId, String packageName) {
1237            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1238            return packages.get(packageName);
1239        }
1240
1241        public void put(int userId, String packageName, ArrayList<String> components) {
1242            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1243            packages.put(packageName, components);
1244        }
1245
1246        public void remove(int userId, String packageName) {
1247            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1248            if (packages != null) {
1249                packages.remove(packageName);
1250            }
1251        }
1252
1253        public void remove(int userId) {
1254            mUidMap.remove(userId);
1255        }
1256
1257        public int userIdCount() {
1258            return mUidMap.size();
1259        }
1260
1261        public int userIdAt(int n) {
1262            return mUidMap.keyAt(n);
1263        }
1264
1265        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1266            return mUidMap.get(userId);
1267        }
1268
1269        public int size() {
1270            // total number of pending broadcast entries across all userIds
1271            int num = 0;
1272            for (int i = 0; i< mUidMap.size(); i++) {
1273                num += mUidMap.valueAt(i).size();
1274            }
1275            return num;
1276        }
1277
1278        public void clear() {
1279            mUidMap.clear();
1280        }
1281
1282        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1283            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1284            if (map == null) {
1285                map = new ArrayMap<String, ArrayList<String>>();
1286                mUidMap.put(userId, map);
1287            }
1288            return map;
1289        }
1290    }
1291    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1292
1293    // Service Connection to remote media container service to copy
1294    // package uri's from external media onto secure containers
1295    // or internal storage.
1296    private IMediaContainerService mContainerService = null;
1297
1298    static final int SEND_PENDING_BROADCAST = 1;
1299    static final int MCS_BOUND = 3;
1300    static final int END_COPY = 4;
1301    static final int INIT_COPY = 5;
1302    static final int MCS_UNBIND = 6;
1303    static final int START_CLEANING_PACKAGE = 7;
1304    static final int FIND_INSTALL_LOC = 8;
1305    static final int POST_INSTALL = 9;
1306    static final int MCS_RECONNECT = 10;
1307    static final int MCS_GIVE_UP = 11;
1308    static final int WRITE_SETTINGS = 13;
1309    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1310    static final int PACKAGE_VERIFIED = 15;
1311    static final int CHECK_PENDING_VERIFICATION = 16;
1312    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1313    static final int INTENT_FILTER_VERIFIED = 18;
1314    static final int WRITE_PACKAGE_LIST = 19;
1315    static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1316
1317    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1318
1319    // Delay time in millisecs
1320    static final int BROADCAST_DELAY = 10 * 1000;
1321
1322    private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1323            2 * 60 * 60 * 1000L; /* two hours */
1324
1325    static UserManagerService sUserManager;
1326
1327    // Stores a list of users whose package restrictions file needs to be updated
1328    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
1329
1330    final private DefaultContainerConnection mDefContainerConn =
1331            new DefaultContainerConnection();
1332    class DefaultContainerConnection implements ServiceConnection {
1333        public void onServiceConnected(ComponentName name, IBinder service) {
1334            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
1335            final IMediaContainerService imcs = IMediaContainerService.Stub
1336                    .asInterface(Binder.allowBlocking(service));
1337            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
1338        }
1339
1340        public void onServiceDisconnected(ComponentName name) {
1341            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
1342        }
1343    }
1344
1345    // Recordkeeping of restore-after-install operations that are currently in flight
1346    // between the Package Manager and the Backup Manager
1347    static class PostInstallData {
1348        public InstallArgs args;
1349        public PackageInstalledInfo res;
1350
1351        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
1352            args = _a;
1353            res = _r;
1354        }
1355    }
1356
1357    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
1358    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1359
1360    // XML tags for backup/restore of various bits of state
1361    private static final String TAG_PREFERRED_BACKUP = "pa";
1362    private static final String TAG_DEFAULT_APPS = "da";
1363    private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1364
1365    private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1366    private static final String TAG_ALL_GRANTS = "rt-grants";
1367    private static final String TAG_GRANT = "grant";
1368    private static final String ATTR_PACKAGE_NAME = "pkg";
1369
1370    private static final String TAG_PERMISSION = "perm";
1371    private static final String ATTR_PERMISSION_NAME = "name";
1372    private static final String ATTR_IS_GRANTED = "g";
1373    private static final String ATTR_USER_SET = "set";
1374    private static final String ATTR_USER_FIXED = "fixed";
1375    private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1376
1377    // System/policy permission grants are not backed up
1378    private static final int SYSTEM_RUNTIME_GRANT_MASK =
1379            FLAG_PERMISSION_POLICY_FIXED
1380            | FLAG_PERMISSION_SYSTEM_FIXED
1381            | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1382
1383    // And we back up these user-adjusted states
1384    private static final int USER_RUNTIME_GRANT_MASK =
1385            FLAG_PERMISSION_USER_SET
1386            | FLAG_PERMISSION_USER_FIXED
1387            | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1388
1389    final @Nullable String mRequiredVerifierPackage;
1390    final @NonNull String mRequiredInstallerPackage;
1391    final @NonNull String mRequiredUninstallerPackage;
1392    final @Nullable String mSetupWizardPackage;
1393    final @Nullable String mStorageManagerPackage;
1394    final @Nullable String mSystemTextClassifierPackage;
1395    final @NonNull String mServicesSystemSharedLibraryPackageName;
1396    final @NonNull String mSharedSystemSharedLibraryPackageName;
1397
1398    private final PackageUsage mPackageUsage = new PackageUsage();
1399    private final CompilerStats mCompilerStats = new CompilerStats();
1400
1401    class PackageHandler extends Handler {
1402        private boolean mBound = false;
1403        final ArrayList<HandlerParams> mPendingInstalls =
1404            new ArrayList<HandlerParams>();
1405
1406        private boolean connectToService() {
1407            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1408                    " DefaultContainerService");
1409            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1410            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1411            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1412                    Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
1413                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1414                mBound = true;
1415                return true;
1416            }
1417            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1418            return false;
1419        }
1420
1421        private void disconnectService() {
1422            mContainerService = null;
1423            mBound = false;
1424            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1425            mContext.unbindService(mDefContainerConn);
1426            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1427        }
1428
1429        PackageHandler(Looper looper) {
1430            super(looper);
1431        }
1432
1433        public void handleMessage(Message msg) {
1434            try {
1435                doHandleMessage(msg);
1436            } finally {
1437                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1438            }
1439        }
1440
1441        void doHandleMessage(Message msg) {
1442            switch (msg.what) {
1443                case INIT_COPY: {
1444                    HandlerParams params = (HandlerParams) msg.obj;
1445                    int idx = mPendingInstalls.size();
1446                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1447                    // If a bind was already initiated we dont really
1448                    // need to do anything. The pending install
1449                    // will be processed later on.
1450                    if (!mBound) {
1451                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1452                                System.identityHashCode(mHandler));
1453                        // If this is the only one pending we might
1454                        // have to bind to the service again.
1455                        if (!connectToService()) {
1456                            Slog.e(TAG, "Failed to bind to media container service");
1457                            params.serviceError();
1458                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1459                                    System.identityHashCode(mHandler));
1460                            if (params.traceMethod != null) {
1461                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod,
1462                                        params.traceCookie);
1463                            }
1464                            return;
1465                        } else {
1466                            // Once we bind to the service, the first
1467                            // pending request will be processed.
1468                            mPendingInstalls.add(idx, params);
1469                        }
1470                    } else {
1471                        mPendingInstalls.add(idx, params);
1472                        // Already bound to the service. Just make
1473                        // sure we trigger off processing the first request.
1474                        if (idx == 0) {
1475                            mHandler.sendEmptyMessage(MCS_BOUND);
1476                        }
1477                    }
1478                    break;
1479                }
1480                case MCS_BOUND: {
1481                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1482                    if (msg.obj != null) {
1483                        mContainerService = (IMediaContainerService) msg.obj;
1484                        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS",
1485                                System.identityHashCode(mHandler));
1486                    }
1487                    if (mContainerService == null) {
1488                        if (!mBound) {
1489                            // Something seriously wrong since we are not bound and we are not
1490                            // waiting for connection. Bail out.
1491                            Slog.e(TAG, "Cannot bind to media container service");
1492                            for (HandlerParams params : mPendingInstalls) {
1493                                // Indicate service bind error
1494                                params.serviceError();
1495                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1496                                        System.identityHashCode(params));
1497                                if (params.traceMethod != null) {
1498                                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER,
1499                                            params.traceMethod, params.traceCookie);
1500                                }
1501                                return;
1502                            }
1503                            mPendingInstalls.clear();
1504                        } else {
1505                            Slog.w(TAG, "Waiting to connect to media container service");
1506                        }
1507                    } else if (mPendingInstalls.size() > 0) {
1508                        HandlerParams params = mPendingInstalls.get(0);
1509                        if (params != null) {
1510                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1511                                    System.identityHashCode(params));
1512                            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1513                            if (params.startCopy()) {
1514                                // We are done...  look for more work or to
1515                                // go idle.
1516                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1517                                        "Checking for more work or unbind...");
1518                                // Delete pending install
1519                                if (mPendingInstalls.size() > 0) {
1520                                    mPendingInstalls.remove(0);
1521                                }
1522                                if (mPendingInstalls.size() == 0) {
1523                                    if (mBound) {
1524                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1525                                                "Posting delayed MCS_UNBIND");
1526                                        removeMessages(MCS_UNBIND);
1527                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1528                                        // Unbind after a little delay, to avoid
1529                                        // continual thrashing.
1530                                        sendMessageDelayed(ubmsg, 10000);
1531                                    }
1532                                } else {
1533                                    // There are more pending requests in queue.
1534                                    // Just post MCS_BOUND message to trigger processing
1535                                    // of next pending install.
1536                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1537                                            "Posting MCS_BOUND for next work");
1538                                    mHandler.sendEmptyMessage(MCS_BOUND);
1539                                }
1540                            }
1541                            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1542                        }
1543                    } else {
1544                        // Should never happen ideally.
1545                        Slog.w(TAG, "Empty queue");
1546                    }
1547                    break;
1548                }
1549                case MCS_RECONNECT: {
1550                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1551                    if (mPendingInstalls.size() > 0) {
1552                        if (mBound) {
1553                            disconnectService();
1554                        }
1555                        if (!connectToService()) {
1556                            Slog.e(TAG, "Failed to bind to media container service");
1557                            for (HandlerParams params : mPendingInstalls) {
1558                                // Indicate service bind error
1559                                params.serviceError();
1560                                Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1561                                        System.identityHashCode(params));
1562                            }
1563                            mPendingInstalls.clear();
1564                        }
1565                    }
1566                    break;
1567                }
1568                case MCS_UNBIND: {
1569                    // If there is no actual work left, then time to unbind.
1570                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1571
1572                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1573                        if (mBound) {
1574                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1575
1576                            disconnectService();
1577                        }
1578                    } else if (mPendingInstalls.size() > 0) {
1579                        // There are more pending requests in queue.
1580                        // Just post MCS_BOUND message to trigger processing
1581                        // of next pending install.
1582                        mHandler.sendEmptyMessage(MCS_BOUND);
1583                    }
1584
1585                    break;
1586                }
1587                case MCS_GIVE_UP: {
1588                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1589                    HandlerParams params = mPendingInstalls.remove(0);
1590                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1591                            System.identityHashCode(params));
1592                    break;
1593                }
1594                case SEND_PENDING_BROADCAST: {
1595                    String packages[];
1596                    ArrayList<String> components[];
1597                    int size = 0;
1598                    int uids[];
1599                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1600                    synchronized (mPackages) {
1601                        if (mPendingBroadcasts == null) {
1602                            return;
1603                        }
1604                        size = mPendingBroadcasts.size();
1605                        if (size <= 0) {
1606                            // Nothing to be done. Just return
1607                            return;
1608                        }
1609                        packages = new String[size];
1610                        components = new ArrayList[size];
1611                        uids = new int[size];
1612                        int i = 0;  // filling out the above arrays
1613
1614                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1615                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1616                            Iterator<Map.Entry<String, ArrayList<String>>> it
1617                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1618                                            .entrySet().iterator();
1619                            while (it.hasNext() && i < size) {
1620                                Map.Entry<String, ArrayList<String>> ent = it.next();
1621                                packages[i] = ent.getKey();
1622                                components[i] = ent.getValue();
1623                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1624                                uids[i] = (ps != null)
1625                                        ? UserHandle.getUid(packageUserId, ps.appId)
1626                                        : -1;
1627                                i++;
1628                            }
1629                        }
1630                        size = i;
1631                        mPendingBroadcasts.clear();
1632                    }
1633                    // Send broadcasts
1634                    for (int i = 0; i < size; i++) {
1635                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1636                    }
1637                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1638                    break;
1639                }
1640                case START_CLEANING_PACKAGE: {
1641                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1642                    final String packageName = (String)msg.obj;
1643                    final int userId = msg.arg1;
1644                    final boolean andCode = msg.arg2 != 0;
1645                    synchronized (mPackages) {
1646                        if (userId == UserHandle.USER_ALL) {
1647                            int[] users = sUserManager.getUserIds();
1648                            for (int user : users) {
1649                                mSettings.addPackageToCleanLPw(
1650                                        new PackageCleanItem(user, packageName, andCode));
1651                            }
1652                        } else {
1653                            mSettings.addPackageToCleanLPw(
1654                                    new PackageCleanItem(userId, packageName, andCode));
1655                        }
1656                    }
1657                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1658                    startCleaningPackages();
1659                } break;
1660                case POST_INSTALL: {
1661                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1662
1663                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1664                    final boolean didRestore = (msg.arg2 != 0);
1665                    mRunningInstalls.delete(msg.arg1);
1666
1667                    if (data != null) {
1668                        InstallArgs args = data.args;
1669                        PackageInstalledInfo parentRes = data.res;
1670
1671                        final boolean grantPermissions = (args.installFlags
1672                                & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1673                        final boolean killApp = (args.installFlags
1674                                & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1675                        final boolean virtualPreload = ((args.installFlags
1676                                & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1677                        final String[] grantedPermissions = args.installGrantPermissions;
1678
1679                        // Handle the parent package
1680                        handlePackagePostInstall(parentRes, grantPermissions, killApp,
1681                                virtualPreload, grantedPermissions, didRestore,
1682                                args.installerPackageName, args.observer);
1683
1684                        // Handle the child packages
1685                        final int childCount = (parentRes.addedChildPackages != null)
1686                                ? parentRes.addedChildPackages.size() : 0;
1687                        for (int i = 0; i < childCount; i++) {
1688                            PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1689                            handlePackagePostInstall(childRes, grantPermissions, killApp,
1690                                    virtualPreload, grantedPermissions, false /*didRestore*/,
1691                                    args.installerPackageName, args.observer);
1692                        }
1693
1694                        // Log tracing if needed
1695                        if (args.traceMethod != null) {
1696                            Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1697                                    args.traceCookie);
1698                        }
1699                    } else {
1700                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1701                    }
1702
1703                    Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1704                } break;
1705                case WRITE_SETTINGS: {
1706                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1707                    synchronized (mPackages) {
1708                        removeMessages(WRITE_SETTINGS);
1709                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1710                        mSettings.writeLPr();
1711                        mDirtyUsers.clear();
1712                    }
1713                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1714                } break;
1715                case WRITE_PACKAGE_RESTRICTIONS: {
1716                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1717                    synchronized (mPackages) {
1718                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1719                        for (int userId : mDirtyUsers) {
1720                            mSettings.writePackageRestrictionsLPr(userId);
1721                        }
1722                        mDirtyUsers.clear();
1723                    }
1724                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1725                } break;
1726                case WRITE_PACKAGE_LIST: {
1727                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1728                    synchronized (mPackages) {
1729                        removeMessages(WRITE_PACKAGE_LIST);
1730                        mSettings.writePackageListLPr(msg.arg1);
1731                    }
1732                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1733                } break;
1734                case CHECK_PENDING_VERIFICATION: {
1735                    final int verificationId = msg.arg1;
1736                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1737
1738                    if ((state != null) && !state.timeoutExtended()) {
1739                        final InstallArgs args = state.getInstallArgs();
1740                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1741
1742                        Slog.i(TAG, "Verification timed out for " + originUri);
1743                        mPendingVerification.remove(verificationId);
1744
1745                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1746
1747                        final UserHandle user = args.getUser();
1748                        if (getDefaultVerificationResponse(user)
1749                                == PackageManager.VERIFICATION_ALLOW) {
1750                            Slog.i(TAG, "Continuing with installation of " + originUri);
1751                            state.setVerifierResponse(Binder.getCallingUid(),
1752                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1753                            broadcastPackageVerified(verificationId, originUri,
1754                                    PackageManager.VERIFICATION_ALLOW, user);
1755                            try {
1756                                ret = args.copyApk(mContainerService, true);
1757                            } catch (RemoteException e) {
1758                                Slog.e(TAG, "Could not contact the ContainerService");
1759                            }
1760                        } else {
1761                            broadcastPackageVerified(verificationId, originUri,
1762                                    PackageManager.VERIFICATION_REJECT, user);
1763                        }
1764
1765                        Trace.asyncTraceEnd(
1766                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1767
1768                        processPendingInstall(args, ret);
1769                        mHandler.sendEmptyMessage(MCS_UNBIND);
1770                    }
1771                    break;
1772                }
1773                case PACKAGE_VERIFIED: {
1774                    final int verificationId = msg.arg1;
1775
1776                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1777                    if (state == null) {
1778                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1779                        break;
1780                    }
1781
1782                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1783
1784                    state.setVerifierResponse(response.callerUid, response.code);
1785
1786                    if (state.isVerificationComplete()) {
1787                        mPendingVerification.remove(verificationId);
1788
1789                        final InstallArgs args = state.getInstallArgs();
1790                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1791
1792                        int ret;
1793                        if (state.isInstallAllowed()) {
1794                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1795                            broadcastPackageVerified(verificationId, originUri,
1796                                    response.code, state.getInstallArgs().getUser());
1797                            try {
1798                                ret = args.copyApk(mContainerService, true);
1799                            } catch (RemoteException e) {
1800                                Slog.e(TAG, "Could not contact the ContainerService");
1801                            }
1802                        } else {
1803                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1804                        }
1805
1806                        Trace.asyncTraceEnd(
1807                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1808
1809                        processPendingInstall(args, ret);
1810                        mHandler.sendEmptyMessage(MCS_UNBIND);
1811                    }
1812
1813                    break;
1814                }
1815                case START_INTENT_FILTER_VERIFICATIONS: {
1816                    IFVerificationParams params = (IFVerificationParams) msg.obj;
1817                    verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1818                            params.replacing, params.pkg);
1819                    break;
1820                }
1821                case INTENT_FILTER_VERIFIED: {
1822                    final int verificationId = msg.arg1;
1823
1824                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1825                            verificationId);
1826                    if (state == null) {
1827                        Slog.w(TAG, "Invalid IntentFilter verification token "
1828                                + verificationId + " received");
1829                        break;
1830                    }
1831
1832                    final int userId = state.getUserId();
1833
1834                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1835                            "Processing IntentFilter verification with token:"
1836                            + verificationId + " and userId:" + userId);
1837
1838                    final IntentFilterVerificationResponse response =
1839                            (IntentFilterVerificationResponse) msg.obj;
1840
1841                    state.setVerifierResponse(response.callerUid, response.code);
1842
1843                    if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1844                            "IntentFilter verification with token:" + verificationId
1845                            + " and userId:" + userId
1846                            + " is settings verifier response with response code:"
1847                            + response.code);
1848
1849                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1850                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1851                                + response.getFailedDomainsString());
1852                    }
1853
1854                    if (state.isVerificationComplete()) {
1855                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1856                    } else {
1857                        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1858                                "IntentFilter verification with token:" + verificationId
1859                                + " was not said to be complete");
1860                    }
1861
1862                    break;
1863                }
1864                case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1865                    InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1866                            mInstantAppResolverConnection,
1867                            (InstantAppRequest) msg.obj,
1868                            mInstantAppInstallerActivity,
1869                            mHandler);
1870                }
1871            }
1872        }
1873    }
1874
1875    private PermissionCallback mPermissionCallback = new PermissionCallback() {
1876        @Override
1877        public void onGidsChanged(int appId, int userId) {
1878            mHandler.post(new Runnable() {
1879                @Override
1880                public void run() {
1881                    killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
1882                }
1883            });
1884        }
1885        @Override
1886        public void onPermissionGranted(int uid, int userId) {
1887            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1888
1889            // Not critical; if this is lost, the application has to request again.
1890            synchronized (mPackages) {
1891                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1892            }
1893        }
1894        @Override
1895        public void onInstallPermissionGranted() {
1896            synchronized (mPackages) {
1897                scheduleWriteSettingsLocked();
1898            }
1899        }
1900        @Override
1901        public void onPermissionRevoked(int uid, int userId) {
1902            mOnPermissionChangeListeners.onPermissionsChanged(uid);
1903
1904            synchronized (mPackages) {
1905                // Critical; after this call the application should never have the permission
1906                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1907            }
1908
1909            final int appId = UserHandle.getAppId(uid);
1910            killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1911        }
1912        @Override
1913        public void onInstallPermissionRevoked() {
1914            synchronized (mPackages) {
1915                scheduleWriteSettingsLocked();
1916            }
1917        }
1918        @Override
1919        public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1920            synchronized (mPackages) {
1921                for (int userId : updatedUserIds) {
1922                    mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1923                }
1924            }
1925        }
1926        @Override
1927        public void onInstallPermissionUpdated() {
1928            synchronized (mPackages) {
1929                scheduleWriteSettingsLocked();
1930            }
1931        }
1932        @Override
1933        public void onPermissionRemoved() {
1934            synchronized (mPackages) {
1935                mSettings.writeLPr();
1936            }
1937        }
1938    };
1939
1940    private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1941            boolean killApp, boolean virtualPreload, String[] grantedPermissions,
1942            boolean launchedForRestore, String installerPackage,
1943            IPackageInstallObserver2 installObserver) {
1944        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1945            // Send the removed broadcasts
1946            if (res.removedInfo != null) {
1947                res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1948            }
1949
1950            // Now that we successfully installed the package, grant runtime
1951            // permissions if requested before broadcasting the install. Also
1952            // for legacy apps in permission review mode we clear the permission
1953            // review flag which is used to emulate runtime permissions for
1954            // legacy apps.
1955            if (grantPermissions) {
1956                final int callingUid = Binder.getCallingUid();
1957                mPermissionManager.grantRequestedRuntimePermissions(
1958                        res.pkg, res.newUsers, grantedPermissions, callingUid,
1959                        mPermissionCallback);
1960            }
1961
1962            final boolean update = res.removedInfo != null
1963                    && res.removedInfo.removedPackage != null;
1964            final String installerPackageName =
1965                    res.installerPackageName != null
1966                            ? res.installerPackageName
1967                            : res.removedInfo != null
1968                                    ? res.removedInfo.installerPackageName
1969                                    : null;
1970
1971            // If this is the first time we have child packages for a disabled privileged
1972            // app that had no children, we grant requested runtime permissions to the new
1973            // children if the parent on the system image had them already granted.
1974            if (res.pkg.parentPackage != null) {
1975                final int callingUid = Binder.getCallingUid();
1976                mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1977                        res.pkg, callingUid, mPermissionCallback);
1978            }
1979
1980            synchronized (mPackages) {
1981                mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1982            }
1983
1984            final String packageName = res.pkg.applicationInfo.packageName;
1985
1986            // Determine the set of users who are adding this package for
1987            // the first time vs. those who are seeing an update.
1988            int[] firstUserIds = EMPTY_INT_ARRAY;
1989            int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1990            int[] updateUserIds = EMPTY_INT_ARRAY;
1991            int[] instantUserIds = EMPTY_INT_ARRAY;
1992            final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1993            final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1994            for (int newUser : res.newUsers) {
1995                final boolean isInstantApp = ps.getInstantApp(newUser);
1996                if (allNewUsers) {
1997                    if (isInstantApp) {
1998                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1999                    } else {
2000                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2001                    }
2002                    continue;
2003                }
2004                boolean isNew = true;
2005                for (int origUser : res.origUsers) {
2006                    if (origUser == newUser) {
2007                        isNew = false;
2008                        break;
2009                    }
2010                }
2011                if (isNew) {
2012                    if (isInstantApp) {
2013                        firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
2014                    } else {
2015                        firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
2016                    }
2017                } else {
2018                    if (isInstantApp) {
2019                        instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
2020                    } else {
2021                        updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
2022                    }
2023                }
2024            }
2025
2026            // Send installed broadcasts if the package is not a static shared lib.
2027            if (res.pkg.staticSharedLibName == null) {
2028                mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
2029
2030                // Send added for users that see the package for the first time
2031                // sendPackageAddedForNewUsers also deals with system apps
2032                int appId = UserHandle.getAppId(res.uid);
2033                boolean isSystem = res.pkg.applicationInfo.isSystemApp();
2034                sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
2035                        virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
2036
2037                // Send added for users that don't see the package for the first time
2038                Bundle extras = new Bundle(1);
2039                extras.putInt(Intent.EXTRA_UID, res.uid);
2040                if (update) {
2041                    extras.putBoolean(Intent.EXTRA_REPLACING, true);
2042                }
2043                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2044                        extras, 0 /*flags*/,
2045                        null /*targetPackage*/, null /*finishedReceiver*/,
2046                        updateUserIds, instantUserIds);
2047                if (installerPackageName != null) {
2048                    sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
2049                            extras, 0 /*flags*/,
2050                            installerPackageName, null /*finishedReceiver*/,
2051                            updateUserIds, instantUserIds);
2052                }
2053
2054                // Send replaced for users that don't see the package for the first time
2055                if (update) {
2056                    sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
2057                            packageName, extras, 0 /*flags*/,
2058                            null /*targetPackage*/, null /*finishedReceiver*/,
2059                            updateUserIds, instantUserIds);
2060                    if (installerPackageName != null) {
2061                        sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
2062                                extras, 0 /*flags*/,
2063                                installerPackageName, null /*finishedReceiver*/,
2064                                updateUserIds, instantUserIds);
2065                    }
2066                    sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
2067                            null /*package*/, null /*extras*/, 0 /*flags*/,
2068                            packageName /*targetPackage*/,
2069                            null /*finishedReceiver*/, updateUserIds, instantUserIds);
2070                } else if (launchedForRestore && !isSystemApp(res.pkg)) {
2071                    // First-install and we did a restore, so we're responsible for the
2072                    // first-launch broadcast.
2073                    if (DEBUG_BACKUP) {
2074                        Slog.i(TAG, "Post-restore of " + packageName
2075                                + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
2076                    }
2077                    sendFirstLaunchBroadcast(packageName, installerPackage,
2078                            firstUserIds, firstInstantUserIds);
2079                }
2080
2081                // Send broadcast package appeared if forward locked/external for all users
2082                // treat asec-hosted packages like removable media on upgrade
2083                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
2084                    if (DEBUG_INSTALL) {
2085                        Slog.i(TAG, "upgrading pkg " + res.pkg
2086                                + " is ASEC-hosted -> AVAILABLE");
2087                    }
2088                    final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2089                    ArrayList<String> pkgList = new ArrayList<>(1);
2090                    pkgList.add(packageName);
2091                    sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2092                }
2093            }
2094
2095            // Work that needs to happen on first install within each user
2096            if (firstUserIds != null && firstUserIds.length > 0) {
2097                synchronized (mPackages) {
2098                    for (int userId : firstUserIds) {
2099                        // If this app is a browser and it's newly-installed for some
2100                        // users, clear any default-browser state in those users. The
2101                        // app's nature doesn't depend on the user, so we can just check
2102                        // its browser nature in any user and generalize.
2103                        if (packageIsBrowser(packageName, userId)) {
2104                            mSettings.setDefaultBrowserPackageNameLPw(null, userId);
2105                        }
2106
2107                        // We may also need to apply pending (restored) runtime
2108                        // permission grants within these users.
2109                        mSettings.applyPendingPermissionGrantsLPw(packageName, userId);
2110                    }
2111                }
2112            }
2113
2114            if (allNewUsers && !update) {
2115                notifyPackageAdded(packageName);
2116            }
2117
2118            // Log current value of "unknown sources" setting
2119            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2120                    getUnknownSourcesSettings());
2121
2122            // Remove the replaced package's older resources safely now
2123            // We delete after a gc for applications  on sdcard.
2124            if (res.removedInfo != null && res.removedInfo.args != null) {
2125                Runtime.getRuntime().gc();
2126                synchronized (mInstallLock) {
2127                    res.removedInfo.args.doPostDeleteLI(true);
2128                }
2129            } else {
2130                // Force a gc to clear up things. Ask for a background one, it's fine to go on
2131                // and not block here.
2132                VMRuntime.getRuntime().requestConcurrentGC();
2133            }
2134
2135            // Notify DexManager that the package was installed for new users.
2136            // The updated users should already be indexed and the package code paths
2137            // should not change.
2138            // Don't notify the manager for ephemeral apps as they are not expected to
2139            // survive long enough to benefit of background optimizations.
2140            for (int userId : firstUserIds) {
2141                PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2142                // There's a race currently where some install events may interleave with an uninstall.
2143                // This can lead to package info being null (b/36642664).
2144                if (info != null) {
2145                    mDexManager.notifyPackageInstalled(info, userId);
2146                }
2147            }
2148        }
2149
2150        // If someone is watching installs - notify them
2151        if (installObserver != null) {
2152            try {
2153                Bundle extras = extrasForInstallResult(res);
2154                installObserver.onPackageInstalled(res.name, res.returnCode,
2155                        res.returnMsg, extras);
2156            } catch (RemoteException e) {
2157                Slog.i(TAG, "Observer no longer exists.");
2158            }
2159        }
2160    }
2161
2162    private StorageEventListener mStorageListener = new StorageEventListener() {
2163        @Override
2164        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2165            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2166                if (vol.state == VolumeInfo.STATE_MOUNTED) {
2167                    final String volumeUuid = vol.getFsUuid();
2168
2169                    // Clean up any users or apps that were removed or recreated
2170                    // while this volume was missing
2171                    sUserManager.reconcileUsers(volumeUuid);
2172                    reconcileApps(volumeUuid);
2173
2174                    // Clean up any install sessions that expired or were
2175                    // cancelled while this volume was missing
2176                    mInstallerService.onPrivateVolumeMounted(volumeUuid);
2177
2178                    loadPrivatePackages(vol);
2179
2180                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2181                    unloadPrivatePackages(vol);
2182                }
2183            }
2184        }
2185
2186        @Override
2187        public void onVolumeForgotten(String fsUuid) {
2188            if (TextUtils.isEmpty(fsUuid)) {
2189                Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2190                return;
2191            }
2192
2193            // Remove any apps installed on the forgotten volume
2194            synchronized (mPackages) {
2195                final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2196                for (PackageSetting ps : packages) {
2197                    Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2198                    deletePackageVersioned(new VersionedPackage(ps.name,
2199                            PackageManager.VERSION_CODE_HIGHEST),
2200                            new LegacyPackageDeleteObserver(null).getBinder(),
2201                            UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2202                    // Try very hard to release any references to this package
2203                    // so we don't risk the system server being killed due to
2204                    // open FDs
2205                    AttributeCache.instance().removePackage(ps.name);
2206                }
2207
2208                mSettings.onVolumeForgotten(fsUuid);
2209                mSettings.writeLPr();
2210            }
2211        }
2212    };
2213
2214    Bundle extrasForInstallResult(PackageInstalledInfo res) {
2215        Bundle extras = null;
2216        switch (res.returnCode) {
2217            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2218                extras = new Bundle();
2219                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2220                        res.origPermission);
2221                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2222                        res.origPackage);
2223                break;
2224            }
2225            case PackageManager.INSTALL_SUCCEEDED: {
2226                extras = new Bundle();
2227                extras.putBoolean(Intent.EXTRA_REPLACING,
2228                        res.removedInfo != null && res.removedInfo.removedPackage != null);
2229                break;
2230            }
2231        }
2232        return extras;
2233    }
2234
2235    void scheduleWriteSettingsLocked() {
2236        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2237            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2238        }
2239    }
2240
2241    void scheduleWritePackageListLocked(int userId) {
2242        if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2243            Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2244            msg.arg1 = userId;
2245            mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2246        }
2247    }
2248
2249    void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2250        final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2251        scheduleWritePackageRestrictionsLocked(userId);
2252    }
2253
2254    void scheduleWritePackageRestrictionsLocked(int userId) {
2255        final int[] userIds = (userId == UserHandle.USER_ALL)
2256                ? sUserManager.getUserIds() : new int[]{userId};
2257        for (int nextUserId : userIds) {
2258            if (!sUserManager.exists(nextUserId)) return;
2259            mDirtyUsers.add(nextUserId);
2260            if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2261                mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2262            }
2263        }
2264    }
2265
2266    public static PackageManagerService main(Context context, Installer installer,
2267            boolean factoryTest, boolean onlyCore) {
2268        // Self-check for initial settings.
2269        PackageManagerServiceCompilerMapping.checkProperties();
2270
2271        PackageManagerService m = new PackageManagerService(context, installer,
2272                factoryTest, onlyCore);
2273        m.enableSystemUserPackages();
2274        ServiceManager.addService("package", m);
2275        final PackageManagerNative pmn = m.new PackageManagerNative();
2276        ServiceManager.addService("package_native", pmn);
2277        return m;
2278    }
2279
2280    private void enableSystemUserPackages() {
2281        if (!UserManager.isSplitSystemUser()) {
2282            return;
2283        }
2284        // For system user, enable apps based on the following conditions:
2285        // - app is whitelisted or belong to one of these groups:
2286        //   -- system app which has no launcher icons
2287        //   -- system app which has INTERACT_ACROSS_USERS permission
2288        //   -- system IME app
2289        // - app is not in the blacklist
2290        AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2291        Set<String> enableApps = new ArraySet<>();
2292        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2293                | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2294                | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2295        ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2296        enableApps.addAll(wlApps);
2297        enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2298                /* systemAppsOnly */ false, UserHandle.SYSTEM));
2299        ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2300        enableApps.removeAll(blApps);
2301        Log.i(TAG, "Applications installed for system user: " + enableApps);
2302        List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2303                UserHandle.SYSTEM);
2304        final int allAppsSize = allAps.size();
2305        synchronized (mPackages) {
2306            for (int i = 0; i < allAppsSize; i++) {
2307                String pName = allAps.get(i);
2308                PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2309                // Should not happen, but we shouldn't be failing if it does
2310                if (pkgSetting == null) {
2311                    continue;
2312                }
2313                boolean install = enableApps.contains(pName);
2314                if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2315                    Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2316                            + " for system user");
2317                    pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2318                }
2319            }
2320            scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2321        }
2322    }
2323
2324    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2325        DisplayManager displayManager = (DisplayManager) context.getSystemService(
2326                Context.DISPLAY_SERVICE);
2327        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2328    }
2329
2330    /**
2331     * Requests that files preopted on a secondary system partition be copied to the data partition
2332     * if possible.  Note that the actual copying of the files is accomplished by init for security
2333     * reasons. This simply requests that the copy takes place and awaits confirmation of its
2334     * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2335     */
2336    private static void requestCopyPreoptedFiles() {
2337        final int WAIT_TIME_MS = 100;
2338        final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2339        if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2340            SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2341            // We will wait for up to 100 seconds.
2342            final long timeStart = SystemClock.uptimeMillis();
2343            final long timeEnd = timeStart + 100 * 1000;
2344            long timeNow = timeStart;
2345            while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2346                try {
2347                    Thread.sleep(WAIT_TIME_MS);
2348                } catch (InterruptedException e) {
2349                    // Do nothing
2350                }
2351                timeNow = SystemClock.uptimeMillis();
2352                if (timeNow > timeEnd) {
2353                    SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2354                    Slog.wtf(TAG, "cppreopt did not finish!");
2355                    break;
2356                }
2357            }
2358
2359            Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2360        }
2361    }
2362
2363    public PackageManagerService(Context context, Installer installer,
2364            boolean factoryTest, boolean onlyCore) {
2365        LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2366        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2367        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2368                SystemClock.uptimeMillis());
2369
2370        if (mSdkVersion <= 0) {
2371            Slog.w(TAG, "**** ro.build.version.sdk not set!");
2372        }
2373
2374        mContext = context;
2375
2376        mFactoryTest = factoryTest;
2377        mOnlyCore = onlyCore;
2378        mMetrics = new DisplayMetrics();
2379        mInstaller = installer;
2380
2381        // Create sub-components that provide services / data. Order here is important.
2382        synchronized (mInstallLock) {
2383        synchronized (mPackages) {
2384            // Expose private service for system components to use.
2385            LocalServices.addService(
2386                    PackageManagerInternal.class, new PackageManagerInternalImpl());
2387            sUserManager = new UserManagerService(context, this,
2388                    new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2389            mPermissionManager = PermissionManagerService.create(context,
2390                    new DefaultPermissionGrantedCallback() {
2391                        @Override
2392                        public void onDefaultRuntimePermissionsGranted(int userId) {
2393                            synchronized(mPackages) {
2394                                mSettings.onDefaultRuntimePermissionsGrantedLPr(userId);
2395                            }
2396                        }
2397                    }, mPackages /*externalLock*/);
2398            mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2399            mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages);
2400        }
2401        }
2402        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2403                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2404        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2405                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2406        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2407                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2408        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2409                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2410        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2411                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2412        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2413                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2414        mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2415                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2416
2417        String separateProcesses = SystemProperties.get("debug.separate_processes");
2418        if (separateProcesses != null && separateProcesses.length() > 0) {
2419            if ("*".equals(separateProcesses)) {
2420                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2421                mSeparateProcesses = null;
2422                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2423            } else {
2424                mDefParseFlags = 0;
2425                mSeparateProcesses = separateProcesses.split(",");
2426                Slog.w(TAG, "Running with debug.separate_processes: "
2427                        + separateProcesses);
2428            }
2429        } else {
2430            mDefParseFlags = 0;
2431            mSeparateProcesses = null;
2432        }
2433
2434        mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2435                "*dexopt*");
2436        DexManager.Listener dexManagerListener = DexLogger.getListener(this,
2437                installer, mInstallLock);
2438        mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock,
2439                dexManagerListener);
2440        mArtManagerService = new ArtManagerService(this, installer, mInstallLock);
2441        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2442
2443        mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2444                FgThread.get().getLooper());
2445
2446        getDefaultDisplayMetrics(context, mMetrics);
2447
2448        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2449        SystemConfig systemConfig = SystemConfig.getInstance();
2450        mAvailableFeatures = systemConfig.getAvailableFeatures();
2451        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2452
2453        mProtectedPackages = new ProtectedPackages(mContext);
2454
2455        synchronized (mInstallLock) {
2456        // writer
2457        synchronized (mPackages) {
2458            mHandlerThread = new ServiceThread(TAG,
2459                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2460            mHandlerThread.start();
2461            mHandler = new PackageHandler(mHandlerThread.getLooper());
2462            mProcessLoggingHandler = new ProcessLoggingHandler();
2463            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2464            mInstantAppRegistry = new InstantAppRegistry(this);
2465
2466            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
2467            final int builtInLibCount = libConfig.size();
2468            for (int i = 0; i < builtInLibCount; i++) {
2469                String name = libConfig.keyAt(i);
2470                String path = libConfig.valueAt(i);
2471                addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED,
2472                        SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0);
2473            }
2474
2475            SELinuxMMAC.readInstallPolicy();
2476
2477            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2478            mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2479            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2480
2481            // Clean up orphaned packages for which the code path doesn't exist
2482            // and they are an update to a system app - caused by bug/32321269
2483            final int packageSettingCount = mSettings.mPackages.size();
2484            for (int i = packageSettingCount - 1; i >= 0; i--) {
2485                PackageSetting ps = mSettings.mPackages.valueAt(i);
2486                if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2487                        && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2488                    mSettings.mPackages.removeAt(i);
2489                    mSettings.enableSystemPackageLPw(ps.name);
2490                }
2491            }
2492
2493            if (mFirstBoot) {
2494                requestCopyPreoptedFiles();
2495            }
2496
2497            String customResolverActivity = Resources.getSystem().getString(
2498                    R.string.config_customResolverActivity);
2499            if (TextUtils.isEmpty(customResolverActivity)) {
2500                customResolverActivity = null;
2501            } else {
2502                mCustomResolverComponentName = ComponentName.unflattenFromString(
2503                        customResolverActivity);
2504            }
2505
2506            long startTime = SystemClock.uptimeMillis();
2507
2508            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2509                    startTime);
2510
2511            final String bootClassPath = System.getenv("BOOTCLASSPATH");
2512            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2513
2514            if (bootClassPath == null) {
2515                Slog.w(TAG, "No BOOTCLASSPATH found!");
2516            }
2517
2518            if (systemServerClassPath == null) {
2519                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2520            }
2521
2522            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2523
2524            final VersionInfo ver = mSettings.getInternalVersion();
2525            mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2526            if (mIsUpgrade) {
2527                logCriticalInfo(Log.INFO,
2528                        "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2529            }
2530
2531            // when upgrading from pre-M, promote system app permissions from install to runtime
2532            mPromoteSystemApps =
2533                    mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2534
2535            // When upgrading from pre-N, we need to handle package extraction like first boot,
2536            // as there is no profiling data available.
2537            mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2538
2539            mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2540
2541            // save off the names of pre-existing system packages prior to scanning; we don't
2542            // want to automatically grant runtime permissions for new system apps
2543            if (mPromoteSystemApps) {
2544                Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2545                while (pkgSettingIter.hasNext()) {
2546                    PackageSetting ps = pkgSettingIter.next();
2547                    if (isSystemApp(ps)) {
2548                        mExistingSystemPackages.add(ps.name);
2549                    }
2550                }
2551            }
2552
2553            mCacheDir = preparePackageParserCache(mIsUpgrade);
2554
2555            // Set flag to monitor and not change apk file paths when
2556            // scanning install directories.
2557            int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2558
2559            if (mIsUpgrade || mFirstBoot) {
2560                scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2561            }
2562
2563            // Collect vendor/product overlay packages. (Do this before scanning any apps.)
2564            // For security and version matching reason, only consider
2565            // overlay packages if they reside in the right directory.
2566            scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2567                    mDefParseFlags
2568                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2569                    scanFlags
2570                    | SCAN_AS_SYSTEM
2571                    | SCAN_AS_VENDOR,
2572                    0);
2573            scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2574                    mDefParseFlags
2575                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2576                    scanFlags
2577                    | SCAN_AS_SYSTEM
2578                    | SCAN_AS_PRODUCT,
2579                    0);
2580
2581            mParallelPackageParserCallback.findStaticOverlayPackages();
2582
2583            // Find base frameworks (resource packages without code).
2584            scanDirTracedLI(frameworkDir,
2585                    mDefParseFlags
2586                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2587                    scanFlags
2588                    | SCAN_NO_DEX
2589                    | SCAN_AS_SYSTEM
2590                    | SCAN_AS_PRIVILEGED,
2591                    0);
2592
2593            // Collect privileged system packages.
2594            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2595            scanDirTracedLI(privilegedAppDir,
2596                    mDefParseFlags
2597                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2598                    scanFlags
2599                    | SCAN_AS_SYSTEM
2600                    | SCAN_AS_PRIVILEGED,
2601                    0);
2602
2603            // Collect ordinary system packages.
2604            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2605            scanDirTracedLI(systemAppDir,
2606                    mDefParseFlags
2607                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2608                    scanFlags
2609                    | SCAN_AS_SYSTEM,
2610                    0);
2611
2612            // Collect privileged vendor packages.
2613            File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2614            try {
2615                privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2616            } catch (IOException e) {
2617                // failed to look up canonical path, continue with original one
2618            }
2619            scanDirTracedLI(privilegedVendorAppDir,
2620                    mDefParseFlags
2621                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2622                    scanFlags
2623                    | SCAN_AS_SYSTEM
2624                    | SCAN_AS_VENDOR
2625                    | SCAN_AS_PRIVILEGED,
2626                    0);
2627
2628            // Collect ordinary vendor packages.
2629            File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2630            try {
2631                vendorAppDir = vendorAppDir.getCanonicalFile();
2632            } catch (IOException e) {
2633                // failed to look up canonical path, continue with original one
2634            }
2635            scanDirTracedLI(vendorAppDir,
2636                    mDefParseFlags
2637                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2638                    scanFlags
2639                    | SCAN_AS_SYSTEM
2640                    | SCAN_AS_VENDOR,
2641                    0);
2642
2643            // Collect privileged odm packages. /odm is another vendor partition
2644            // other than /vendor.
2645            File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2646                        "priv-app");
2647            try {
2648                privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2649            } catch (IOException e) {
2650                // failed to look up canonical path, continue with original one
2651            }
2652            scanDirTracedLI(privilegedOdmAppDir,
2653                    mDefParseFlags
2654                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2655                    scanFlags
2656                    | SCAN_AS_SYSTEM
2657                    | SCAN_AS_VENDOR
2658                    | SCAN_AS_PRIVILEGED,
2659                    0);
2660
2661            // Collect ordinary odm packages. /odm is another vendor partition
2662            // other than /vendor.
2663            File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2664            try {
2665                odmAppDir = odmAppDir.getCanonicalFile();
2666            } catch (IOException e) {
2667                // failed to look up canonical path, continue with original one
2668            }
2669            scanDirTracedLI(odmAppDir,
2670                    mDefParseFlags
2671                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2672                    scanFlags
2673                    | SCAN_AS_SYSTEM
2674                    | SCAN_AS_VENDOR,
2675                    0);
2676
2677            // Collect all OEM packages.
2678            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2679            scanDirTracedLI(oemAppDir,
2680                    mDefParseFlags
2681                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2682                    scanFlags
2683                    | SCAN_AS_SYSTEM
2684                    | SCAN_AS_OEM,
2685                    0);
2686
2687            // Collected privileged product packages.
2688            File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2689            try {
2690                privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2691            } catch (IOException e) {
2692                // failed to look up canonical path, continue with original one
2693            }
2694            scanDirTracedLI(privilegedProductAppDir,
2695                    mDefParseFlags
2696                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2697                    scanFlags
2698                    | SCAN_AS_SYSTEM
2699                    | SCAN_AS_PRODUCT
2700                    | SCAN_AS_PRIVILEGED,
2701                    0);
2702
2703            // Collect ordinary product packages.
2704            File productAppDir = new File(Environment.getProductDirectory(), "app");
2705            try {
2706                productAppDir = productAppDir.getCanonicalFile();
2707            } catch (IOException e) {
2708                // failed to look up canonical path, continue with original one
2709            }
2710            scanDirTracedLI(productAppDir,
2711                    mDefParseFlags
2712                    | PackageParser.PARSE_IS_SYSTEM_DIR,
2713                    scanFlags
2714                    | SCAN_AS_SYSTEM
2715                    | SCAN_AS_PRODUCT,
2716                    0);
2717
2718            // Prune any system packages that no longer exist.
2719            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2720            // Stub packages must either be replaced with full versions in the /data
2721            // partition or be disabled.
2722            final List<String> stubSystemApps = new ArrayList<>();
2723            if (!mOnlyCore) {
2724                // do this first before mucking with mPackages for the "expecting better" case
2725                final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2726                while (pkgIterator.hasNext()) {
2727                    final PackageParser.Package pkg = pkgIterator.next();
2728                    if (pkg.isStub) {
2729                        stubSystemApps.add(pkg.packageName);
2730                    }
2731                }
2732
2733                final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2734                while (psit.hasNext()) {
2735                    PackageSetting ps = psit.next();
2736
2737                    /*
2738                     * If this is not a system app, it can't be a
2739                     * disable system app.
2740                     */
2741                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2742                        continue;
2743                    }
2744
2745                    /*
2746                     * If the package is scanned, it's not erased.
2747                     */
2748                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2749                    if (scannedPkg != null) {
2750                        /*
2751                         * If the system app is both scanned and in the
2752                         * disabled packages list, then it must have been
2753                         * added via OTA. Remove it from the currently
2754                         * scanned package so the previously user-installed
2755                         * application can be scanned.
2756                         */
2757                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2758                            logCriticalInfo(Log.WARN,
2759                                    "Expecting better updated system app for " + ps.name
2760                                    + "; removing system app.  Last known"
2761                                    + " codePath=" + ps.codePathString
2762                                    + ", versionCode=" + ps.versionCode
2763                                    + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2764                            removePackageLI(scannedPkg, true);
2765                            mExpectingBetter.put(ps.name, ps.codePath);
2766                        }
2767
2768                        continue;
2769                    }
2770
2771                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2772                        psit.remove();
2773                        logCriticalInfo(Log.WARN, "System package " + ps.name
2774                                + " no longer exists; it's data will be wiped");
2775                        // Actual deletion of code and data will be handled by later
2776                        // reconciliation step
2777                    } else {
2778                        // we still have a disabled system package, but, it still might have
2779                        // been removed. check the code path still exists and check there's
2780                        // still a package. the latter can happen if an OTA keeps the same
2781                        // code path, but, changes the package name.
2782                        final PackageSetting disabledPs =
2783                                mSettings.getDisabledSystemPkgLPr(ps.name);
2784                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2785                                || disabledPs.pkg == null) {
2786                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2787                        }
2788                    }
2789                }
2790            }
2791
2792            //delete tmp files
2793            deleteTempPackageFiles();
2794
2795            final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2796
2797            // Remove any shared userIDs that have no associated packages
2798            mSettings.pruneSharedUsersLPw();
2799            final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2800            final int systemPackagesCount = mPackages.size();
2801            Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2802                    + " ms, packageCount: " + systemPackagesCount
2803                    + " , timePerPackage: "
2804                    + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2805                    + " , cached: " + cachedSystemApps);
2806            if (mIsUpgrade && systemPackagesCount > 0) {
2807                MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2808                        ((int) systemScanTime) / systemPackagesCount);
2809            }
2810            if (!mOnlyCore) {
2811                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2812                        SystemClock.uptimeMillis());
2813                scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2814
2815                scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags
2816                        | PackageParser.PARSE_FORWARD_LOCK,
2817                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2818
2819                // Remove disable package settings for updated system apps that were
2820                // removed via an OTA. If the update is no longer present, remove the
2821                // app completely. Otherwise, revoke their system privileges.
2822                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2823                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2824                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2825                    final String msg;
2826                    if (deletedPkg == null) {
2827                        // should have found an update, but, we didn't; remove everything
2828                        msg = "Updated system package " + deletedAppName
2829                                + " no longer exists; removing its data";
2830                        // Actual deletion of code and data will be handled by later
2831                        // reconciliation step
2832                    } else {
2833                        // found an update; revoke system privileges
2834                        msg = "Updated system package + " + deletedAppName
2835                                + " no longer exists; revoking system privileges";
2836
2837                        // Don't do anything if a stub is removed from the system image. If
2838                        // we were to remove the uncompressed version from the /data partition,
2839                        // this is where it'd be done.
2840
2841                        final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2842                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2843                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2844                    }
2845                    logCriticalInfo(Log.WARN, msg);
2846                }
2847
2848                /*
2849                 * Make sure all system apps that we expected to appear on
2850                 * the userdata partition actually showed up. If they never
2851                 * appeared, crawl back and revive the system version.
2852                 */
2853                for (int i = 0; i < mExpectingBetter.size(); i++) {
2854                    final String packageName = mExpectingBetter.keyAt(i);
2855                    if (!mPackages.containsKey(packageName)) {
2856                        final File scanFile = mExpectingBetter.valueAt(i);
2857
2858                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2859                                + " but never showed up; reverting to system");
2860
2861                        final @ParseFlags int reparseFlags;
2862                        final @ScanFlags int rescanFlags;
2863                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2864                            reparseFlags =
2865                                    mDefParseFlags |
2866                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2867                            rescanFlags =
2868                                    scanFlags
2869                                    | SCAN_AS_SYSTEM
2870                                    | SCAN_AS_PRIVILEGED;
2871                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2872                            reparseFlags =
2873                                    mDefParseFlags |
2874                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2875                            rescanFlags =
2876                                    scanFlags
2877                                    | SCAN_AS_SYSTEM;
2878                        } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
2879                                || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
2880                            reparseFlags =
2881                                    mDefParseFlags |
2882                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2883                            rescanFlags =
2884                                    scanFlags
2885                                    | SCAN_AS_SYSTEM
2886                                    | SCAN_AS_VENDOR
2887                                    | SCAN_AS_PRIVILEGED;
2888                        } else if (FileUtils.contains(vendorAppDir, scanFile)
2889                                || FileUtils.contains(odmAppDir, scanFile)) {
2890                            reparseFlags =
2891                                    mDefParseFlags |
2892                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2893                            rescanFlags =
2894                                    scanFlags
2895                                    | SCAN_AS_SYSTEM
2896                                    | SCAN_AS_VENDOR;
2897                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2898                            reparseFlags =
2899                                    mDefParseFlags |
2900                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2901                            rescanFlags =
2902                                    scanFlags
2903                                    | SCAN_AS_SYSTEM
2904                                    | SCAN_AS_OEM;
2905                        } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
2906                            reparseFlags =
2907                                    mDefParseFlags |
2908                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2909                            rescanFlags =
2910                                    scanFlags
2911                                    | SCAN_AS_SYSTEM
2912                                    | SCAN_AS_PRODUCT
2913                                    | SCAN_AS_PRIVILEGED;
2914                        } else if (FileUtils.contains(productAppDir, scanFile)) {
2915                            reparseFlags =
2916                                    mDefParseFlags |
2917                                    PackageParser.PARSE_IS_SYSTEM_DIR;
2918                            rescanFlags =
2919                                    scanFlags
2920                                    | SCAN_AS_SYSTEM
2921                                    | SCAN_AS_PRODUCT;
2922                        } else {
2923                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2924                            continue;
2925                        }
2926
2927                        mSettings.enableSystemPackageLPw(packageName);
2928
2929                        try {
2930                            scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
2931                        } catch (PackageManagerException e) {
2932                            Slog.e(TAG, "Failed to parse original system package: "
2933                                    + e.getMessage());
2934                        }
2935                    }
2936                }
2937
2938                // Uncompress and install any stubbed system applications.
2939                // This must be done last to ensure all stubs are replaced or disabled.
2940                decompressSystemApplications(stubSystemApps, scanFlags);
2941
2942                final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
2943                                - cachedSystemApps;
2944
2945                final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
2946                final int dataPackagesCount = mPackages.size() - systemPackagesCount;
2947                Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
2948                        + " ms, packageCount: " + dataPackagesCount
2949                        + " , timePerPackage: "
2950                        + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
2951                        + " , cached: " + cachedNonSystemApps);
2952                if (mIsUpgrade && dataPackagesCount > 0) {
2953                    MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
2954                            ((int) dataScanTime) / dataPackagesCount);
2955                }
2956            }
2957            mExpectingBetter.clear();
2958
2959            // Resolve the storage manager.
2960            mStorageManagerPackage = getStorageManagerPackageName();
2961
2962            // Resolve protected action filters. Only the setup wizard is allowed to
2963            // have a high priority filter for these actions.
2964            mSetupWizardPackage = getSetupWizardPackageName();
2965            if (mProtectedFilters.size() > 0) {
2966                if (DEBUG_FILTERS && mSetupWizardPackage == null) {
2967                    Slog.i(TAG, "No setup wizard;"
2968                        + " All protected intents capped to priority 0");
2969                }
2970                for (ActivityIntentInfo filter : mProtectedFilters) {
2971                    if (filter.activity.info.packageName.equals(mSetupWizardPackage)) {
2972                        if (DEBUG_FILTERS) {
2973                            Slog.i(TAG, "Found setup wizard;"
2974                                + " allow priority " + filter.getPriority() + ";"
2975                                + " package: " + filter.activity.info.packageName
2976                                + " activity: " + filter.activity.className
2977                                + " priority: " + filter.getPriority());
2978                        }
2979                        // skip setup wizard; allow it to keep the high priority filter
2980                        continue;
2981                    }
2982                    if (DEBUG_FILTERS) {
2983                        Slog.i(TAG, "Protected action; cap priority to 0;"
2984                                + " package: " + filter.activity.info.packageName
2985                                + " activity: " + filter.activity.className
2986                                + " origPrio: " + filter.getPriority());
2987                    }
2988                    filter.setPriority(0);
2989                }
2990            }
2991
2992            mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
2993
2994            mDeferProtectedFilters = false;
2995            mProtectedFilters.clear();
2996
2997            // Now that we know all of the shared libraries, update all clients to have
2998            // the correct library paths.
2999            updateAllSharedLibrariesLPw(null);
3000
3001            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3002                // NOTE: We ignore potential failures here during a system scan (like
3003                // the rest of the commands above) because there's precious little we
3004                // can do about it. A settings error is reported, though.
3005                final List<String> changedAbiCodePath =
3006                        adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3007                if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3008                    for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3009                        final String codePathString = changedAbiCodePath.get(i);
3010                        try {
3011                            mInstaller.rmdex(codePathString,
3012                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
3013                        } catch (InstallerException ignored) {
3014                        }
3015                    }
3016                }
3017                // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3018                // SELinux domain.
3019                setting.fixSeInfoLocked();
3020            }
3021
3022            // Now that we know all the packages we are keeping,
3023            // read and update their last usage times.
3024            mPackageUsage.read(mPackages);
3025            mCompilerStats.read();
3026
3027            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3028                    SystemClock.uptimeMillis());
3029            Slog.i(TAG, "Time to scan packages: "
3030                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
3031                    + " seconds");
3032
3033            // If the platform SDK has changed since the last time we booted,
3034            // we need to re-grant app permission to catch any new ones that
3035            // appear.  This is really a hack, and means that apps can in some
3036            // cases get permissions that the user didn't initially explicitly
3037            // allow...  it would be nice to have some better way to handle
3038            // this situation.
3039            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3040            if (sdkUpdated) {
3041                Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3042                        + mSdkVersion + "; regranting permissions for internal storage");
3043            }
3044            mPermissionManager.updateAllPermissions(
3045                    StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3046                    mPermissionCallback);
3047            ver.sdkVersion = mSdkVersion;
3048
3049            // If this is the first boot or an update from pre-M, and it is a normal
3050            // boot, then we need to initialize the default preferred apps across
3051            // all defined users.
3052            if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3053                for (UserInfo user : sUserManager.getUsers(true)) {
3054                    mSettings.applyDefaultPreferredAppsLPw(this, user.id);
3055                    applyFactoryDefaultBrowserLPw(user.id);
3056                    primeDomainVerificationsLPw(user.id);
3057                }
3058            }
3059
3060            // Prepare storage for system user really early during boot,
3061            // since core system apps like SettingsProvider and SystemUI
3062            // can't wait for user to start
3063            final int storageFlags;
3064            if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3065                storageFlags = StorageManager.FLAG_STORAGE_DE;
3066            } else {
3067                storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3068            }
3069            List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3070                    UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3071                    true /* onlyCoreApps */);
3072            mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3073                TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3074                        Trace.TRACE_TAG_PACKAGE_MANAGER);
3075                traceLog.traceBegin("AppDataFixup");
3076                try {
3077                    mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3078                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3079                } catch (InstallerException e) {
3080                    Slog.w(TAG, "Trouble fixing GIDs", e);
3081                }
3082                traceLog.traceEnd();
3083
3084                traceLog.traceBegin("AppDataPrepare");
3085                if (deferPackages == null || deferPackages.isEmpty()) {
3086                    return;
3087                }
3088                int count = 0;
3089                for (String pkgName : deferPackages) {
3090                    PackageParser.Package pkg = null;
3091                    synchronized (mPackages) {
3092                        PackageSetting ps = mSettings.getPackageLPr(pkgName);
3093                        if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3094                            pkg = ps.pkg;
3095                        }
3096                    }
3097                    if (pkg != null) {
3098                        synchronized (mInstallLock) {
3099                            prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3100                                    true /* maybeMigrateAppData */);
3101                        }
3102                        count++;
3103                    }
3104                }
3105                traceLog.traceEnd();
3106                Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3107            }, "prepareAppData");
3108
3109            // If this is first boot after an OTA, and a normal boot, then
3110            // we need to clear code cache directories.
3111            // Note that we do *not* clear the application profiles. These remain valid
3112            // across OTAs and are used to drive profile verification (post OTA) and
3113            // profile compilation (without waiting to collect a fresh set of profiles).
3114            if (mIsUpgrade && !onlyCore) {
3115                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3116                for (int i = 0; i < mSettings.mPackages.size(); i++) {
3117                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
3118                    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3119                        // No apps are running this early, so no need to freeze
3120                        clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3121                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
3122                                        | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3123                    }
3124                }
3125                ver.fingerprint = Build.FINGERPRINT;
3126            }
3127
3128            checkDefaultBrowser();
3129
3130            // clear only after permissions and other defaults have been updated
3131            mExistingSystemPackages.clear();
3132            mPromoteSystemApps = false;
3133
3134            // All the changes are done during package scanning.
3135            ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3136
3137            // can downgrade to reader
3138            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3139            mSettings.writeLPr();
3140            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3141            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3142                    SystemClock.uptimeMillis());
3143
3144            if (!mOnlyCore) {
3145                mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3146                mRequiredInstallerPackage = getRequiredInstallerLPr();
3147                mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3148                mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3149                if (mIntentFilterVerifierComponent != null) {
3150                    mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3151                            mIntentFilterVerifierComponent);
3152                } else {
3153                    mIntentFilterVerifier = null;
3154                }
3155                mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3156                        PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3157                        SharedLibraryInfo.VERSION_UNDEFINED);
3158                mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3159                        PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3160                        SharedLibraryInfo.VERSION_UNDEFINED);
3161            } else {
3162                mRequiredVerifierPackage = null;
3163                mRequiredInstallerPackage = null;
3164                mRequiredUninstallerPackage = null;
3165                mIntentFilterVerifierComponent = null;
3166                mIntentFilterVerifier = null;
3167                mServicesSystemSharedLibraryPackageName = null;
3168                mSharedSystemSharedLibraryPackageName = null;
3169            }
3170
3171            mInstallerService = new PackageInstallerService(context, this);
3172            final Pair<ComponentName, String> instantAppResolverComponent =
3173                    getInstantAppResolverLPr();
3174            if (instantAppResolverComponent != null) {
3175                if (DEBUG_INSTANT) {
3176                    Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3177                }
3178                mInstantAppResolverConnection = new InstantAppResolverConnection(
3179                        mContext, instantAppResolverComponent.first,
3180                        instantAppResolverComponent.second);
3181                mInstantAppResolverSettingsComponent =
3182                        getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3183            } else {
3184                mInstantAppResolverConnection = null;
3185                mInstantAppResolverSettingsComponent = null;
3186            }
3187            updateInstantAppInstallerLocked(null);
3188
3189            // Read and update the usage of dex files.
3190            // Do this at the end of PM init so that all the packages have their
3191            // data directory reconciled.
3192            // At this point we know the code paths of the packages, so we can validate
3193            // the disk file and build the internal cache.
3194            // The usage file is expected to be small so loading and verifying it
3195            // should take a fairly small time compare to the other activities (e.g. package
3196            // scanning).
3197            final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3198            final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
3199            for (int userId : currentUserIds) {
3200                userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3201            }
3202            mDexManager.load(userPackages);
3203            if (mIsUpgrade) {
3204                MetricsLogger.histogram(null, "ota_package_manager_init_time",
3205                        (int) (SystemClock.uptimeMillis() - startTime));
3206            }
3207        } // synchronized (mPackages)
3208        } // synchronized (mInstallLock)
3209
3210        // Now after opening every single application zip, make sure they
3211        // are all flushed.  Not really needed, but keeps things nice and
3212        // tidy.
3213        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3214        Runtime.getRuntime().gc();
3215        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3216
3217        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
3218        FallbackCategoryProvider.loadFallbacks();
3219        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3220
3221        // The initial scanning above does many calls into installd while
3222        // holding the mPackages lock, but we're mostly interested in yelling
3223        // once we have a booted system.
3224        mInstaller.setWarnIfHeld(mPackages);
3225
3226        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3227    }
3228
3229    /**
3230     * Uncompress and install stub applications.
3231     * <p>In order to save space on the system partition, some applications are shipped in a
3232     * compressed form. In addition the compressed bits for the full application, the
3233     * system image contains a tiny stub comprised of only the Android manifest.
3234     * <p>During the first boot, attempt to uncompress and install the full application. If
3235     * the application can't be installed for any reason, disable the stub and prevent
3236     * uncompressing the full application during future boots.
3237     * <p>In order to forcefully attempt an installation of a full application, go to app
3238     * settings and enable the application.
3239     */
3240    private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) {
3241        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3242            final String pkgName = stubSystemApps.get(i);
3243            // skip if the system package is already disabled
3244            if (mSettings.isDisabledSystemPackageLPr(pkgName)) {
3245                stubSystemApps.remove(i);
3246                continue;
3247            }
3248            // skip if the package isn't installed (?!); this should never happen
3249            final PackageParser.Package pkg = mPackages.get(pkgName);
3250            if (pkg == null) {
3251                stubSystemApps.remove(i);
3252                continue;
3253            }
3254            // skip if the package has been disabled by the user
3255            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3256            if (ps != null) {
3257                final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3258                if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3259                    stubSystemApps.remove(i);
3260                    continue;
3261                }
3262            }
3263
3264            if (DEBUG_COMPRESSION) {
3265                Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName);
3266            }
3267
3268            // uncompress the binary to its eventual destination on /data
3269            final File scanFile = decompressPackage(pkg);
3270            if (scanFile == null) {
3271                continue;
3272            }
3273
3274            // install the package to replace the stub on /system
3275            try {
3276                mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/);
3277                removePackageLI(pkg, true /*chatty*/);
3278                scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null);
3279                ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3280                        UserHandle.USER_SYSTEM, "android");
3281                stubSystemApps.remove(i);
3282                continue;
3283            } catch (PackageManagerException e) {
3284                Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3285            }
3286
3287            // any failed attempt to install the package will be cleaned up later
3288        }
3289
3290        // disable any stub still left; these failed to install the full application
3291        for (int i = stubSystemApps.size() - 1; i >= 0; --i) {
3292            final String pkgName = stubSystemApps.get(i);
3293            final PackageSetting ps = mSettings.mPackages.get(pkgName);
3294            ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3295                    UserHandle.USER_SYSTEM, "android");
3296            logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3297        }
3298    }
3299
3300    /**
3301     * Decompresses the given package on the system image onto
3302     * the /data partition.
3303     * @return The directory the package was decompressed into. Otherwise, {@code null}.
3304     */
3305    private File decompressPackage(PackageParser.Package pkg) {
3306        final File[] compressedFiles = getCompressedFiles(pkg.codePath);
3307        if (compressedFiles == null || compressedFiles.length == 0) {
3308            if (DEBUG_COMPRESSION) {
3309                Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath);
3310            }
3311            return null;
3312        }
3313        final File dstCodePath =
3314                getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName);
3315        int ret = PackageManager.INSTALL_SUCCEEDED;
3316        try {
3317            Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3318            Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3319            for (File srcFile : compressedFiles) {
3320                final String srcFileName = srcFile.getName();
3321                final String dstFileName = srcFileName.substring(
3322                        0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3323                final File dstFile = new File(dstCodePath, dstFileName);
3324                ret = decompressFile(srcFile, dstFile);
3325                if (ret != PackageManager.INSTALL_SUCCEEDED) {
3326                    logCriticalInfo(Log.ERROR, "Failed to decompress"
3327                            + "; pkg: " + pkg.packageName
3328                            + ", file: " + dstFileName);
3329                    break;
3330                }
3331            }
3332        } catch (ErrnoException e) {
3333            logCriticalInfo(Log.ERROR, "Failed to decompress"
3334                    + "; pkg: " + pkg.packageName
3335                    + ", err: " + e.errno);
3336        }
3337        if (ret == PackageManager.INSTALL_SUCCEEDED) {
3338            final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3339            NativeLibraryHelper.Handle handle = null;
3340            try {
3341                handle = NativeLibraryHelper.Handle.create(dstCodePath);
3342                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3343                        null /*abiOverride*/);
3344            } catch (IOException e) {
3345                logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3346                        + "; pkg: " + pkg.packageName);
3347                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3348            } finally {
3349                IoUtils.closeQuietly(handle);
3350            }
3351        }
3352        if (ret != PackageManager.INSTALL_SUCCEEDED) {
3353            if (dstCodePath == null || !dstCodePath.exists()) {
3354                return null;
3355            }
3356            removeCodePathLI(dstCodePath);
3357            return null;
3358        }
3359
3360        return dstCodePath;
3361    }
3362
3363    private void updateInstantAppInstallerLocked(String modifiedPackage) {
3364        // we're only interested in updating the installer appliction when 1) it's not
3365        // already set or 2) the modified package is the installer
3366        if (mInstantAppInstallerActivity != null
3367                && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3368                        .equals(modifiedPackage)) {
3369            return;
3370        }
3371        setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3372    }
3373
3374    private static File preparePackageParserCache(boolean isUpgrade) {
3375        if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3376            return null;
3377        }
3378
3379        // Disable package parsing on eng builds to allow for faster incremental development.
3380        if (Build.IS_ENG) {
3381            return null;
3382        }
3383
3384        if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3385            Slog.i(TAG, "Disabling package parser cache due to system property.");
3386            return null;
3387        }
3388
3389        // The base directory for the package parser cache lives under /data/system/.
3390        final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(),
3391                "package_cache");
3392        if (cacheBaseDir == null) {
3393            return null;
3394        }
3395
3396        // If this is a system upgrade scenario, delete the contents of the package cache dir.
3397        // This also serves to "GC" unused entries when the package cache version changes (which
3398        // can only happen during upgrades).
3399        if (isUpgrade) {
3400            FileUtils.deleteContents(cacheBaseDir);
3401        }
3402
3403
3404        // Return the versioned package cache directory. This is something like
3405        // "/data/system/package_cache/1"
3406        File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3407
3408        if (cacheDir == null) {
3409            // Something went wrong. Attempt to delete everything and return.
3410            Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3411            FileUtils.deleteContentsAndDir(cacheBaseDir);
3412            return null;
3413        }
3414
3415        // The following is a workaround to aid development on non-numbered userdebug
3416        // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3417        // the system partition is newer.
3418        //
3419        // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3420        // that starts with "eng." to signify that this is an engineering build and not
3421        // destined for release.
3422        if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3423            Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3424
3425            // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3426            // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3427            // in general and should not be used for production changes. In this specific case,
3428            // we know that they will work.
3429            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3430            if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3431                FileUtils.deleteContents(cacheBaseDir);
3432                cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION);
3433            }
3434        }
3435
3436        return cacheDir;
3437    }
3438
3439    @Override
3440    public boolean isFirstBoot() {
3441        // allow instant applications
3442        return mFirstBoot;
3443    }
3444
3445    @Override
3446    public boolean isOnlyCoreApps() {
3447        // allow instant applications
3448        return mOnlyCore;
3449    }
3450
3451    @Override
3452    public boolean isUpgrade() {
3453        // allow instant applications
3454        // The system property allows testing ota flow when upgraded to the same image.
3455        return mIsUpgrade || SystemProperties.getBoolean(
3456                "persist.pm.mock-upgrade", false /* default */);
3457    }
3458
3459    private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3460        final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3461
3462        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3463                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3464                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3465        if (matches.size() == 1) {
3466            return matches.get(0).getComponentInfo().packageName;
3467        } else if (matches.size() == 0) {
3468            Log.e(TAG, "There should probably be a verifier, but, none were found");
3469            return null;
3470        }
3471        throw new RuntimeException("There must be exactly one verifier; found " + matches);
3472    }
3473
3474    private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3475        synchronized (mPackages) {
3476            SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version);
3477            if (libraryEntry == null) {
3478                throw new IllegalStateException("Missing required shared library:" + name);
3479            }
3480            return libraryEntry.apk;
3481        }
3482    }
3483
3484    private @NonNull String getRequiredInstallerLPr() {
3485        final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3486        intent.addCategory(Intent.CATEGORY_DEFAULT);
3487        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3488
3489        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3490                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3491                UserHandle.USER_SYSTEM);
3492        if (matches.size() == 1) {
3493            ResolveInfo resolveInfo = matches.get(0);
3494            if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3495                throw new RuntimeException("The installer must be a privileged app");
3496            }
3497            return matches.get(0).getComponentInfo().packageName;
3498        } else {
3499            throw new RuntimeException("There must be exactly one installer; found " + matches);
3500        }
3501    }
3502
3503    private @NonNull String getRequiredUninstallerLPr() {
3504        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3505        intent.addCategory(Intent.CATEGORY_DEFAULT);
3506        intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3507
3508        final ResolveInfo resolveInfo = resolveIntent(intent, null,
3509                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3510                UserHandle.USER_SYSTEM);
3511        if (resolveInfo == null ||
3512                mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3513            throw new RuntimeException("There must be exactly one uninstaller; found "
3514                    + resolveInfo);
3515        }
3516        return resolveInfo.getComponentInfo().packageName;
3517    }
3518
3519    private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3520        final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3521
3522        final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3523                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3524                UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3525        ResolveInfo best = null;
3526        final int N = matches.size();
3527        for (int i = 0; i < N; i++) {
3528            final ResolveInfo cur = matches.get(i);
3529            final String packageName = cur.getComponentInfo().packageName;
3530            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3531                    packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3532                continue;
3533            }
3534
3535            if (best == null || cur.priority > best.priority) {
3536                best = cur;
3537            }
3538        }
3539
3540        if (best != null) {
3541            return best.getComponentInfo().getComponentName();
3542        }
3543        Slog.w(TAG, "Intent filter verifier not found");
3544        return null;
3545    }
3546
3547    @Override
3548    public @Nullable ComponentName getInstantAppResolverComponent() {
3549        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3550            return null;
3551        }
3552        synchronized (mPackages) {
3553            final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3554            if (instantAppResolver == null) {
3555                return null;
3556            }
3557            return instantAppResolver.first;
3558        }
3559    }
3560
3561    private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3562        final String[] packageArray =
3563                mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3564        if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3565            if (DEBUG_INSTANT) {
3566                Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3567            }
3568            return null;
3569        }
3570
3571        final int callingUid = Binder.getCallingUid();
3572        final int resolveFlags =
3573                MATCH_DIRECT_BOOT_AWARE
3574                | MATCH_DIRECT_BOOT_UNAWARE
3575                | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3576        String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3577        final Intent resolverIntent = new Intent(actionName);
3578        List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3579                resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3580        final int N = resolvers.size();
3581        if (N == 0) {
3582            if (DEBUG_INSTANT) {
3583                Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3584            }
3585            return null;
3586        }
3587
3588        final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3589        for (int i = 0; i < N; i++) {
3590            final ResolveInfo info = resolvers.get(i);
3591
3592            if (info.serviceInfo == null) {
3593                continue;
3594            }
3595
3596            final String packageName = info.serviceInfo.packageName;
3597            if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3598                if (DEBUG_INSTANT) {
3599                    Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3600                            + " pkg: " + packageName + ", info:" + info);
3601                }
3602                continue;
3603            }
3604
3605            if (DEBUG_INSTANT) {
3606                Slog.v(TAG, "Ephemeral resolver found;"
3607                        + " pkg: " + packageName + ", info:" + info);
3608            }
3609            return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3610        }
3611        if (DEBUG_INSTANT) {
3612            Slog.v(TAG, "Ephemeral resolver NOT found");
3613        }
3614        return null;
3615    }
3616
3617    private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3618        String[] orderedActions = Build.IS_ENG
3619                ? new String[]{
3620                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3621                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3622                : new String[]{
3623                        Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3624
3625        final int resolveFlags =
3626                MATCH_DIRECT_BOOT_AWARE
3627                        | MATCH_DIRECT_BOOT_UNAWARE
3628                        | Intent.FLAG_IGNORE_EPHEMERAL
3629                        | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3630        final Intent intent = new Intent();
3631        intent.addCategory(Intent.CATEGORY_DEFAULT);
3632        intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3633        List<ResolveInfo> matches = null;
3634        for (String action : orderedActions) {
3635            intent.setAction(action);
3636            matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3637                    resolveFlags, UserHandle.USER_SYSTEM);
3638            if (matches.isEmpty()) {
3639                if (DEBUG_INSTANT) {
3640                    Slog.d(TAG, "Instant App installer not found with " + action);
3641                }
3642            } else {
3643                break;
3644            }
3645        }
3646        Iterator<ResolveInfo> iter = matches.iterator();
3647        while (iter.hasNext()) {
3648            final ResolveInfo rInfo = iter.next();
3649            final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3650            if (ps != null) {
3651                final PermissionsState permissionsState = ps.getPermissionsState();
3652                if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3653                        || Build.IS_ENG) {
3654                    continue;
3655                }
3656            }
3657            iter.remove();
3658        }
3659        if (matches.size() == 0) {
3660            return null;
3661        } else if (matches.size() == 1) {
3662            return (ActivityInfo) matches.get(0).getComponentInfo();
3663        } else {
3664            throw new RuntimeException(
3665                    "There must be at most one ephemeral installer; found " + matches);
3666        }
3667    }
3668
3669    private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3670            @NonNull ComponentName resolver) {
3671        final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3672                .addCategory(Intent.CATEGORY_DEFAULT)
3673                .setPackage(resolver.getPackageName());
3674        final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3675        List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3676                UserHandle.USER_SYSTEM);
3677        if (matches.isEmpty()) {
3678            return null;
3679        }
3680        return matches.get(0).getComponentInfo().getComponentName();
3681    }
3682
3683    private void primeDomainVerificationsLPw(int userId) {
3684        if (DEBUG_DOMAIN_VERIFICATION) {
3685            Slog.d(TAG, "Priming domain verifications in user " + userId);
3686        }
3687
3688        SystemConfig systemConfig = SystemConfig.getInstance();
3689        ArraySet<String> packages = systemConfig.getLinkedApps();
3690
3691        for (String packageName : packages) {
3692            PackageParser.Package pkg = mPackages.get(packageName);
3693            if (pkg != null) {
3694                if (!pkg.isSystem()) {
3695                    Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3696                    continue;
3697                }
3698
3699                ArraySet<String> domains = null;
3700                for (PackageParser.Activity a : pkg.activities) {
3701                    for (ActivityIntentInfo filter : a.intents) {
3702                        if (hasValidDomains(filter)) {
3703                            if (domains == null) {
3704                                domains = new ArraySet<String>();
3705                            }
3706                            domains.addAll(filter.getHostsList());
3707                        }
3708                    }
3709                }
3710
3711                if (domains != null && domains.size() > 0) {
3712                    if (DEBUG_DOMAIN_VERIFICATION) {
3713                        Slog.v(TAG, "      + " + packageName);
3714                    }
3715                    // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3716                    // state w.r.t. the formal app-linkage "no verification attempted" state;
3717                    // and then 'always' in the per-user state actually used for intent resolution.
3718                    final IntentFilterVerificationInfo ivi;
3719                    ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3720                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3721                    mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3722                            INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3723                } else {
3724                    Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3725                            + "' does not handle web links");
3726                }
3727            } else {
3728                Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3729            }
3730        }
3731
3732        scheduleWritePackageRestrictionsLocked(userId);
3733        scheduleWriteSettingsLocked();
3734    }
3735
3736    private void applyFactoryDefaultBrowserLPw(int userId) {
3737        // The default browser app's package name is stored in a string resource,
3738        // with a product-specific overlay used for vendor customization.
3739        String browserPkg = mContext.getResources().getString(
3740                com.android.internal.R.string.default_browser);
3741        if (!TextUtils.isEmpty(browserPkg)) {
3742            // non-empty string => required to be a known package
3743            PackageSetting ps = mSettings.mPackages.get(browserPkg);
3744            if (ps == null) {
3745                Slog.e(TAG, "Product default browser app does not exist: " + browserPkg);
3746                browserPkg = null;
3747            } else {
3748                mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3749            }
3750        }
3751
3752        // Nothing valid explicitly set? Make the factory-installed browser the explicit
3753        // default.  If there's more than one, just leave everything alone.
3754        if (browserPkg == null) {
3755            calculateDefaultBrowserLPw(userId);
3756        }
3757    }
3758
3759    private void calculateDefaultBrowserLPw(int userId) {
3760        List<String> allBrowsers = resolveAllBrowserApps(userId);
3761        final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null;
3762        mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId);
3763    }
3764
3765    private List<String> resolveAllBrowserApps(int userId) {
3766        // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set
3767        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3768                PackageManager.MATCH_ALL, userId);
3769
3770        final int count = list.size();
3771        List<String> result = new ArrayList<String>(count);
3772        for (int i=0; i<count; i++) {
3773            ResolveInfo info = list.get(i);
3774            if (info.activityInfo == null
3775                    || !info.handleAllWebDataURI
3776                    || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0
3777                    || result.contains(info.activityInfo.packageName)) {
3778                continue;
3779            }
3780            result.add(info.activityInfo.packageName);
3781        }
3782
3783        return result;
3784    }
3785
3786    private boolean packageIsBrowser(String packageName, int userId) {
3787        List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
3788                PackageManager.MATCH_ALL, userId);
3789        final int N = list.size();
3790        for (int i = 0; i < N; i++) {
3791            ResolveInfo info = list.get(i);
3792            if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
3793                return true;
3794            }
3795        }
3796        return false;
3797    }
3798
3799    private void checkDefaultBrowser() {
3800        final int myUserId = UserHandle.myUserId();
3801        final String packageName = getDefaultBrowserPackageName(myUserId);
3802        if (packageName != null) {
3803            PackageInfo info = getPackageInfo(packageName, 0, myUserId);
3804            if (info == null) {
3805                Slog.w(TAG, "Default browser no longer installed: " + packageName);
3806                synchronized (mPackages) {
3807                    applyFactoryDefaultBrowserLPw(myUserId);    // leaves ambiguous when > 1
3808                }
3809            }
3810        }
3811    }
3812
3813    @Override
3814    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
3815            throws RemoteException {
3816        try {
3817            return super.onTransact(code, data, reply, flags);
3818        } catch (RuntimeException e) {
3819            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
3820                Slog.wtf(TAG, "Package Manager Crash", e);
3821            }
3822            throw e;
3823        }
3824    }
3825
3826    static int[] appendInts(int[] cur, int[] add) {
3827        if (add == null) return cur;
3828        if (cur == null) return add;
3829        final int N = add.length;
3830        for (int i=0; i<N; i++) {
3831            cur = appendInt(cur, add[i]);
3832        }
3833        return cur;
3834    }
3835
3836    /**
3837     * Returns whether or not a full application can see an instant application.
3838     * <p>
3839     * Currently, there are three cases in which this can occur:
3840     * <ol>
3841     * <li>The calling application is a "special" process. Special processes
3842     *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
3843     * <li>The calling application has the permission
3844     *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
3845     * <li>The calling application is the default launcher on the
3846     *     system partition.</li>
3847     * </ol>
3848     */
3849    private boolean canViewInstantApps(int callingUid, int userId) {
3850        if (callingUid < Process.FIRST_APPLICATION_UID) {
3851            return true;
3852        }
3853        if (mContext.checkCallingOrSelfPermission(
3854                android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
3855            return true;
3856        }
3857        if (mContext.checkCallingOrSelfPermission(
3858                android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
3859            final ComponentName homeComponent = getDefaultHomeActivity(userId);
3860            if (homeComponent != null
3861                    && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
3862                return true;
3863            }
3864        }
3865        return false;
3866    }
3867
3868    private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
3869        if (!sUserManager.exists(userId)) return null;
3870        if (ps == null) {
3871            return null;
3872        }
3873        final int callingUid = Binder.getCallingUid();
3874        // Filter out ephemeral app metadata:
3875        //   * The system/shell/root can see metadata for any app
3876        //   * An installed app can see metadata for 1) other installed apps
3877        //     and 2) ephemeral apps that have explicitly interacted with it
3878        //   * Ephemeral apps can only see their own data and exposed installed apps
3879        //   * Holding a signature permission allows seeing instant apps
3880        if (filterAppAccessLPr(ps, callingUid, userId)) {
3881            return null;
3882        }
3883
3884        if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
3885                && ps.isSystem()) {
3886            flags |= MATCH_ANY_USER;
3887        }
3888
3889        final PackageUserState state = ps.readUserState(userId);
3890        PackageParser.Package p = ps.pkg;
3891        if (p != null) {
3892            final PermissionsState permissionsState = ps.getPermissionsState();
3893
3894            // Compute GIDs only if requested
3895            final int[] gids = (flags & PackageManager.GET_GIDS) == 0
3896                    ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
3897            // Compute granted permissions only if package has requested permissions
3898            final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
3899                    ? Collections.<String>emptySet() : permissionsState.getPermissions(userId);
3900
3901            PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
3902                    ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
3903
3904            if (packageInfo == null) {
3905                return null;
3906            }
3907
3908            packageInfo.packageName = packageInfo.applicationInfo.packageName =
3909                    resolveExternalPackageNameLPr(p);
3910
3911            return packageInfo;
3912        } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
3913            PackageInfo pi = new PackageInfo();
3914            pi.packageName = ps.name;
3915            pi.setLongVersionCode(ps.versionCode);
3916            pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
3917            pi.firstInstallTime = ps.firstInstallTime;
3918            pi.lastUpdateTime = ps.lastUpdateTime;
3919
3920            ApplicationInfo ai = new ApplicationInfo();
3921            ai.packageName = ps.name;
3922            ai.uid = UserHandle.getUid(userId, ps.appId);
3923            ai.primaryCpuAbi = ps.primaryCpuAbiString;
3924            ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
3925            ai.versionCode = ps.versionCode;
3926            ai.flags = ps.pkgFlags;
3927            ai.privateFlags = ps.pkgPrivateFlags;
3928            pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
3929
3930            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
3931                    + ps.name + "]. Provides a minimum info.");
3932            return pi;
3933        } else {
3934            return null;
3935        }
3936    }
3937
3938    @Override
3939    public void checkPackageStartable(String packageName, int userId) {
3940        final int callingUid = Binder.getCallingUid();
3941        if (getInstantAppPackageName(callingUid) != null) {
3942            throw new SecurityException("Instant applications don't have access to this method");
3943        }
3944        final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
3945        synchronized (mPackages) {
3946            final PackageSetting ps = mSettings.mPackages.get(packageName);
3947            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
3948                throw new SecurityException("Package " + packageName + " was not found!");
3949            }
3950
3951            if (!ps.getInstalled(userId)) {
3952                throw new SecurityException(
3953                        "Package " + packageName + " was not installed for user " + userId + "!");
3954            }
3955
3956            if (mSafeMode && !ps.isSystem()) {
3957                throw new SecurityException("Package " + packageName + " not a system app!");
3958            }
3959
3960            if (mFrozenPackages.contains(packageName)) {
3961                throw new SecurityException("Package " + packageName + " is currently frozen!");
3962            }
3963
3964            if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
3965                throw new SecurityException("Package " + packageName + " is not encryption aware!");
3966            }
3967        }
3968    }
3969
3970    @Override
3971    public boolean isPackageAvailable(String packageName, int userId) {
3972        if (!sUserManager.exists(userId)) return false;
3973        final int callingUid = Binder.getCallingUid();
3974        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
3975                false /*requireFullPermission*/, false /*checkShell*/, "is package available");
3976        synchronized (mPackages) {
3977            PackageParser.Package p = mPackages.get(packageName);
3978            if (p != null) {
3979                final PackageSetting ps = (PackageSetting) p.mExtras;
3980                if (filterAppAccessLPr(ps, callingUid, userId)) {
3981                    return false;
3982                }
3983                if (ps != null) {
3984                    final PackageUserState state = ps.readUserState(userId);
3985                    if (state != null) {
3986                        return PackageParser.isAvailable(state);
3987                    }
3988                }
3989            }
3990        }
3991        return false;
3992    }
3993
3994    @Override
3995    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
3996        return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
3997                flags, Binder.getCallingUid(), userId);
3998    }
3999
4000    @Override
4001    public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4002            int flags, int userId) {
4003        return getPackageInfoInternal(versionedPackage.getPackageName(),
4004                versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4005    }
4006
4007    /**
4008     * Important: The provided filterCallingUid is used exclusively to filter out packages
4009     * that can be seen based on user state. It's typically the original caller uid prior
4010     * to clearing. Because it can only be provided by trusted code, it's value can be
4011     * trusted and will be used as-is; unlike userId which will be validated by this method.
4012     */
4013    private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4014            int flags, int filterCallingUid, int userId) {
4015        if (!sUserManager.exists(userId)) return null;
4016        flags = updateFlagsForPackage(flags, userId, packageName);
4017        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4018                false /* requireFullPermission */, false /* checkShell */, "get package info");
4019
4020        // reader
4021        synchronized (mPackages) {
4022            // Normalize package name to handle renamed packages and static libs
4023            packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4024
4025            final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4026            if (matchFactoryOnly) {
4027                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4028                if (ps != null) {
4029                    if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4030                        return null;
4031                    }
4032                    if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4033                        return null;
4034                    }
4035                    return generatePackageInfo(ps, flags, userId);
4036                }
4037            }
4038
4039            PackageParser.Package p = mPackages.get(packageName);
4040            if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4041                return null;
4042            }
4043            if (DEBUG_PACKAGE_INFO)
4044                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4045            if (p != null) {
4046                final PackageSetting ps = (PackageSetting) p.mExtras;
4047                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4048                    return null;
4049                }
4050                if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4051                    return null;
4052                }
4053                return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4054            }
4055            if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4056                final PackageSetting ps = mSettings.mPackages.get(packageName);
4057                if (ps == null) return null;
4058                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4059                    return null;
4060                }
4061                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4062                    return null;
4063                }
4064                return generatePackageInfo(ps, flags, userId);
4065            }
4066        }
4067        return null;
4068    }
4069
4070    private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4071        if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4072            return true;
4073        }
4074        if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4075            return true;
4076        }
4077        if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4078            return true;
4079        }
4080        return false;
4081    }
4082
4083    private boolean isComponentVisibleToInstantApp(
4084            @Nullable ComponentName component, @ComponentType int type) {
4085        if (type == TYPE_ACTIVITY) {
4086            final PackageParser.Activity activity = mActivities.mActivities.get(component);
4087            return activity != null
4088                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4089                    : false;
4090        } else if (type == TYPE_RECEIVER) {
4091            final PackageParser.Activity activity = mReceivers.mActivities.get(component);
4092            return activity != null
4093                    ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4094                    : false;
4095        } else if (type == TYPE_SERVICE) {
4096            final PackageParser.Service service = mServices.mServices.get(component);
4097            return service != null
4098                    ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4099                    : false;
4100        } else if (type == TYPE_PROVIDER) {
4101            final PackageParser.Provider provider = mProviders.mProviders.get(component);
4102            return provider != null
4103                    ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4104                    : false;
4105        } else if (type == TYPE_UNKNOWN) {
4106            return isComponentVisibleToInstantApp(component);
4107        }
4108        return false;
4109    }
4110
4111    /**
4112     * Returns whether or not access to the application should be filtered.
4113     * <p>
4114     * Access may be limited based upon whether the calling or target applications
4115     * are instant applications.
4116     *
4117     * @see #canAccessInstantApps(int)
4118     */
4119    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4120            @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4121        // if we're in an isolated process, get the real calling UID
4122        if (Process.isIsolated(callingUid)) {
4123            callingUid = mIsolatedOwners.get(callingUid);
4124        }
4125        final String instantAppPkgName = getInstantAppPackageName(callingUid);
4126        final boolean callerIsInstantApp = instantAppPkgName != null;
4127        if (ps == null) {
4128            if (callerIsInstantApp) {
4129                // pretend the application exists, but, needs to be filtered
4130                return true;
4131            }
4132            return false;
4133        }
4134        // if the target and caller are the same application, don't filter
4135        if (isCallerSameApp(ps.name, callingUid)) {
4136            return false;
4137        }
4138        if (callerIsInstantApp) {
4139            // request for a specific component; if it hasn't been explicitly exposed through
4140            // property or instrumentation target, filter
4141            if (component != null) {
4142                final PackageParser.Instrumentation instrumentation =
4143                        mInstrumentation.get(component);
4144                if (instrumentation != null
4145                        && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4146                    return false;
4147                }
4148                return !isComponentVisibleToInstantApp(component, componentType);
4149            }
4150            // request for application; if no components have been explicitly exposed, filter
4151            return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps;
4152        }
4153        if (ps.getInstantApp(userId)) {
4154            // caller can see all components of all instant applications, don't filter
4155            if (canViewInstantApps(callingUid, userId)) {
4156                return false;
4157            }
4158            // request for a specific instant application component, filter
4159            if (component != null) {
4160                return true;
4161            }
4162            // request for an instant application; if the caller hasn't been granted access, filter
4163            return !mInstantAppRegistry.isInstantAccessGranted(
4164                    userId, UserHandle.getAppId(callingUid), ps.appId);
4165        }
4166        return false;
4167    }
4168
4169    /**
4170     * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int)
4171     */
4172    private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4173        return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4174    }
4175
4176    private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4177            int flags) {
4178        // Callers can access only the libs they depend on, otherwise they need to explicitly
4179        // ask for the shared libraries given the caller is allowed to access all static libs.
4180        if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4181            // System/shell/root get to see all static libs
4182            final int appId = UserHandle.getAppId(uid);
4183            if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4184                    || appId == Process.ROOT_UID) {
4185                return false;
4186            }
4187        }
4188
4189        // No package means no static lib as it is always on internal storage
4190        if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4191            return false;
4192        }
4193
4194        final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName,
4195                ps.pkg.staticSharedLibVersion);
4196        if (libEntry == null) {
4197            return false;
4198        }
4199
4200        final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4201        final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4202        if (uidPackageNames == null) {
4203            return true;
4204        }
4205
4206        for (String uidPackageName : uidPackageNames) {
4207            if (ps.name.equals(uidPackageName)) {
4208                return false;
4209            }
4210            PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4211            if (uidPs != null) {
4212                final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4213                        libEntry.info.getName());
4214                if (index < 0) {
4215                    continue;
4216                }
4217                if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) {
4218                    return false;
4219                }
4220            }
4221        }
4222        return true;
4223    }
4224
4225    @Override
4226    public String[] currentToCanonicalPackageNames(String[] names) {
4227        final int callingUid = Binder.getCallingUid();
4228        if (getInstantAppPackageName(callingUid) != null) {
4229            return names;
4230        }
4231        final String[] out = new String[names.length];
4232        // reader
4233        synchronized (mPackages) {
4234            final int callingUserId = UserHandle.getUserId(callingUid);
4235            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4236            for (int i=names.length-1; i>=0; i--) {
4237                final PackageSetting ps = mSettings.mPackages.get(names[i]);
4238                boolean translateName = false;
4239                if (ps != null && ps.realName != null) {
4240                    final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4241                    translateName = !targetIsInstantApp
4242                            || canViewInstantApps
4243                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4244                                    UserHandle.getAppId(callingUid), ps.appId);
4245                }
4246                out[i] = translateName ? ps.realName : names[i];
4247            }
4248        }
4249        return out;
4250    }
4251
4252    @Override
4253    public String[] canonicalToCurrentPackageNames(String[] names) {
4254        final int callingUid = Binder.getCallingUid();
4255        if (getInstantAppPackageName(callingUid) != null) {
4256            return names;
4257        }
4258        final String[] out = new String[names.length];
4259        // reader
4260        synchronized (mPackages) {
4261            final int callingUserId = UserHandle.getUserId(callingUid);
4262            final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4263            for (int i=names.length-1; i>=0; i--) {
4264                final String cur = mSettings.getRenamedPackageLPr(names[i]);
4265                boolean translateName = false;
4266                if (cur != null) {
4267                    final PackageSetting ps = mSettings.mPackages.get(names[i]);
4268                    final boolean targetIsInstantApp =
4269                            ps != null && ps.getInstantApp(callingUserId);
4270                    translateName = !targetIsInstantApp
4271                            || canViewInstantApps
4272                            || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4273                                    UserHandle.getAppId(callingUid), ps.appId);
4274                }
4275                out[i] = translateName ? cur : names[i];
4276            }
4277        }
4278        return out;
4279    }
4280
4281    @Override
4282    public int getPackageUid(String packageName, int flags, int userId) {
4283        if (!sUserManager.exists(userId)) return -1;
4284        final int callingUid = Binder.getCallingUid();
4285        flags = updateFlagsForPackage(flags, userId, packageName);
4286        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4287                false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4288
4289        // reader
4290        synchronized (mPackages) {
4291            final PackageParser.Package p = mPackages.get(packageName);
4292            if (p != null && p.isMatch(flags)) {
4293                PackageSetting ps = (PackageSetting) p.mExtras;
4294                if (filterAppAccessLPr(ps, callingUid, userId)) {
4295                    return -1;
4296                }
4297                return UserHandle.getUid(userId, p.applicationInfo.uid);
4298            }
4299            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4300                final PackageSetting ps = mSettings.mPackages.get(packageName);
4301                if (ps != null && ps.isMatch(flags)
4302                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4303                    return UserHandle.getUid(userId, ps.appId);
4304                }
4305            }
4306        }
4307
4308        return -1;
4309    }
4310
4311    @Override
4312    public int[] getPackageGids(String packageName, int flags, int userId) {
4313        if (!sUserManager.exists(userId)) return null;
4314        final int callingUid = Binder.getCallingUid();
4315        flags = updateFlagsForPackage(flags, userId, packageName);
4316        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4317                false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4318
4319        // reader
4320        synchronized (mPackages) {
4321            final PackageParser.Package p = mPackages.get(packageName);
4322            if (p != null && p.isMatch(flags)) {
4323                PackageSetting ps = (PackageSetting) p.mExtras;
4324                if (filterAppAccessLPr(ps, callingUid, userId)) {
4325                    return null;
4326                }
4327                // TODO: Shouldn't this be checking for package installed state for userId and
4328                // return null?
4329                return ps.getPermissionsState().computeGids(userId);
4330            }
4331            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4332                final PackageSetting ps = mSettings.mPackages.get(packageName);
4333                if (ps != null && ps.isMatch(flags)
4334                        && !filterAppAccessLPr(ps, callingUid, userId)) {
4335                    return ps.getPermissionsState().computeGids(userId);
4336                }
4337            }
4338        }
4339
4340        return null;
4341    }
4342
4343    @Override
4344    public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4345        return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4346    }
4347
4348    @Override
4349    public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4350            int flags) {
4351        final List<PermissionInfo> permissionList =
4352                mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4353        return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4354    }
4355
4356    @Override
4357    public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4358        return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4359    }
4360
4361    @Override
4362    public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4363        final List<PermissionGroupInfo> permissionList =
4364                mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4365        return (permissionList == null)
4366                ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4367    }
4368
4369    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4370            int filterCallingUid, int userId) {
4371        if (!sUserManager.exists(userId)) return null;
4372        PackageSetting ps = mSettings.mPackages.get(packageName);
4373        if (ps != null) {
4374            if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4375                return null;
4376            }
4377            if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4378                return null;
4379            }
4380            if (ps.pkg == null) {
4381                final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4382                if (pInfo != null) {
4383                    return pInfo.applicationInfo;
4384                }
4385                return null;
4386            }
4387            ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4388                    ps.readUserState(userId), userId);
4389            if (ai != null) {
4390                ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4391            }
4392            return ai;
4393        }
4394        return null;
4395    }
4396
4397    @Override
4398    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4399        return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4400    }
4401
4402    /**
4403     * Important: The provided filterCallingUid is used exclusively to filter out applications
4404     * that can be seen based on user state. It's typically the original caller uid prior
4405     * to clearing. Because it can only be provided by trusted code, it's value can be
4406     * trusted and will be used as-is; unlike userId which will be validated by this method.
4407     */
4408    private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4409            int filterCallingUid, int userId) {
4410        if (!sUserManager.exists(userId)) return null;
4411        flags = updateFlagsForApplication(flags, userId, packageName);
4412        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4413                false /* requireFullPermission */, false /* checkShell */, "get application info");
4414
4415        // writer
4416        synchronized (mPackages) {
4417            // Normalize package name to handle renamed packages and static libs
4418            packageName = resolveInternalPackageNameLPr(packageName,
4419                    PackageManager.VERSION_CODE_HIGHEST);
4420
4421            PackageParser.Package p = mPackages.get(packageName);
4422            if (DEBUG_PACKAGE_INFO) Log.v(
4423                    TAG, "getApplicationInfo " + packageName
4424                    + ": " + p);
4425            if (p != null) {
4426                PackageSetting ps = mSettings.mPackages.get(packageName);
4427                if (ps == null) return null;
4428                if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4429                    return null;
4430                }
4431                if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4432                    return null;
4433                }
4434                // Note: isEnabledLP() does not apply here - always return info
4435                ApplicationInfo ai = PackageParser.generateApplicationInfo(
4436                        p, flags, ps.readUserState(userId), userId);
4437                if (ai != null) {
4438                    ai.packageName = resolveExternalPackageNameLPr(p);
4439                }
4440                return ai;
4441            }
4442            if ("android".equals(packageName)||"system".equals(packageName)) {
4443                return mAndroidApplication;
4444            }
4445            if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4446                // Already generates the external package name
4447                return generateApplicationInfoFromSettingsLPw(packageName,
4448                        flags, filterCallingUid, userId);
4449            }
4450        }
4451        return null;
4452    }
4453
4454    private String normalizePackageNameLPr(String packageName) {
4455        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4456        return normalizedPackageName != null ? normalizedPackageName : packageName;
4457    }
4458
4459    @Override
4460    public void deletePreloadsFileCache() {
4461        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
4462            throw new SecurityException("Only system or settings may call deletePreloadsFileCache");
4463        }
4464        File dir = Environment.getDataPreloadsFileCacheDirectory();
4465        Slog.i(TAG, "Deleting preloaded file cache " + dir);
4466        FileUtils.deleteContents(dir);
4467    }
4468
4469    @Override
4470    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4471            final int storageFlags, final IPackageDataObserver observer) {
4472        mContext.enforceCallingOrSelfPermission(
4473                android.Manifest.permission.CLEAR_APP_CACHE, null);
4474        mHandler.post(() -> {
4475            boolean success = false;
4476            try {
4477                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4478                success = true;
4479            } catch (IOException e) {
4480                Slog.w(TAG, e);
4481            }
4482            if (observer != null) {
4483                try {
4484                    observer.onRemoveCompleted(null, success);
4485                } catch (RemoteException e) {
4486                    Slog.w(TAG, e);
4487                }
4488            }
4489        });
4490    }
4491
4492    @Override
4493    public void freeStorage(final String volumeUuid, final long freeStorageSize,
4494            final int storageFlags, final IntentSender pi) {
4495        mContext.enforceCallingOrSelfPermission(
4496                android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4497        mHandler.post(() -> {
4498            boolean success = false;
4499            try {
4500                freeStorage(volumeUuid, freeStorageSize, storageFlags);
4501                success = true;
4502            } catch (IOException e) {
4503                Slog.w(TAG, e);
4504            }
4505            if (pi != null) {
4506                try {
4507                    pi.sendIntent(null, success ? 1 : 0, null, null, null);
4508                } catch (SendIntentException e) {
4509                    Slog.w(TAG, e);
4510                }
4511            }
4512        });
4513    }
4514
4515    /**
4516     * Blocking call to clear various types of cached data across the system
4517     * until the requested bytes are available.
4518     */
4519    public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4520        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4521        final File file = storage.findPathForUuid(volumeUuid);
4522        if (file.getUsableSpace() >= bytes) return;
4523
4524        if (ENABLE_FREE_CACHE_V2) {
4525            final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4526                    volumeUuid);
4527            final boolean aggressive = (storageFlags
4528                    & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4529            final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4530
4531            // 1. Pre-flight to determine if we have any chance to succeed
4532            // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4533            if (internalVolume && (aggressive || SystemProperties
4534                    .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4535                deletePreloadsFileCache();
4536                if (file.getUsableSpace() >= bytes) return;
4537            }
4538
4539            // 3. Consider parsed APK data (aggressive only)
4540            if (internalVolume && aggressive) {
4541                FileUtils.deleteContents(mCacheDir);
4542                if (file.getUsableSpace() >= bytes) return;
4543            }
4544
4545            // 4. Consider cached app data (above quotas)
4546            try {
4547                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4548                        Installer.FLAG_FREE_CACHE_V2);
4549            } catch (InstallerException ignored) {
4550            }
4551            if (file.getUsableSpace() >= bytes) return;
4552
4553            // 5. Consider shared libraries with refcount=0 and age>min cache period
4554            if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4555                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4556                            Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4557                            DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4558                return;
4559            }
4560
4561            // 6. Consider dexopt output (aggressive only)
4562            // TODO: Implement
4563
4564            // 7. Consider installed instant apps unused longer than min cache period
4565            if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4566                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4567                            Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4568                            InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4569                return;
4570            }
4571
4572            // 8. Consider cached app data (below quotas)
4573            try {
4574                mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4575                        Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4576            } catch (InstallerException ignored) {
4577            }
4578            if (file.getUsableSpace() >= bytes) return;
4579
4580            // 9. Consider DropBox entries
4581            // TODO: Implement
4582
4583            // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4584            if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4585                    android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4586                            Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4587                            InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4588                return;
4589            }
4590        } else {
4591            try {
4592                mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4593            } catch (InstallerException ignored) {
4594            }
4595            if (file.getUsableSpace() >= bytes) return;
4596        }
4597
4598        throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4599    }
4600
4601    private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4602            throws IOException {
4603        final StorageManager storage = mContext.getSystemService(StorageManager.class);
4604        final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4605
4606        List<VersionedPackage> packagesToDelete = null;
4607        final long now = System.currentTimeMillis();
4608
4609        synchronized (mPackages) {
4610            final int[] allUsers = sUserManager.getUserIds();
4611            final int libCount = mSharedLibraries.size();
4612            for (int i = 0; i < libCount; i++) {
4613                final LongSparseArray<SharedLibraryEntry> versionedLib
4614                        = mSharedLibraries.valueAt(i);
4615                if (versionedLib == null) {
4616                    continue;
4617                }
4618                final int versionCount = versionedLib.size();
4619                for (int j = 0; j < versionCount; j++) {
4620                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4621                    // Skip packages that are not static shared libs.
4622                    if (!libInfo.isStatic()) {
4623                        break;
4624                    }
4625                    // Important: We skip static shared libs used for some user since
4626                    // in such a case we need to keep the APK on the device. The check for
4627                    // a lib being used for any user is performed by the uninstall call.
4628                    final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4629                    // Resolve the package name - we use synthetic package names internally
4630                    final String internalPackageName = resolveInternalPackageNameLPr(
4631                            declaringPackage.getPackageName(),
4632                            declaringPackage.getLongVersionCode());
4633                    final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4634                    // Skip unused static shared libs cached less than the min period
4635                    // to prevent pruning a lib needed by a subsequently installed package.
4636                    if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4637                        continue;
4638                    }
4639                    if (packagesToDelete == null) {
4640                        packagesToDelete = new ArrayList<>();
4641                    }
4642                    packagesToDelete.add(new VersionedPackage(internalPackageName,
4643                            declaringPackage.getLongVersionCode()));
4644                }
4645            }
4646        }
4647
4648        if (packagesToDelete != null) {
4649            final int packageCount = packagesToDelete.size();
4650            for (int i = 0; i < packageCount; i++) {
4651                final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4652                // Delete the package synchronously (will fail of the lib used for any user).
4653                if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4654                        UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4655                                == PackageManager.DELETE_SUCCEEDED) {
4656                    if (volume.getUsableSpace() >= neededSpace) {
4657                        return true;
4658                    }
4659                }
4660            }
4661        }
4662
4663        return false;
4664    }
4665
4666    /**
4667     * Update given flags based on encryption status of current user.
4668     */
4669    private int updateFlags(int flags, int userId) {
4670        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4671                | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4672            // Caller expressed an explicit opinion about what encryption
4673            // aware/unaware components they want to see, so fall through and
4674            // give them what they want
4675        } else {
4676            // Caller expressed no opinion, so match based on user state
4677            if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4678                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4679            } else {
4680                flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4681            }
4682        }
4683        return flags;
4684    }
4685
4686    private UserManagerInternal getUserManagerInternal() {
4687        if (mUserManagerInternal == null) {
4688            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4689        }
4690        return mUserManagerInternal;
4691    }
4692
4693    private ActivityManagerInternal getActivityManagerInternal() {
4694        if (mActivityManagerInternal == null) {
4695            mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4696        }
4697        return mActivityManagerInternal;
4698    }
4699
4700
4701    private DeviceIdleController.LocalService getDeviceIdleController() {
4702        if (mDeviceIdleController == null) {
4703            mDeviceIdleController =
4704                    LocalServices.getService(DeviceIdleController.LocalService.class);
4705        }
4706        return mDeviceIdleController;
4707    }
4708
4709    /**
4710     * Update given flags when being used to request {@link PackageInfo}.
4711     */
4712    private int updateFlagsForPackage(int flags, int userId, Object cookie) {
4713        final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
4714        boolean triaged = true;
4715        if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS
4716                | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) {
4717            // Caller is asking for component details, so they'd better be
4718            // asking for specific encryption matching behavior, or be triaged
4719            if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4720                    | PackageManager.MATCH_DIRECT_BOOT_AWARE
4721                    | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4722                triaged = false;
4723            }
4724        }
4725        if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES
4726                | PackageManager.MATCH_SYSTEM_ONLY
4727                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4728            triaged = false;
4729        }
4730        if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
4731            mPermissionManager.enforceCrossUserPermission(
4732                    Binder.getCallingUid(), userId, false, false,
4733                    "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
4734                    + Debug.getCallers(5));
4735        } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
4736                && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
4737            // If the caller wants all packages and has a restricted profile associated with it,
4738            // then match all users. This is to make sure that launchers that need to access work
4739            // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
4740            // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
4741            flags |= PackageManager.MATCH_ANY_USER;
4742        }
4743        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4744            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4745                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4746        }
4747        return updateFlags(flags, userId);
4748    }
4749
4750    /**
4751     * Update given flags when being used to request {@link ApplicationInfo}.
4752     */
4753    private int updateFlagsForApplication(int flags, int userId, Object cookie) {
4754        return updateFlagsForPackage(flags, userId, cookie);
4755    }
4756
4757    /**
4758     * Update given flags when being used to request {@link ComponentInfo}.
4759     */
4760    private int updateFlagsForComponent(int flags, int userId, Object cookie) {
4761        if (cookie instanceof Intent) {
4762            if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) {
4763                flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
4764            }
4765        }
4766
4767        boolean triaged = true;
4768        // Caller is asking for component details, so they'd better be
4769        // asking for specific encryption matching behavior, or be triaged
4770        if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4771                | PackageManager.MATCH_DIRECT_BOOT_AWARE
4772                | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) {
4773            triaged = false;
4774        }
4775        if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) {
4776            Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie
4777                    + " with flags 0x" + Integer.toHexString(flags), new Throwable());
4778        }
4779
4780        return updateFlags(flags, userId);
4781    }
4782
4783    /**
4784     * Update given intent when being used to request {@link ResolveInfo}.
4785     */
4786    private Intent updateIntentForResolve(Intent intent) {
4787        if (intent.getSelector() != null) {
4788            intent = intent.getSelector();
4789        }
4790        if (DEBUG_PREFERRED) {
4791            intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
4792        }
4793        return intent;
4794    }
4795
4796    /**
4797     * Update given flags when being used to request {@link ResolveInfo}.
4798     * <p>Instant apps are resolved specially, depending upon context. Minimally,
4799     * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
4800     * flag set. However, this flag is only honoured in three circumstances:
4801     * <ul>
4802     * <li>when called from a system process</li>
4803     * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
4804     * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
4805     * action and a {@code android.intent.category.BROWSABLE} category</li>
4806     * </ul>
4807     */
4808    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
4809        return updateFlagsForResolve(flags, userId, intent, callingUid,
4810                false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
4811    }
4812    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4813            boolean wantInstantApps) {
4814        return updateFlagsForResolve(flags, userId, intent, callingUid,
4815                wantInstantApps, false /*onlyExposedExplicitly*/);
4816    }
4817    int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
4818            boolean wantInstantApps, boolean onlyExposedExplicitly) {
4819        // Safe mode means we shouldn't match any third-party components
4820        if (mSafeMode) {
4821            flags |= PackageManager.MATCH_SYSTEM_ONLY;
4822        }
4823        if (getInstantAppPackageName(callingUid) != null) {
4824            // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
4825            if (onlyExposedExplicitly) {
4826                flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
4827            }
4828            flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
4829            flags |= PackageManager.MATCH_INSTANT;
4830        } else {
4831            final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
4832            final boolean allowMatchInstant = wantInstantApps
4833                    || (wantMatchInstant && canViewInstantApps(callingUid, userId));
4834            flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
4835                    | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
4836            if (!allowMatchInstant) {
4837                flags &= ~PackageManager.MATCH_INSTANT;
4838            }
4839        }
4840        return updateFlagsForComponent(flags, userId, intent /*cookie*/);
4841    }
4842
4843    @Override
4844    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
4845        return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
4846    }
4847
4848    /**
4849     * Important: The provided filterCallingUid is used exclusively to filter out activities
4850     * that can be seen based on user state. It's typically the original caller uid prior
4851     * to clearing. Because it can only be provided by trusted code, it's value can be
4852     * trusted and will be used as-is; unlike userId which will be validated by this method.
4853     */
4854    private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
4855            int filterCallingUid, int userId) {
4856        if (!sUserManager.exists(userId)) return null;
4857        flags = updateFlagsForComponent(flags, userId, component);
4858
4859        if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4860            mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4861                    false /* requireFullPermission */, false /* checkShell */, "get activity info");
4862        }
4863
4864        synchronized (mPackages) {
4865            PackageParser.Activity a = mActivities.mActivities.get(component);
4866
4867            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
4868            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4869                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4870                if (ps == null) return null;
4871                if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
4872                    return null;
4873                }
4874                return PackageParser.generateActivityInfo(
4875                        a, flags, ps.readUserState(userId), userId);
4876            }
4877            if (mResolveComponentName.equals(component)) {
4878                return PackageParser.generateActivityInfo(
4879                        mResolveActivity, flags, new PackageUserState(), userId);
4880            }
4881        }
4882        return null;
4883    }
4884
4885    private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
4886        if (!getActivityManagerInternal().isCallerRecents(callingUid)) {
4887            return false;
4888        }
4889        final long token = Binder.clearCallingIdentity();
4890        try {
4891            final int callingUserId = UserHandle.getUserId(callingUid);
4892            if (ActivityManager.getCurrentUser() != callingUserId) {
4893                return false;
4894            }
4895            return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
4896        } finally {
4897            Binder.restoreCallingIdentity(token);
4898        }
4899    }
4900
4901    @Override
4902    public boolean activitySupportsIntent(ComponentName component, Intent intent,
4903            String resolvedType) {
4904        synchronized (mPackages) {
4905            if (component.equals(mResolveComponentName)) {
4906                // The resolver supports EVERYTHING!
4907                return true;
4908            }
4909            final int callingUid = Binder.getCallingUid();
4910            final int callingUserId = UserHandle.getUserId(callingUid);
4911            PackageParser.Activity a = mActivities.mActivities.get(component);
4912            if (a == null) {
4913                return false;
4914            }
4915            PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4916            if (ps == null) {
4917                return false;
4918            }
4919            if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
4920                return false;
4921            }
4922            for (int i=0; i<a.intents.size(); i++) {
4923                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
4924                        intent.getData(), intent.getCategories(), TAG) >= 0) {
4925                    return true;
4926                }
4927            }
4928            return false;
4929        }
4930    }
4931
4932    @Override
4933    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
4934        if (!sUserManager.exists(userId)) return null;
4935        final int callingUid = Binder.getCallingUid();
4936        flags = updateFlagsForComponent(flags, userId, component);
4937        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4938                false /* requireFullPermission */, false /* checkShell */, "get receiver info");
4939        synchronized (mPackages) {
4940            PackageParser.Activity a = mReceivers.mActivities.get(component);
4941            if (DEBUG_PACKAGE_INFO) Log.v(
4942                TAG, "getReceiverInfo " + component + ": " + a);
4943            if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
4944                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
4945                if (ps == null) return null;
4946                if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
4947                    return null;
4948                }
4949                return PackageParser.generateActivityInfo(
4950                        a, flags, ps.readUserState(userId), userId);
4951            }
4952        }
4953        return null;
4954    }
4955
4956    @Override
4957    public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
4958            int flags, int userId) {
4959        if (!sUserManager.exists(userId)) return null;
4960        Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
4961        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
4962            return null;
4963        }
4964
4965        flags = updateFlagsForPackage(flags, userId, null);
4966
4967        final boolean canSeeStaticLibraries =
4968                mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
4969                        == PERMISSION_GRANTED
4970                || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
4971                        == PERMISSION_GRANTED
4972                || canRequestPackageInstallsInternal(packageName,
4973                        PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
4974                        false  /* throwIfPermNotDeclared*/)
4975                || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
4976                        == PERMISSION_GRANTED;
4977
4978        synchronized (mPackages) {
4979            List<SharedLibraryInfo> result = null;
4980
4981            final int libCount = mSharedLibraries.size();
4982            for (int i = 0; i < libCount; i++) {
4983                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
4984                if (versionedLib == null) {
4985                    continue;
4986                }
4987
4988                final int versionCount = versionedLib.size();
4989                for (int j = 0; j < versionCount; j++) {
4990                    SharedLibraryInfo libInfo = versionedLib.valueAt(j).info;
4991                    if (!canSeeStaticLibraries && libInfo.isStatic()) {
4992                        break;
4993                    }
4994                    final long identity = Binder.clearCallingIdentity();
4995                    try {
4996                        PackageInfo packageInfo = getPackageInfoVersioned(
4997                                libInfo.getDeclaringPackage(), flags
4998                                        | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
4999                        if (packageInfo == null) {
5000                            continue;
5001                        }
5002                    } finally {
5003                        Binder.restoreCallingIdentity(identity);
5004                    }
5005
5006                    SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(),
5007                            libInfo.getLongVersion(), libInfo.getType(),
5008                            libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo,
5009                            flags, userId));
5010
5011                    if (result == null) {
5012                        result = new ArrayList<>();
5013                    }
5014                    result.add(resLibInfo);
5015                }
5016            }
5017
5018            return result != null ? new ParceledListSlice<>(result) : null;
5019        }
5020    }
5021
5022    private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5023            SharedLibraryInfo libInfo, int flags, int userId) {
5024        List<VersionedPackage> versionedPackages = null;
5025        final int packageCount = mSettings.mPackages.size();
5026        for (int i = 0; i < packageCount; i++) {
5027            PackageSetting ps = mSettings.mPackages.valueAt(i);
5028
5029            if (ps == null) {
5030                continue;
5031            }
5032
5033            if (!ps.getUserState().get(userId).isAvailable(flags)) {
5034                continue;
5035            }
5036
5037            final String libName = libInfo.getName();
5038            if (libInfo.isStatic()) {
5039                final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5040                if (libIdx < 0) {
5041                    continue;
5042                }
5043                if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5044                    continue;
5045                }
5046                if (versionedPackages == null) {
5047                    versionedPackages = new ArrayList<>();
5048                }
5049                // If the dependent is a static shared lib, use the public package name
5050                String dependentPackageName = ps.name;
5051                if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5052                    dependentPackageName = ps.pkg.manifestPackageName;
5053                }
5054                versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5055            } else if (ps.pkg != null) {
5056                if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5057                        || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5058                    if (versionedPackages == null) {
5059                        versionedPackages = new ArrayList<>();
5060                    }
5061                    versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5062                }
5063            }
5064        }
5065
5066        return versionedPackages;
5067    }
5068
5069    @Override
5070    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5071        if (!sUserManager.exists(userId)) return null;
5072        final int callingUid = Binder.getCallingUid();
5073        flags = updateFlagsForComponent(flags, userId, component);
5074        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5075                false /* requireFullPermission */, false /* checkShell */, "get service info");
5076        synchronized (mPackages) {
5077            PackageParser.Service s = mServices.mServices.get(component);
5078            if (DEBUG_PACKAGE_INFO) Log.v(
5079                TAG, "getServiceInfo " + component + ": " + s);
5080            if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5081                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5082                if (ps == null) return null;
5083                if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5084                    return null;
5085                }
5086                return PackageParser.generateServiceInfo(
5087                        s, flags, ps.readUserState(userId), userId);
5088            }
5089        }
5090        return null;
5091    }
5092
5093    @Override
5094    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5095        if (!sUserManager.exists(userId)) return null;
5096        final int callingUid = Binder.getCallingUid();
5097        flags = updateFlagsForComponent(flags, userId, component);
5098        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5099                false /* requireFullPermission */, false /* checkShell */, "get provider info");
5100        synchronized (mPackages) {
5101            PackageParser.Provider p = mProviders.mProviders.get(component);
5102            if (DEBUG_PACKAGE_INFO) Log.v(
5103                TAG, "getProviderInfo " + component + ": " + p);
5104            if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5105                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5106                if (ps == null) return null;
5107                if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5108                    return null;
5109                }
5110                return PackageParser.generateProviderInfo(
5111                        p, flags, ps.readUserState(userId), userId);
5112            }
5113        }
5114        return null;
5115    }
5116
5117    @Override
5118    public String[] getSystemSharedLibraryNames() {
5119        // allow instant applications
5120        synchronized (mPackages) {
5121            Set<String> libs = null;
5122            final int libCount = mSharedLibraries.size();
5123            for (int i = 0; i < libCount; i++) {
5124                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i);
5125                if (versionedLib == null) {
5126                    continue;
5127                }
5128                final int versionCount = versionedLib.size();
5129                for (int j = 0; j < versionCount; j++) {
5130                    SharedLibraryEntry libEntry = versionedLib.valueAt(j);
5131                    if (!libEntry.info.isStatic()) {
5132                        if (libs == null) {
5133                            libs = new ArraySet<>();
5134                        }
5135                        libs.add(libEntry.info.getName());
5136                        break;
5137                    }
5138                    PackageSetting ps = mSettings.getPackageLPr(libEntry.apk);
5139                    if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5140                            UserHandle.getUserId(Binder.getCallingUid()),
5141                            PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5142                        if (libs == null) {
5143                            libs = new ArraySet<>();
5144                        }
5145                        libs.add(libEntry.info.getName());
5146                        break;
5147                    }
5148                }
5149            }
5150
5151            if (libs != null) {
5152                String[] libsArray = new String[libs.size()];
5153                libs.toArray(libsArray);
5154                return libsArray;
5155            }
5156
5157            return null;
5158        }
5159    }
5160
5161    @Override
5162    public @NonNull String getServicesSystemSharedLibraryPackageName() {
5163        // allow instant applications
5164        synchronized (mPackages) {
5165            return mServicesSystemSharedLibraryPackageName;
5166        }
5167    }
5168
5169    @Override
5170    public @NonNull String getSharedSystemSharedLibraryPackageName() {
5171        // allow instant applications
5172        synchronized (mPackages) {
5173            return mSharedSystemSharedLibraryPackageName;
5174        }
5175    }
5176
5177    private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5178        for (int i = userList.length - 1; i >= 0; --i) {
5179            final int userId = userList[i];
5180            // don't add instant app to the list of updates
5181            if (pkgSetting.getInstantApp(userId)) {
5182                continue;
5183            }
5184            SparseArray<String> changedPackages = mChangedPackages.get(userId);
5185            if (changedPackages == null) {
5186                changedPackages = new SparseArray<>();
5187                mChangedPackages.put(userId, changedPackages);
5188            }
5189            Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5190            if (sequenceNumbers == null) {
5191                sequenceNumbers = new HashMap<>();
5192                mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5193            }
5194            final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5195            if (sequenceNumber != null) {
5196                changedPackages.remove(sequenceNumber);
5197            }
5198            changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5199            sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5200        }
5201        mChangedPackagesSequenceNumber++;
5202    }
5203
5204    @Override
5205    public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5206        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5207            return null;
5208        }
5209        synchronized (mPackages) {
5210            if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5211                return null;
5212            }
5213            final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5214            if (changedPackages == null) {
5215                return null;
5216            }
5217            final List<String> packageNames =
5218                    new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5219            for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5220                final String packageName = changedPackages.get(i);
5221                if (packageName != null) {
5222                    packageNames.add(packageName);
5223                }
5224            }
5225            return packageNames.isEmpty()
5226                    ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5227        }
5228    }
5229
5230    @Override
5231    public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5232        // allow instant applications
5233        ArrayList<FeatureInfo> res;
5234        synchronized (mAvailableFeatures) {
5235            res = new ArrayList<>(mAvailableFeatures.size() + 1);
5236            res.addAll(mAvailableFeatures.values());
5237        }
5238        final FeatureInfo fi = new FeatureInfo();
5239        fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5240                FeatureInfo.GL_ES_VERSION_UNDEFINED);
5241        res.add(fi);
5242
5243        return new ParceledListSlice<>(res);
5244    }
5245
5246    @Override
5247    public boolean hasSystemFeature(String name, int version) {
5248        // allow instant applications
5249        synchronized (mAvailableFeatures) {
5250            final FeatureInfo feat = mAvailableFeatures.get(name);
5251            if (feat == null) {
5252                return false;
5253            } else {
5254                return feat.version >= version;
5255            }
5256        }
5257    }
5258
5259    @Override
5260    public int checkPermission(String permName, String pkgName, int userId) {
5261        return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5262    }
5263
5264    @Override
5265    public int checkUidPermission(String permName, int uid) {
5266        synchronized (mPackages) {
5267            final String[] packageNames = getPackagesForUid(uid);
5268            final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0)
5269                    ? mPackages.get(packageNames[0])
5270                    : null;
5271            return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5272        }
5273    }
5274
5275    @Override
5276    public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5277        if (UserHandle.getCallingUserId() != userId) {
5278            mContext.enforceCallingPermission(
5279                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5280                    "isPermissionRevokedByPolicy for user " + userId);
5281        }
5282
5283        if (checkPermission(permission, packageName, userId)
5284                == PackageManager.PERMISSION_GRANTED) {
5285            return false;
5286        }
5287
5288        final int callingUid = Binder.getCallingUid();
5289        if (getInstantAppPackageName(callingUid) != null) {
5290            if (!isCallerSameApp(packageName, callingUid)) {
5291                return false;
5292            }
5293        } else {
5294            if (isInstantApp(packageName, userId)) {
5295                return false;
5296            }
5297        }
5298
5299        final long identity = Binder.clearCallingIdentity();
5300        try {
5301            final int flags = getPermissionFlags(permission, packageName, userId);
5302            return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5303        } finally {
5304            Binder.restoreCallingIdentity(identity);
5305        }
5306    }
5307
5308    @Override
5309    public String getPermissionControllerPackageName() {
5310        synchronized (mPackages) {
5311            return mRequiredInstallerPackage;
5312        }
5313    }
5314
5315    private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5316        return mPermissionManager.addDynamicPermission(
5317                info, async, getCallingUid(), new PermissionCallback() {
5318                    @Override
5319                    public void onPermissionChanged() {
5320                        if (!async) {
5321                            mSettings.writeLPr();
5322                        } else {
5323                            scheduleWriteSettingsLocked();
5324                        }
5325                    }
5326                });
5327    }
5328
5329    @Override
5330    public boolean addPermission(PermissionInfo info) {
5331        synchronized (mPackages) {
5332            return addDynamicPermission(info, false);
5333        }
5334    }
5335
5336    @Override
5337    public boolean addPermissionAsync(PermissionInfo info) {
5338        synchronized (mPackages) {
5339            return addDynamicPermission(info, true);
5340        }
5341    }
5342
5343    @Override
5344    public void removePermission(String permName) {
5345        mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5346    }
5347
5348    @Override
5349    public void grantRuntimePermission(String packageName, String permName, final int userId) {
5350        mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/,
5351                getCallingUid(), userId, mPermissionCallback);
5352    }
5353
5354    @Override
5355    public void revokeRuntimePermission(String packageName, String permName, int userId) {
5356        mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/,
5357                getCallingUid(), userId, mPermissionCallback);
5358    }
5359
5360    @Override
5361    public void resetRuntimePermissions() {
5362        mContext.enforceCallingOrSelfPermission(
5363                android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5364                "revokeRuntimePermission");
5365
5366        int callingUid = Binder.getCallingUid();
5367        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5368            mContext.enforceCallingOrSelfPermission(
5369                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5370                    "resetRuntimePermissions");
5371        }
5372
5373        synchronized (mPackages) {
5374            mPermissionManager.updateAllPermissions(
5375                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5376                    mPermissionCallback);
5377            for (int userId : UserManagerService.getInstance().getUserIds()) {
5378                final int packageCount = mPackages.size();
5379                for (int i = 0; i < packageCount; i++) {
5380                    PackageParser.Package pkg = mPackages.valueAt(i);
5381                    if (!(pkg.mExtras instanceof PackageSetting)) {
5382                        continue;
5383                    }
5384                    PackageSetting ps = (PackageSetting) pkg.mExtras;
5385                    resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5386                }
5387            }
5388        }
5389    }
5390
5391    @Override
5392    public int getPermissionFlags(String permName, String packageName, int userId) {
5393        return mPermissionManager.getPermissionFlags(
5394                permName, packageName, getCallingUid(), userId);
5395    }
5396
5397    @Override
5398    public void updatePermissionFlags(String permName, String packageName, int flagMask,
5399            int flagValues, int userId) {
5400        mPermissionManager.updatePermissionFlags(
5401                permName, packageName, flagMask, flagValues, getCallingUid(), userId,
5402                mPermissionCallback);
5403    }
5404
5405    /**
5406     * Update the permission flags for all packages and runtime permissions of a user in order
5407     * to allow device or profile owner to remove POLICY_FIXED.
5408     */
5409    @Override
5410    public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5411        synchronized (mPackages) {
5412            final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5413                    flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5414                    mPermissionCallback);
5415            if (changed) {
5416                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5417            }
5418        }
5419    }
5420
5421    @Override
5422    public boolean shouldShowRequestPermissionRationale(String permissionName,
5423            String packageName, int userId) {
5424        if (UserHandle.getCallingUserId() != userId) {
5425            mContext.enforceCallingPermission(
5426                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5427                    "canShowRequestPermissionRationale for user " + userId);
5428        }
5429
5430        final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
5431        if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
5432            return false;
5433        }
5434
5435        if (checkPermission(permissionName, packageName, userId)
5436                == PackageManager.PERMISSION_GRANTED) {
5437            return false;
5438        }
5439
5440        final int flags;
5441
5442        final long identity = Binder.clearCallingIdentity();
5443        try {
5444            flags = getPermissionFlags(permissionName,
5445                    packageName, userId);
5446        } finally {
5447            Binder.restoreCallingIdentity(identity);
5448        }
5449
5450        final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
5451                | PackageManager.FLAG_PERMISSION_POLICY_FIXED
5452                | PackageManager.FLAG_PERMISSION_USER_FIXED;
5453
5454        if ((flags & fixedFlags) != 0) {
5455            return false;
5456        }
5457
5458        return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
5459    }
5460
5461    @Override
5462    public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5463        mContext.enforceCallingOrSelfPermission(
5464                Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
5465                "addOnPermissionsChangeListener");
5466
5467        synchronized (mPackages) {
5468            mOnPermissionChangeListeners.addListenerLocked(listener);
5469        }
5470    }
5471
5472    @Override
5473    public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
5474        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5475            throw new SecurityException("Instant applications don't have access to this method");
5476        }
5477        synchronized (mPackages) {
5478            mOnPermissionChangeListeners.removeListenerLocked(listener);
5479        }
5480    }
5481
5482    @Override
5483    public boolean isProtectedBroadcast(String actionName) {
5484        // allow instant applications
5485        synchronized (mProtectedBroadcasts) {
5486            if (mProtectedBroadcasts.contains(actionName)) {
5487                return true;
5488            } else if (actionName != null) {
5489                // TODO: remove these terrible hacks
5490                if (actionName.startsWith("android.net.netmon.lingerExpired")
5491                        || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5492                        || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5493                        || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5494                    return true;
5495                }
5496            }
5497        }
5498        return false;
5499    }
5500
5501    @Override
5502    public int checkSignatures(String pkg1, String pkg2) {
5503        synchronized (mPackages) {
5504            final PackageParser.Package p1 = mPackages.get(pkg1);
5505            final PackageParser.Package p2 = mPackages.get(pkg2);
5506            if (p1 == null || p1.mExtras == null
5507                    || p2 == null || p2.mExtras == null) {
5508                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5509            }
5510            final int callingUid = Binder.getCallingUid();
5511            final int callingUserId = UserHandle.getUserId(callingUid);
5512            final PackageSetting ps1 = (PackageSetting) p1.mExtras;
5513            final PackageSetting ps2 = (PackageSetting) p2.mExtras;
5514            if (filterAppAccessLPr(ps1, callingUid, callingUserId)
5515                    || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
5516                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5517            }
5518            return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
5519        }
5520    }
5521
5522    @Override
5523    public int checkUidSignatures(int uid1, int uid2) {
5524        final int callingUid = Binder.getCallingUid();
5525        final int callingUserId = UserHandle.getUserId(callingUid);
5526        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5527        // Map to base uids.
5528        uid1 = UserHandle.getAppId(uid1);
5529        uid2 = UserHandle.getAppId(uid2);
5530        // reader
5531        synchronized (mPackages) {
5532            Signature[] s1;
5533            Signature[] s2;
5534            Object obj = mSettings.getUserIdLPr(uid1);
5535            if (obj != null) {
5536                if (obj instanceof SharedUserSetting) {
5537                    if (isCallerInstantApp) {
5538                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5539                    }
5540                    s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5541                } else if (obj instanceof PackageSetting) {
5542                    final PackageSetting ps = (PackageSetting) obj;
5543                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5544                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5545                    }
5546                    s1 = ps.signatures.mSigningDetails.signatures;
5547                } else {
5548                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5549                }
5550            } else {
5551                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5552            }
5553            obj = mSettings.getUserIdLPr(uid2);
5554            if (obj != null) {
5555                if (obj instanceof SharedUserSetting) {
5556                    if (isCallerInstantApp) {
5557                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5558                    }
5559                    s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
5560                } else if (obj instanceof PackageSetting) {
5561                    final PackageSetting ps = (PackageSetting) obj;
5562                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5563                        return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5564                    }
5565                    s2 = ps.signatures.mSigningDetails.signatures;
5566                } else {
5567                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5568                }
5569            } else {
5570                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
5571            }
5572            return compareSignatures(s1, s2);
5573        }
5574    }
5575
5576    @Override
5577    public boolean hasSigningCertificate(
5578            String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
5579
5580        synchronized (mPackages) {
5581            final PackageParser.Package p = mPackages.get(packageName);
5582            if (p == null || p.mExtras == null) {
5583                return false;
5584            }
5585            final int callingUid = Binder.getCallingUid();
5586            final int callingUserId = UserHandle.getUserId(callingUid);
5587            final PackageSetting ps = (PackageSetting) p.mExtras;
5588            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5589                return false;
5590            }
5591            switch (type) {
5592                case CERT_INPUT_RAW_X509:
5593                    return p.mSigningDetails.hasCertificate(certificate);
5594                case CERT_INPUT_SHA256:
5595                    return p.mSigningDetails.hasSha256Certificate(certificate);
5596                default:
5597                    return false;
5598            }
5599        }
5600    }
5601
5602    @Override
5603    public boolean hasUidSigningCertificate(
5604            int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
5605        final int callingUid = Binder.getCallingUid();
5606        final int callingUserId = UserHandle.getUserId(callingUid);
5607        // Map to base uids.
5608        uid = UserHandle.getAppId(uid);
5609        // reader
5610        synchronized (mPackages) {
5611            final PackageParser.SigningDetails signingDetails;
5612            final Object obj = mSettings.getUserIdLPr(uid);
5613            if (obj != null) {
5614                if (obj instanceof SharedUserSetting) {
5615                    final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5616                    if (isCallerInstantApp) {
5617                        return false;
5618                    }
5619                    signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
5620                } else if (obj instanceof PackageSetting) {
5621                    final PackageSetting ps = (PackageSetting) obj;
5622                    if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
5623                        return false;
5624                    }
5625                    signingDetails = ps.signatures.mSigningDetails;
5626                } else {
5627                    return false;
5628                }
5629            } else {
5630                return false;
5631            }
5632            switch (type) {
5633                case CERT_INPUT_RAW_X509:
5634                    return signingDetails.hasCertificate(certificate);
5635                case CERT_INPUT_SHA256:
5636                    return signingDetails.hasSha256Certificate(certificate);
5637                default:
5638                    return false;
5639            }
5640        }
5641    }
5642
5643    /**
5644     * This method should typically only be used when granting or revoking
5645     * permissions, since the app may immediately restart after this call.
5646     * <p>
5647     * If you're doing surgery on app code/data, use {@link PackageFreezer} to
5648     * guard your work against the app being relaunched.
5649     */
5650    private void killUid(int appId, int userId, String reason) {
5651        final long identity = Binder.clearCallingIdentity();
5652        try {
5653            IActivityManager am = ActivityManager.getService();
5654            if (am != null) {
5655                try {
5656                    am.killUid(appId, userId, reason);
5657                } catch (RemoteException e) {
5658                    /* ignore - same process */
5659                }
5660            }
5661        } finally {
5662            Binder.restoreCallingIdentity(identity);
5663        }
5664    }
5665
5666    /**
5667     * If the database version for this type of package (internal storage or
5668     * external storage) is less than the version where package signatures
5669     * were updated, return true.
5670     */
5671    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5672        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5673        return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
5674    }
5675
5676    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
5677        final VersionInfo ver = getSettingsVersionForPackage(scannedPkg);
5678        return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
5679    }
5680
5681    @Override
5682    public List<String> getAllPackages() {
5683        final int callingUid = Binder.getCallingUid();
5684        final int callingUserId = UserHandle.getUserId(callingUid);
5685        synchronized (mPackages) {
5686            if (canViewInstantApps(callingUid, callingUserId)) {
5687                return new ArrayList<String>(mPackages.keySet());
5688            }
5689            final String instantAppPkgName = getInstantAppPackageName(callingUid);
5690            final List<String> result = new ArrayList<>();
5691            if (instantAppPkgName != null) {
5692                // caller is an instant application; filter unexposed applications
5693                for (PackageParser.Package pkg : mPackages.values()) {
5694                    if (!pkg.visibleToInstantApps) {
5695                        continue;
5696                    }
5697                    result.add(pkg.packageName);
5698                }
5699            } else {
5700                // caller is a normal application; filter instant applications
5701                for (PackageParser.Package pkg : mPackages.values()) {
5702                    final PackageSetting ps =
5703                            pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
5704                    if (ps != null
5705                            && ps.getInstantApp(callingUserId)
5706                            && !mInstantAppRegistry.isInstantAccessGranted(
5707                                    callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
5708                        continue;
5709                    }
5710                    result.add(pkg.packageName);
5711                }
5712            }
5713            return result;
5714        }
5715    }
5716
5717    @Override
5718    public String[] getPackagesForUid(int uid) {
5719        final int callingUid = Binder.getCallingUid();
5720        final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
5721        final int userId = UserHandle.getUserId(uid);
5722        uid = UserHandle.getAppId(uid);
5723        // reader
5724        synchronized (mPackages) {
5725            Object obj = mSettings.getUserIdLPr(uid);
5726            if (obj instanceof SharedUserSetting) {
5727                if (isCallerInstantApp) {
5728                    return null;
5729                }
5730                final SharedUserSetting sus = (SharedUserSetting) obj;
5731                final int N = sus.packages.size();
5732                String[] res = new String[N];
5733                final Iterator<PackageSetting> it = sus.packages.iterator();
5734                int i = 0;
5735                while (it.hasNext()) {
5736                    PackageSetting ps = it.next();
5737                    if (ps.getInstalled(userId)) {
5738                        res[i++] = ps.name;
5739                    } else {
5740                        res = ArrayUtils.removeElement(String.class, res, res[i]);
5741                    }
5742                }
5743                return res;
5744            } else if (obj instanceof PackageSetting) {
5745                final PackageSetting ps = (PackageSetting) obj;
5746                if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
5747                    return new String[]{ps.name};
5748                }
5749            }
5750        }
5751        return null;
5752    }
5753
5754    @Override
5755    public String getNameForUid(int uid) {
5756        final int callingUid = Binder.getCallingUid();
5757        if (getInstantAppPackageName(callingUid) != null) {
5758            return null;
5759        }
5760        synchronized (mPackages) {
5761            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5762            if (obj instanceof SharedUserSetting) {
5763                final SharedUserSetting sus = (SharedUserSetting) obj;
5764                return sus.name + ":" + sus.userId;
5765            } else if (obj instanceof PackageSetting) {
5766                final PackageSetting ps = (PackageSetting) obj;
5767                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5768                    return null;
5769                }
5770                return ps.name;
5771            }
5772            return null;
5773        }
5774    }
5775
5776    @Override
5777    public String[] getNamesForUids(int[] uids) {
5778        if (uids == null || uids.length == 0) {
5779            return null;
5780        }
5781        final int callingUid = Binder.getCallingUid();
5782        if (getInstantAppPackageName(callingUid) != null) {
5783            return null;
5784        }
5785        final String[] names = new String[uids.length];
5786        synchronized (mPackages) {
5787            for (int i = uids.length - 1; i >= 0; i--) {
5788                final int uid = uids[i];
5789                Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5790                if (obj instanceof SharedUserSetting) {
5791                    final SharedUserSetting sus = (SharedUserSetting) obj;
5792                    names[i] = "shared:" + sus.name;
5793                } else if (obj instanceof PackageSetting) {
5794                    final PackageSetting ps = (PackageSetting) obj;
5795                    if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5796                        names[i] = null;
5797                    } else {
5798                        names[i] = ps.name;
5799                    }
5800                } else {
5801                    names[i] = null;
5802                }
5803            }
5804        }
5805        return names;
5806    }
5807
5808    @Override
5809    public int getUidForSharedUser(String sharedUserName) {
5810        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5811            return -1;
5812        }
5813        if (sharedUserName == null) {
5814            return -1;
5815        }
5816        // reader
5817        synchronized (mPackages) {
5818            SharedUserSetting suid;
5819            try {
5820                suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
5821                if (suid != null) {
5822                    return suid.userId;
5823                }
5824            } catch (PackageManagerException ignore) {
5825                // can't happen, but, still need to catch it
5826            }
5827            return -1;
5828        }
5829    }
5830
5831    @Override
5832    public int getFlagsForUid(int uid) {
5833        final int callingUid = Binder.getCallingUid();
5834        if (getInstantAppPackageName(callingUid) != null) {
5835            return 0;
5836        }
5837        synchronized (mPackages) {
5838            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5839            if (obj instanceof SharedUserSetting) {
5840                final SharedUserSetting sus = (SharedUserSetting) obj;
5841                return sus.pkgFlags;
5842            } else if (obj instanceof PackageSetting) {
5843                final PackageSetting ps = (PackageSetting) obj;
5844                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5845                    return 0;
5846                }
5847                return ps.pkgFlags;
5848            }
5849        }
5850        return 0;
5851    }
5852
5853    @Override
5854    public int getPrivateFlagsForUid(int uid) {
5855        final int callingUid = Binder.getCallingUid();
5856        if (getInstantAppPackageName(callingUid) != null) {
5857            return 0;
5858        }
5859        synchronized (mPackages) {
5860            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
5861            if (obj instanceof SharedUserSetting) {
5862                final SharedUserSetting sus = (SharedUserSetting) obj;
5863                return sus.pkgPrivateFlags;
5864            } else if (obj instanceof PackageSetting) {
5865                final PackageSetting ps = (PackageSetting) obj;
5866                if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
5867                    return 0;
5868                }
5869                return ps.pkgPrivateFlags;
5870            }
5871        }
5872        return 0;
5873    }
5874
5875    @Override
5876    public boolean isUidPrivileged(int uid) {
5877        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5878            return false;
5879        }
5880        uid = UserHandle.getAppId(uid);
5881        // reader
5882        synchronized (mPackages) {
5883            Object obj = mSettings.getUserIdLPr(uid);
5884            if (obj instanceof SharedUserSetting) {
5885                final SharedUserSetting sus = (SharedUserSetting) obj;
5886                final Iterator<PackageSetting> it = sus.packages.iterator();
5887                while (it.hasNext()) {
5888                    if (it.next().isPrivileged()) {
5889                        return true;
5890                    }
5891                }
5892            } else if (obj instanceof PackageSetting) {
5893                final PackageSetting ps = (PackageSetting) obj;
5894                return ps.isPrivileged();
5895            }
5896        }
5897        return false;
5898    }
5899
5900    @Override
5901    public String[] getAppOpPermissionPackages(String permName) {
5902        return mPermissionManager.getAppOpPermissionPackages(permName);
5903    }
5904
5905    @Override
5906    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
5907            int flags, int userId) {
5908        return resolveIntentInternal(
5909                intent, resolvedType, flags, userId, false /*resolveForStart*/);
5910    }
5911
5912    /**
5913     * Normally instant apps can only be resolved when they're visible to the caller.
5914     * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
5915     * since we need to allow the system to start any installed application.
5916     */
5917    private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
5918            int flags, int userId, boolean resolveForStart) {
5919        try {
5920            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
5921
5922            if (!sUserManager.exists(userId)) return null;
5923            final int callingUid = Binder.getCallingUid();
5924            flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart);
5925            mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5926                    false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
5927
5928            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
5929            final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
5930                    flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
5931            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5932
5933            final ResolveInfo bestChoice =
5934                    chooseBestActivity(intent, resolvedType, flags, query, userId);
5935            return bestChoice;
5936        } finally {
5937            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
5938        }
5939    }
5940
5941    @Override
5942    public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
5943        if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
5944            throw new SecurityException(
5945                    "findPersistentPreferredActivity can only be run by the system");
5946        }
5947        if (!sUserManager.exists(userId)) {
5948            return null;
5949        }
5950        final int callingUid = Binder.getCallingUid();
5951        intent = updateIntentForResolve(intent);
5952        final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
5953        final int flags = updateFlagsForResolve(
5954                0, userId, intent, callingUid, false /*includeInstantApps*/);
5955        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5956                userId);
5957        synchronized (mPackages) {
5958            return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
5959                    userId);
5960        }
5961    }
5962
5963    @Override
5964    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
5965            IntentFilter filter, int match, ComponentName activity) {
5966        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5967            return;
5968        }
5969        final int userId = UserHandle.getCallingUserId();
5970        if (DEBUG_PREFERRED) {
5971            Log.v(TAG, "setLastChosenActivity intent=" + intent
5972                + " resolvedType=" + resolvedType
5973                + " flags=" + flags
5974                + " filter=" + filter
5975                + " match=" + match
5976                + " activity=" + activity);
5977            filter.dump(new PrintStreamPrinter(System.out), "    ");
5978        }
5979        intent.setComponent(null);
5980        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5981                userId);
5982        // Find any earlier preferred or last chosen entries and nuke them
5983        findPreferredActivity(intent, resolvedType,
5984                flags, query, 0, false, true, false, userId);
5985        // Add the new activity as the last chosen for this filter
5986        addPreferredActivityInternal(filter, match, null, activity, false, userId,
5987                "Setting last chosen");
5988    }
5989
5990    @Override
5991    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5992        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5993            return null;
5994        }
5995        final int userId = UserHandle.getCallingUserId();
5996        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
5997        final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
5998                userId);
5999        return findPreferredActivity(intent, resolvedType, flags, query, 0,
6000                false, false, false, userId);
6001    }
6002
6003    /**
6004     * Returns whether or not instant apps have been disabled remotely.
6005     */
6006    private boolean areWebInstantAppsDisabled() {
6007        return mWebInstantAppsDisabled;
6008    }
6009
6010    private boolean isInstantAppResolutionAllowed(
6011            Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6012            boolean skipPackageCheck) {
6013        if (mInstantAppResolverConnection == null) {
6014            return false;
6015        }
6016        if (mInstantAppInstallerActivity == null) {
6017            return false;
6018        }
6019        if (intent.getComponent() != null) {
6020            return false;
6021        }
6022        if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6023            return false;
6024        }
6025        if (!skipPackageCheck && intent.getPackage() != null) {
6026            return false;
6027        }
6028        if (!intent.isWebIntent()) {
6029            // for non web intents, we should not resolve externally if an app already exists to
6030            // handle it or if the caller didn't explicitly request it.
6031            if ((resolvedActivities != null && resolvedActivities.size() != 0)
6032                    || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6033                return false;
6034            }
6035        } else {
6036            if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6037                return false;
6038            } else if (areWebInstantAppsDisabled()) {
6039                return false;
6040            }
6041        }
6042        // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6043        // Or if there's already an ephemeral app installed that handles the action
6044        synchronized (mPackages) {
6045            final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6046            for (int n = 0; n < count; n++) {
6047                final ResolveInfo info = resolvedActivities.get(n);
6048                final String packageName = info.activityInfo.packageName;
6049                final PackageSetting ps = mSettings.mPackages.get(packageName);
6050                if (ps != null) {
6051                    // only check domain verification status if the app is not a browser
6052                    if (!info.handleAllWebDataURI) {
6053                        // Try to get the status from User settings first
6054                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6055                        final int status = (int) (packedStatus >> 32);
6056                        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6057                            || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6058                            if (DEBUG_INSTANT) {
6059                                Slog.v(TAG, "DENY instant app;"
6060                                    + " pkg: " + packageName + ", status: " + status);
6061                            }
6062                            return false;
6063                        }
6064                    }
6065                    if (ps.getInstantApp(userId)) {
6066                        if (DEBUG_INSTANT) {
6067                            Slog.v(TAG, "DENY instant app installed;"
6068                                    + " pkg: " + packageName);
6069                        }
6070                        return false;
6071                    }
6072                }
6073            }
6074        }
6075        // We've exhausted all ways to deny ephemeral application; let the system look for them.
6076        return true;
6077    }
6078
6079    private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6080            Intent origIntent, String resolvedType, String callingPackage,
6081            Bundle verificationBundle, int userId) {
6082        final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6083                new InstantAppRequest(responseObj, origIntent, resolvedType,
6084                        callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6085        mHandler.sendMessage(msg);
6086    }
6087
6088    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6089            int flags, List<ResolveInfo> query, int userId) {
6090        if (query != null) {
6091            final int N = query.size();
6092            if (N == 1) {
6093                return query.get(0);
6094            } else if (N > 1) {
6095                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6096                // If there is more than one activity with the same priority,
6097                // then let the user decide between them.
6098                ResolveInfo r0 = query.get(0);
6099                ResolveInfo r1 = query.get(1);
6100                if (DEBUG_INTENT_MATCHING || debug) {
6101                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6102                            + r1.activityInfo.name + "=" + r1.priority);
6103                }
6104                // If the first activity has a higher priority, or a different
6105                // default, then it is always desirable to pick it.
6106                if (r0.priority != r1.priority
6107                        || r0.preferredOrder != r1.preferredOrder
6108                        || r0.isDefault != r1.isDefault) {
6109                    return query.get(0);
6110                }
6111                // If we have saved a preference for a preferred activity for
6112                // this Intent, use that.
6113                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
6114                        flags, query, r0.priority, true, false, debug, userId);
6115                if (ri != null) {
6116                    return ri;
6117                }
6118                // If we have an ephemeral app, use it
6119                for (int i = 0; i < N; i++) {
6120                    ri = query.get(i);
6121                    if (ri.activityInfo.applicationInfo.isInstantApp()) {
6122                        final String packageName = ri.activityInfo.packageName;
6123                        final PackageSetting ps = mSettings.mPackages.get(packageName);
6124                        final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6125                        final int status = (int)(packedStatus >> 32);
6126                        if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6127                            return ri;
6128                        }
6129                    }
6130                }
6131                ri = new ResolveInfo(mResolveInfo);
6132                ri.activityInfo = new ActivityInfo(ri.activityInfo);
6133                ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6134                // If all of the options come from the same package, show the application's
6135                // label and icon instead of the generic resolver's.
6136                // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6137                // and then throw away the ResolveInfo itself, meaning that the caller loses
6138                // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6139                // a fallback for this case; we only set the target package's resources on
6140                // the ResolveInfo, not the ActivityInfo.
6141                final String intentPackage = intent.getPackage();
6142                if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6143                    final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6144                    ri.resolvePackageName = intentPackage;
6145                    if (userNeedsBadging(userId)) {
6146                        ri.noResourceId = true;
6147                    } else {
6148                        ri.icon = appi.icon;
6149                    }
6150                    ri.iconResourceId = appi.icon;
6151                    ri.labelRes = appi.labelRes;
6152                }
6153                ri.activityInfo.applicationInfo = new ApplicationInfo(
6154                        ri.activityInfo.applicationInfo);
6155                if (userId != 0) {
6156                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6157                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6158                }
6159                // Make sure that the resolver is displayable in car mode
6160                if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6161                ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6162                return ri;
6163            }
6164        }
6165        return null;
6166    }
6167
6168    /**
6169     * Return true if the given list is not empty and all of its contents have
6170     * an activityInfo with the given package name.
6171     */
6172    private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6173        if (ArrayUtils.isEmpty(list)) {
6174            return false;
6175        }
6176        for (int i = 0, N = list.size(); i < N; i++) {
6177            final ResolveInfo ri = list.get(i);
6178            final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6179            if (ai == null || !packageName.equals(ai.packageName)) {
6180                return false;
6181            }
6182        }
6183        return true;
6184    }
6185
6186    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6187            int flags, List<ResolveInfo> query, boolean debug, int userId) {
6188        final int N = query.size();
6189        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6190                .get(userId);
6191        // Get the list of persistent preferred activities that handle the intent
6192        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6193        List<PersistentPreferredActivity> pprefs = ppir != null
6194                ? ppir.queryIntent(intent, resolvedType,
6195                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6196                        userId)
6197                : null;
6198        if (pprefs != null && pprefs.size() > 0) {
6199            final int M = pprefs.size();
6200            for (int i=0; i<M; i++) {
6201                final PersistentPreferredActivity ppa = pprefs.get(i);
6202                if (DEBUG_PREFERRED || debug) {
6203                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6204                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6205                            + "\n  component=" + ppa.mComponent);
6206                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6207                }
6208                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6209                        flags | MATCH_DISABLED_COMPONENTS, userId);
6210                if (DEBUG_PREFERRED || debug) {
6211                    Slog.v(TAG, "Found persistent preferred activity:");
6212                    if (ai != null) {
6213                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6214                    } else {
6215                        Slog.v(TAG, "  null");
6216                    }
6217                }
6218                if (ai == null) {
6219                    // This previously registered persistent preferred activity
6220                    // component is no longer known. Ignore it and do NOT remove it.
6221                    continue;
6222                }
6223                for (int j=0; j<N; j++) {
6224                    final ResolveInfo ri = query.get(j);
6225                    if (!ri.activityInfo.applicationInfo.packageName
6226                            .equals(ai.applicationInfo.packageName)) {
6227                        continue;
6228                    }
6229                    if (!ri.activityInfo.name.equals(ai.name)) {
6230                        continue;
6231                    }
6232                    //  Found a persistent preference that can handle the intent.
6233                    if (DEBUG_PREFERRED || debug) {
6234                        Slog.v(TAG, "Returning persistent preferred activity: " +
6235                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6236                    }
6237                    return ri;
6238                }
6239            }
6240        }
6241        return null;
6242    }
6243
6244    // TODO: handle preferred activities missing while user has amnesia
6245    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
6246            List<ResolveInfo> query, int priority, boolean always,
6247            boolean removeMatches, boolean debug, int userId) {
6248        if (!sUserManager.exists(userId)) return null;
6249        final int callingUid = Binder.getCallingUid();
6250        flags = updateFlagsForResolve(
6251                flags, userId, intent, callingUid, false /*includeInstantApps*/);
6252        intent = updateIntentForResolve(intent);
6253        // writer
6254        synchronized (mPackages) {
6255            // Try to find a matching persistent preferred activity.
6256            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6257                    debug, userId);
6258
6259            // If a persistent preferred activity matched, use it.
6260            if (pri != null) {
6261                return pri;
6262            }
6263
6264            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6265            // Get the list of preferred activities that handle the intent
6266            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6267            List<PreferredActivity> prefs = pir != null
6268                    ? pir.queryIntent(intent, resolvedType,
6269                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6270                            userId)
6271                    : null;
6272            if (prefs != null && prefs.size() > 0) {
6273                boolean changed = false;
6274                try {
6275                    // First figure out how good the original match set is.
6276                    // We will only allow preferred activities that came
6277                    // from the same match quality.
6278                    int match = 0;
6279
6280                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6281
6282                    final int N = query.size();
6283                    for (int j=0; j<N; j++) {
6284                        final ResolveInfo ri = query.get(j);
6285                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6286                                + ": 0x" + Integer.toHexString(match));
6287                        if (ri.match > match) {
6288                            match = ri.match;
6289                        }
6290                    }
6291
6292                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6293                            + Integer.toHexString(match));
6294
6295                    match &= IntentFilter.MATCH_CATEGORY_MASK;
6296                    final int M = prefs.size();
6297                    for (int i=0; i<M; i++) {
6298                        final PreferredActivity pa = prefs.get(i);
6299                        if (DEBUG_PREFERRED || debug) {
6300                            Slog.v(TAG, "Checking PreferredActivity ds="
6301                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6302                                    + "\n  component=" + pa.mPref.mComponent);
6303                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6304                        }
6305                        if (pa.mPref.mMatch != match) {
6306                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6307                                    + Integer.toHexString(pa.mPref.mMatch));
6308                            continue;
6309                        }
6310                        // If it's not an "always" type preferred activity and that's what we're
6311                        // looking for, skip it.
6312                        if (always && !pa.mPref.mAlways) {
6313                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6314                            continue;
6315                        }
6316                        final ActivityInfo ai = getActivityInfo(
6317                                pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6318                                        | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6319                                userId);
6320                        if (DEBUG_PREFERRED || debug) {
6321                            Slog.v(TAG, "Found preferred activity:");
6322                            if (ai != null) {
6323                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6324                            } else {
6325                                Slog.v(TAG, "  null");
6326                            }
6327                        }
6328                        if (ai == null) {
6329                            // This previously registered preferred activity
6330                            // component is no longer known.  Most likely an update
6331                            // to the app was installed and in the new version this
6332                            // component no longer exists.  Clean it up by removing
6333                            // it from the preferred activities list, and skip it.
6334                            Slog.w(TAG, "Removing dangling preferred activity: "
6335                                    + pa.mPref.mComponent);
6336                            pir.removeFilter(pa);
6337                            changed = true;
6338                            continue;
6339                        }
6340                        for (int j=0; j<N; j++) {
6341                            final ResolveInfo ri = query.get(j);
6342                            if (!ri.activityInfo.applicationInfo.packageName
6343                                    .equals(ai.applicationInfo.packageName)) {
6344                                continue;
6345                            }
6346                            if (!ri.activityInfo.name.equals(ai.name)) {
6347                                continue;
6348                            }
6349
6350                            if (removeMatches) {
6351                                pir.removeFilter(pa);
6352                                changed = true;
6353                                if (DEBUG_PREFERRED) {
6354                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
6355                                }
6356                                break;
6357                            }
6358
6359                            // Okay we found a previously set preferred or last chosen app.
6360                            // If the result set is different from when this
6361                            // was created, and is not a subset of the preferred set, we need to
6362                            // clear it and re-ask the user their preference, if we're looking for
6363                            // an "always" type entry.
6364                            if (always && !pa.mPref.sameSet(query)) {
6365                                if (pa.mPref.isSuperset(query)) {
6366                                    // some components of the set are no longer present in
6367                                    // the query, but the preferred activity can still be reused
6368                                    if (DEBUG_PREFERRED) {
6369                                        Slog.i(TAG, "Result set changed, but PreferredActivity is"
6370                                                + " still valid as only non-preferred components"
6371                                                + " were removed for " + intent + " type "
6372                                                + resolvedType);
6373                                    }
6374                                    // remove obsolete components and re-add the up-to-date filter
6375                                    PreferredActivity freshPa = new PreferredActivity(pa,
6376                                            pa.mPref.mMatch,
6377                                            pa.mPref.discardObsoleteComponents(query),
6378                                            pa.mPref.mComponent,
6379                                            pa.mPref.mAlways);
6380                                    pir.removeFilter(pa);
6381                                    pir.addFilter(freshPa);
6382                                    changed = true;
6383                                } else {
6384                                    Slog.i(TAG,
6385                                            "Result set changed, dropping preferred activity for "
6386                                                    + intent + " type " + resolvedType);
6387                                    if (DEBUG_PREFERRED) {
6388                                        Slog.v(TAG, "Removing preferred activity since set changed "
6389                                                + pa.mPref.mComponent);
6390                                    }
6391                                    pir.removeFilter(pa);
6392                                    // Re-add the filter as a "last chosen" entry (!always)
6393                                    PreferredActivity lastChosen = new PreferredActivity(
6394                                            pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
6395                                    pir.addFilter(lastChosen);
6396                                    changed = true;
6397                                    return null;
6398                                }
6399                            }
6400
6401                            // Yay! Either the set matched or we're looking for the last chosen
6402                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
6403                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6404                            return ri;
6405                        }
6406                    }
6407                } finally {
6408                    if (changed) {
6409                        if (DEBUG_PREFERRED) {
6410                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
6411                        }
6412                        scheduleWritePackageRestrictionsLocked(userId);
6413                    }
6414                }
6415            }
6416        }
6417        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
6418        return null;
6419    }
6420
6421    /*
6422     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
6423     */
6424    @Override
6425    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
6426            int targetUserId) {
6427        mContext.enforceCallingOrSelfPermission(
6428                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
6429        List<CrossProfileIntentFilter> matches =
6430                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
6431        if (matches != null) {
6432            int size = matches.size();
6433            for (int i = 0; i < size; i++) {
6434                if (matches.get(i).getTargetUserId() == targetUserId) return true;
6435            }
6436        }
6437        if (intent.hasWebURI()) {
6438            // cross-profile app linking works only towards the parent.
6439            final int callingUid = Binder.getCallingUid();
6440            final UserInfo parent = getProfileParent(sourceUserId);
6441            synchronized(mPackages) {
6442                int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
6443                        false /*includeInstantApps*/);
6444                CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
6445                        intent, resolvedType, flags, sourceUserId, parent.id);
6446                return xpDomainInfo != null;
6447            }
6448        }
6449        return false;
6450    }
6451
6452    private UserInfo getProfileParent(int userId) {
6453        final long identity = Binder.clearCallingIdentity();
6454        try {
6455            return sUserManager.getProfileParent(userId);
6456        } finally {
6457            Binder.restoreCallingIdentity(identity);
6458        }
6459    }
6460
6461    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
6462            String resolvedType, int userId) {
6463        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
6464        if (resolver != null) {
6465            return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
6466        }
6467        return null;
6468    }
6469
6470    @Override
6471    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
6472            String resolvedType, int flags, int userId) {
6473        try {
6474            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6475
6476            return new ParceledListSlice<>(
6477                    queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
6478        } finally {
6479            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6480        }
6481    }
6482
6483    /**
6484     * Returns the package name of the calling Uid if it's an instant app. If it isn't
6485     * instant, returns {@code null}.
6486     */
6487    private String getInstantAppPackageName(int callingUid) {
6488        synchronized (mPackages) {
6489            // If the caller is an isolated app use the owner's uid for the lookup.
6490            if (Process.isIsolated(callingUid)) {
6491                callingUid = mIsolatedOwners.get(callingUid);
6492            }
6493            final int appId = UserHandle.getAppId(callingUid);
6494            final Object obj = mSettings.getUserIdLPr(appId);
6495            if (obj instanceof PackageSetting) {
6496                final PackageSetting ps = (PackageSetting) obj;
6497                final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
6498                return isInstantApp ? ps.pkg.packageName : null;
6499            }
6500        }
6501        return null;
6502    }
6503
6504    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6505            String resolvedType, int flags, int userId) {
6506        return queryIntentActivitiesInternal(
6507                intent, resolvedType, flags, Binder.getCallingUid(), userId,
6508                false /*resolveForStart*/, true /*allowDynamicSplits*/);
6509    }
6510
6511    private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
6512            String resolvedType, int flags, int filterCallingUid, int userId,
6513            boolean resolveForStart, boolean allowDynamicSplits) {
6514        if (!sUserManager.exists(userId)) return Collections.emptyList();
6515        final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
6516        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6517                false /* requireFullPermission */, false /* checkShell */,
6518                "query intent activities");
6519        final String pkgName = intent.getPackage();
6520        ComponentName comp = intent.getComponent();
6521        if (comp == null) {
6522            if (intent.getSelector() != null) {
6523                intent = intent.getSelector();
6524                comp = intent.getComponent();
6525            }
6526        }
6527
6528        flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
6529                comp != null || pkgName != null /*onlyExposedExplicitly*/);
6530        if (comp != null) {
6531            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
6532            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
6533            if (ai != null) {
6534                // When specifying an explicit component, we prevent the activity from being
6535                // used when either 1) the calling package is normal and the activity is within
6536                // an ephemeral application or 2) the calling package is ephemeral and the
6537                // activity is not visible to ephemeral applications.
6538                final boolean matchInstantApp =
6539                        (flags & PackageManager.MATCH_INSTANT) != 0;
6540                final boolean matchVisibleToInstantAppOnly =
6541                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
6542                final boolean matchExplicitlyVisibleOnly =
6543                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
6544                final boolean isCallerInstantApp =
6545                        instantAppPkgName != null;
6546                final boolean isTargetSameInstantApp =
6547                        comp.getPackageName().equals(instantAppPkgName);
6548                final boolean isTargetInstantApp =
6549                        (ai.applicationInfo.privateFlags
6550                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
6551                final boolean isTargetVisibleToInstantApp =
6552                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
6553                final boolean isTargetExplicitlyVisibleToInstantApp =
6554                        isTargetVisibleToInstantApp
6555                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
6556                final boolean isTargetHiddenFromInstantApp =
6557                        !isTargetVisibleToInstantApp
6558                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
6559                final boolean blockResolution =
6560                        !isTargetSameInstantApp
6561                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
6562                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
6563                                        && isTargetHiddenFromInstantApp));
6564                if (!blockResolution) {
6565                    final ResolveInfo ri = new ResolveInfo();
6566                    ri.activityInfo = ai;
6567                    list.add(ri);
6568                }
6569            }
6570            return applyPostResolutionFilter(
6571                    list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6572        }
6573
6574        // reader
6575        boolean sortResult = false;
6576        boolean addInstant = false;
6577        List<ResolveInfo> result;
6578        synchronized (mPackages) {
6579            if (pkgName == null) {
6580                List<CrossProfileIntentFilter> matchingFilters =
6581                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
6582                // Check for results that need to skip the current profile.
6583                ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
6584                        resolvedType, flags, userId);
6585                if (xpResolveInfo != null) {
6586                    List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1);
6587                    xpResult.add(xpResolveInfo);
6588                    return applyPostResolutionFilter(
6589                            filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
6590                            allowDynamicSplits, filterCallingUid, userId, intent);
6591                }
6592
6593                // Check for results in the current profile.
6594                result = filterIfNotSystemUser(mActivities.queryIntent(
6595                        intent, resolvedType, flags, userId), userId);
6596                addInstant = isInstantAppResolutionAllowed(intent, result, userId,
6597                        false /*skipPackageCheck*/);
6598                // Check for cross profile results.
6599                boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
6600                xpResolveInfo = queryCrossProfileIntents(
6601                        matchingFilters, intent, resolvedType, flags, userId,
6602                        hasNonNegativePriorityResult);
6603                if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
6604                    boolean isVisibleToUser = filterIfNotSystemUser(
6605                            Collections.singletonList(xpResolveInfo), userId).size() > 0;
6606                    if (isVisibleToUser) {
6607                        result.add(xpResolveInfo);
6608                        sortResult = true;
6609                    }
6610                }
6611                if (intent.hasWebURI()) {
6612                    CrossProfileDomainInfo xpDomainInfo = null;
6613                    final UserInfo parent = getProfileParent(userId);
6614                    if (parent != null) {
6615                        xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
6616                                flags, userId, parent.id);
6617                    }
6618                    if (xpDomainInfo != null) {
6619                        if (xpResolveInfo != null) {
6620                            // If we didn't remove it, the cross-profile ResolveInfo would be twice
6621                            // in the result.
6622                            result.remove(xpResolveInfo);
6623                        }
6624                        if (result.size() == 0 && !addInstant) {
6625                            // No result in current profile, but found candidate in parent user.
6626                            // And we are not going to add emphemeral app, so we can return the
6627                            // result straight away.
6628                            result.add(xpDomainInfo.resolveInfo);
6629                            return applyPostResolutionFilter(result, instantAppPkgName,
6630                                    allowDynamicSplits, filterCallingUid, userId, intent);
6631                        }
6632                    } else if (result.size() <= 1 && !addInstant) {
6633                        // No result in parent user and <= 1 result in current profile, and we
6634                        // are not going to add emphemeral app, so we can return the result without
6635                        // further processing.
6636                        return applyPostResolutionFilter(result, instantAppPkgName,
6637                                allowDynamicSplits, filterCallingUid, userId, intent);
6638                    }
6639                    // We have more than one candidate (combining results from current and parent
6640                    // profile), so we need filtering and sorting.
6641                    result = filterCandidatesWithDomainPreferredActivitiesLPr(
6642                            intent, flags, result, xpDomainInfo, userId);
6643                    sortResult = true;
6644                }
6645            } else {
6646                final PackageParser.Package pkg = mPackages.get(pkgName);
6647                result = null;
6648                if (pkg != null) {
6649                    result = filterIfNotSystemUser(
6650                            mActivities.queryIntentForPackage(
6651                                    intent, resolvedType, flags, pkg.activities, userId),
6652                            userId);
6653                }
6654                if (result == null || result.size() == 0) {
6655                    // the caller wants to resolve for a particular package; however, there
6656                    // were no installed results, so, try to find an ephemeral result
6657                    addInstant = isInstantAppResolutionAllowed(
6658                                    intent, null /*result*/, userId, true /*skipPackageCheck*/);
6659                    if (result == null) {
6660                        result = new ArrayList<>();
6661                    }
6662                }
6663            }
6664        }
6665        if (addInstant) {
6666            result = maybeAddInstantAppInstaller(
6667                    result, intent, resolvedType, flags, userId, resolveForStart);
6668        }
6669        if (sortResult) {
6670            Collections.sort(result, mResolvePrioritySorter);
6671        }
6672        return applyPostResolutionFilter(
6673                result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent);
6674    }
6675
6676    private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
6677            String resolvedType, int flags, int userId, boolean resolveForStart) {
6678        // first, check to see if we've got an instant app already installed
6679        final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
6680        ResolveInfo localInstantApp = null;
6681        boolean blockResolution = false;
6682        if (!alreadyResolvedLocally) {
6683            final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType,
6684                    flags
6685                        | PackageManager.GET_RESOLVED_FILTER
6686                        | PackageManager.MATCH_INSTANT
6687                        | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
6688                    userId);
6689            for (int i = instantApps.size() - 1; i >= 0; --i) {
6690                final ResolveInfo info = instantApps.get(i);
6691                final String packageName = info.activityInfo.packageName;
6692                final PackageSetting ps = mSettings.mPackages.get(packageName);
6693                if (ps.getInstantApp(userId)) {
6694                    final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6695                    final int status = (int)(packedStatus >> 32);
6696                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6697                        // there's a local instant application installed, but, the user has
6698                        // chosen to never use it; skip resolution and don't acknowledge
6699                        // an instant application is even available
6700                        if (DEBUG_INSTANT) {
6701                            Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
6702                        }
6703                        blockResolution = true;
6704                        break;
6705                    } else {
6706                        // we have a locally installed instant application; skip resolution
6707                        // but acknowledge there's an instant application available
6708                        if (DEBUG_INSTANT) {
6709                            Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
6710                        }
6711                        localInstantApp = info;
6712                        break;
6713                    }
6714                }
6715            }
6716        }
6717        // no app installed, let's see if one's available
6718        AuxiliaryResolveInfo auxiliaryResponse = null;
6719        if (!blockResolution) {
6720            if (localInstantApp == null) {
6721                // we don't have an instant app locally, resolve externally
6722                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
6723                final InstantAppRequest requestObject = new InstantAppRequest(
6724                        null /*responseObj*/, intent /*origIntent*/, resolvedType,
6725                        null /*callingPackage*/, userId, null /*verificationBundle*/,
6726                        resolveForStart);
6727                auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
6728                        mInstantAppResolverConnection, requestObject);
6729                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6730            } else {
6731                // we have an instant application locally, but, we can't admit that since
6732                // callers shouldn't be able to determine prior browsing. create a dummy
6733                // auxiliary response so the downstream code behaves as if there's an
6734                // instant application available externally. when it comes time to start
6735                // the instant application, we'll do the right thing.
6736                final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
6737                auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
6738                                        ai.packageName, ai.versionCode, null /* splitName */);
6739            }
6740        }
6741        if (intent.isWebIntent() && auxiliaryResponse == null) {
6742            return result;
6743        }
6744        final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
6745        if (ps == null
6746                || ps.getUserState().get(userId) == null
6747                || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
6748            return result;
6749        }
6750        final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
6751        ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
6752                mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
6753        ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
6754                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
6755        // add a non-generic filter
6756        ephemeralInstaller.filter = new IntentFilter();
6757        if (intent.getAction() != null) {
6758            ephemeralInstaller.filter.addAction(intent.getAction());
6759        }
6760        if (intent.getData() != null && intent.getData().getPath() != null) {
6761            ephemeralInstaller.filter.addDataPath(
6762                    intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
6763        }
6764        ephemeralInstaller.isInstantAppAvailable = true;
6765        // make sure this resolver is the default
6766        ephemeralInstaller.isDefault = true;
6767        ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
6768        if (DEBUG_INSTANT) {
6769            Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
6770        }
6771
6772        result.add(ephemeralInstaller);
6773        return result;
6774    }
6775
6776    private static class CrossProfileDomainInfo {
6777        /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
6778        ResolveInfo resolveInfo;
6779        /* Best domain verification status of the activities found in the other profile */
6780        int bestDomainVerificationStatus;
6781    }
6782
6783    private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
6784            String resolvedType, int flags, int sourceUserId, int parentUserId) {
6785        if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
6786                sourceUserId)) {
6787            return null;
6788        }
6789        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
6790                resolvedType, flags, parentUserId);
6791
6792        if (resultTargetUser == null || resultTargetUser.isEmpty()) {
6793            return null;
6794        }
6795        CrossProfileDomainInfo result = null;
6796        int size = resultTargetUser.size();
6797        for (int i = 0; i < size; i++) {
6798            ResolveInfo riTargetUser = resultTargetUser.get(i);
6799            // Intent filter verification is only for filters that specify a host. So don't return
6800            // those that handle all web uris.
6801            if (riTargetUser.handleAllWebDataURI) {
6802                continue;
6803            }
6804            String packageName = riTargetUser.activityInfo.packageName;
6805            PackageSetting ps = mSettings.mPackages.get(packageName);
6806            if (ps == null) {
6807                continue;
6808            }
6809            long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
6810            int status = (int)(verificationState >> 32);
6811            if (result == null) {
6812                result = new CrossProfileDomainInfo();
6813                result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
6814                        sourceUserId, parentUserId);
6815                result.bestDomainVerificationStatus = status;
6816            } else {
6817                result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
6818                        result.bestDomainVerificationStatus);
6819            }
6820        }
6821        // Don't consider matches with status NEVER across profiles.
6822        if (result != null && result.bestDomainVerificationStatus
6823                == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6824            return null;
6825        }
6826        return result;
6827    }
6828
6829    /**
6830     * Verification statuses are ordered from the worse to the best, except for
6831     * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
6832     */
6833    private int bestDomainVerificationStatus(int status1, int status2) {
6834        if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6835            return status2;
6836        }
6837        if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
6838            return status1;
6839        }
6840        return (int) MathUtils.max(status1, status2);
6841    }
6842
6843    private boolean isUserEnabled(int userId) {
6844        long callingId = Binder.clearCallingIdentity();
6845        try {
6846            UserInfo userInfo = sUserManager.getUserInfo(userId);
6847            return userInfo != null && userInfo.isEnabled();
6848        } finally {
6849            Binder.restoreCallingIdentity(callingId);
6850        }
6851    }
6852
6853    /**
6854     * Filter out activities with systemUserOnly flag set, when current user is not System.
6855     *
6856     * @return filtered list
6857     */
6858    private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
6859        if (userId == UserHandle.USER_SYSTEM) {
6860            return resolveInfos;
6861        }
6862        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6863            ResolveInfo info = resolveInfos.get(i);
6864            if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
6865                resolveInfos.remove(i);
6866            }
6867        }
6868        return resolveInfos;
6869    }
6870
6871    /**
6872     * Filters out ephemeral activities.
6873     * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
6874     * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
6875     *
6876     * @param resolveInfos The pre-filtered list of resolved activities
6877     * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
6878     *          is performed.
6879     * @param intent
6880     * @return A filtered list of resolved activities.
6881     */
6882    private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
6883            String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId,
6884            Intent intent) {
6885        final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled();
6886        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
6887            final ResolveInfo info = resolveInfos.get(i);
6888            // remove locally resolved instant app web results when disabled
6889            if (info.isInstantAppAvailable && blockInstant) {
6890                resolveInfos.remove(i);
6891                continue;
6892            }
6893            // allow activities that are defined in the provided package
6894            if (allowDynamicSplits
6895                    && info.activityInfo != null
6896                    && info.activityInfo.splitName != null
6897                    && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
6898                            info.activityInfo.splitName)) {
6899                if (mInstantAppInstallerActivity == null) {
6900                    if (DEBUG_INSTALL) {
6901                        Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
6902                    }
6903                    resolveInfos.remove(i);
6904                    continue;
6905                }
6906                if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
6907                    resolveInfos.remove(i);
6908                    continue;
6909                }
6910                // requested activity is defined in a split that hasn't been installed yet.
6911                // add the installer to the resolve list
6912                if (DEBUG_INSTALL) {
6913                    Slog.v(TAG, "Adding installer to the ResolveInfo list");
6914                }
6915                final ResolveInfo installerInfo = new ResolveInfo(
6916                        mInstantAppInstallerInfo);
6917                final ComponentName installFailureActivity = findInstallFailureActivity(
6918                        info.activityInfo.packageName,  filterCallingUid, userId);
6919                installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
6920                        installFailureActivity,
6921                        info.activityInfo.packageName,
6922                        info.activityInfo.applicationInfo.versionCode,
6923                        info.activityInfo.splitName);
6924                // add a non-generic filter
6925                installerInfo.filter = new IntentFilter();
6926
6927                // This resolve info may appear in the chooser UI, so let us make it
6928                // look as the one it replaces as far as the user is concerned which
6929                // requires loading the correct label and icon for the resolve info.
6930                installerInfo.resolvePackageName = info.getComponentInfo().packageName;
6931                installerInfo.labelRes = info.resolveLabelResId();
6932                installerInfo.icon = info.resolveIconResId();
6933                installerInfo.isInstantAppAvailable = true;
6934                resolveInfos.set(i, installerInfo);
6935                continue;
6936            }
6937            // caller is a full app, don't need to apply any other filtering
6938            if (ephemeralPkgName == null) {
6939                continue;
6940            } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
6941                // caller is same app; don't need to apply any other filtering
6942                continue;
6943            }
6944            // allow activities that have been explicitly exposed to ephemeral apps
6945            final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
6946            if (!isEphemeralApp
6947                    && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
6948                continue;
6949            }
6950            resolveInfos.remove(i);
6951        }
6952        return resolveInfos;
6953    }
6954
6955    /**
6956     * Returns the activity component that can handle install failures.
6957     * <p>By default, the instant application installer handles failures. However, an
6958     * application may want to handle failures on its own. Applications do this by
6959     * creating an activity with an intent filter that handles the action
6960     * {@link Intent#ACTION_INSTALL_FAILURE}.
6961     */
6962    private @Nullable ComponentName findInstallFailureActivity(
6963            String packageName, int filterCallingUid, int userId) {
6964        final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
6965        failureActivityIntent.setPackage(packageName);
6966        // IMPORTANT: disallow dynamic splits to avoid an infinite loop
6967        final List<ResolveInfo> result = queryIntentActivitiesInternal(
6968                failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
6969                false /*resolveForStart*/, false /*allowDynamicSplits*/);
6970        final int NR = result.size();
6971        if (NR > 0) {
6972            for (int i = 0; i < NR; i++) {
6973                final ResolveInfo info = result.get(i);
6974                if (info.activityInfo.splitName != null) {
6975                    continue;
6976                }
6977                return new ComponentName(packageName, info.activityInfo.name);
6978            }
6979        }
6980        return null;
6981    }
6982
6983    /**
6984     * @param resolveInfos list of resolve infos in descending priority order
6985     * @return if the list contains a resolve info with non-negative priority
6986     */
6987    private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
6988        return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
6989    }
6990
6991    private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
6992            int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
6993            int userId) {
6994        final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
6995
6996        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
6997            Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
6998                    candidates.size());
6999        }
7000
7001        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
7002        ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>();
7003        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
7004        ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>();
7005        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
7006        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
7007
7008        synchronized (mPackages) {
7009            final int count = candidates.size();
7010            // First, try to use linked apps. Partition the candidates into four lists:
7011            // one for the final results, one for the "do not use ever", one for "undefined status"
7012            // and finally one for "browser app type".
7013            for (int n=0; n<count; n++) {
7014                ResolveInfo info = candidates.get(n);
7015                String packageName = info.activityInfo.packageName;
7016                PackageSetting ps = mSettings.mPackages.get(packageName);
7017                if (ps != null) {
7018                    // Add to the special match all list (Browser use case)
7019                    if (info.handleAllWebDataURI) {
7020                        matchAllList.add(info);
7021                        continue;
7022                    }
7023                    // Try to get the status from User settings first
7024                    long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7025                    int status = (int)(packedStatus >> 32);
7026                    int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7027                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7028                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7029                            Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7030                                    + " : linkgen=" + linkGeneration);
7031                        }
7032                        // Use link-enabled generation as preferredOrder, i.e.
7033                        // prefer newly-enabled over earlier-enabled.
7034                        info.preferredOrder = linkGeneration;
7035                        alwaysList.add(info);
7036                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7037                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7038                            Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7039                        }
7040                        neverList.add(info);
7041                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7042                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7043                            Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7044                        }
7045                        alwaysAskList.add(info);
7046                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7047                            status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7048                        if (DEBUG_DOMAIN_VERIFICATION || debug) {
7049                            Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7050                        }
7051                        undefinedList.add(info);
7052                    }
7053                }
7054            }
7055
7056            // We'll want to include browser possibilities in a few cases
7057            boolean includeBrowser = false;
7058
7059            // First try to add the "always" resolution(s) for the current user, if any
7060            if (alwaysList.size() > 0) {
7061                result.addAll(alwaysList);
7062            } else {
7063                // Add all undefined apps as we want them to appear in the disambiguation dialog.
7064                result.addAll(undefinedList);
7065                // Maybe add one for the other profile.
7066                if (xpDomainInfo != null && (
7067                        xpDomainInfo.bestDomainVerificationStatus
7068                        != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7069                    result.add(xpDomainInfo.resolveInfo);
7070                }
7071                includeBrowser = true;
7072            }
7073
7074            // The presence of any 'always ask' alternatives means we'll also offer browsers.
7075            // If there were 'always' entries their preferred order has been set, so we also
7076            // back that off to make the alternatives equivalent
7077            if (alwaysAskList.size() > 0) {
7078                for (ResolveInfo i : result) {
7079                    i.preferredOrder = 0;
7080                }
7081                result.addAll(alwaysAskList);
7082                includeBrowser = true;
7083            }
7084
7085            if (includeBrowser) {
7086                // Also add browsers (all of them or only the default one)
7087                if (DEBUG_DOMAIN_VERIFICATION) {
7088                    Slog.v(TAG, "   ...including browsers in candidate set");
7089                }
7090                if ((matchFlags & MATCH_ALL) != 0) {
7091                    result.addAll(matchAllList);
7092                } else {
7093                    // Browser/generic handling case.  If there's a default browser, go straight
7094                    // to that (but only if there is no other higher-priority match).
7095                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7096                    int maxMatchPrio = 0;
7097                    ResolveInfo defaultBrowserMatch = null;
7098                    final int numCandidates = matchAllList.size();
7099                    for (int n = 0; n < numCandidates; n++) {
7100                        ResolveInfo info = matchAllList.get(n);
7101                        // track the highest overall match priority...
7102                        if (info.priority > maxMatchPrio) {
7103                            maxMatchPrio = info.priority;
7104                        }
7105                        // ...and the highest-priority default browser match
7106                        if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7107                            if (defaultBrowserMatch == null
7108                                    || (defaultBrowserMatch.priority < info.priority)) {
7109                                if (debug) {
7110                                    Slog.v(TAG, "Considering default browser match " + info);
7111                                }
7112                                defaultBrowserMatch = info;
7113                            }
7114                        }
7115                    }
7116                    if (defaultBrowserMatch != null
7117                            && defaultBrowserMatch.priority >= maxMatchPrio
7118                            && !TextUtils.isEmpty(defaultBrowserPackageName))
7119                    {
7120                        if (debug) {
7121                            Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7122                        }
7123                        result.add(defaultBrowserMatch);
7124                    } else {
7125                        result.addAll(matchAllList);
7126                    }
7127                }
7128
7129                // If there is nothing selected, add all candidates and remove the ones that the user
7130                // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7131                if (result.size() == 0) {
7132                    result.addAll(candidates);
7133                    result.removeAll(neverList);
7134                }
7135            }
7136        }
7137        if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7138            Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7139                    result.size());
7140            for (ResolveInfo info : result) {
7141                Slog.v(TAG, "  + " + info.activityInfo);
7142            }
7143        }
7144        return result;
7145    }
7146
7147    // Returns a packed value as a long:
7148    //
7149    // high 'int'-sized word: link status: undefined/ask/never/always.
7150    // low 'int'-sized word: relative priority among 'always' results.
7151    private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7152        long result = ps.getDomainVerificationStatusForUser(userId);
7153        // if none available, get the master status
7154        if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7155            if (ps.getIntentFilterVerificationInfo() != null) {
7156                result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7157            }
7158        }
7159        return result;
7160    }
7161
7162    private ResolveInfo querySkipCurrentProfileIntents(
7163            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7164            int flags, int sourceUserId) {
7165        if (matchingFilters != null) {
7166            int size = matchingFilters.size();
7167            for (int i = 0; i < size; i ++) {
7168                CrossProfileIntentFilter filter = matchingFilters.get(i);
7169                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7170                    // Checking if there are activities in the target user that can handle the
7171                    // intent.
7172                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7173                            resolvedType, flags, sourceUserId);
7174                    if (resolveInfo != null) {
7175                        return resolveInfo;
7176                    }
7177                }
7178            }
7179        }
7180        return null;
7181    }
7182
7183    // Return matching ResolveInfo in target user if any.
7184    private ResolveInfo queryCrossProfileIntents(
7185            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7186            int flags, int sourceUserId, boolean matchInCurrentProfile) {
7187        if (matchingFilters != null) {
7188            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7189            // match the same intent. For performance reasons, it is better not to
7190            // run queryIntent twice for the same userId
7191            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7192            int size = matchingFilters.size();
7193            for (int i = 0; i < size; i++) {
7194                CrossProfileIntentFilter filter = matchingFilters.get(i);
7195                int targetUserId = filter.getTargetUserId();
7196                boolean skipCurrentProfile =
7197                        (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7198                boolean skipCurrentProfileIfNoMatchFound =
7199                        (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7200                if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7201                        && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7202                    // Checking if there are activities in the target user that can handle the
7203                    // intent.
7204                    ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7205                            resolvedType, flags, sourceUserId);
7206                    if (resolveInfo != null) return resolveInfo;
7207                    alreadyTriedUserIds.put(targetUserId, true);
7208                }
7209            }
7210        }
7211        return null;
7212    }
7213
7214    /**
7215     * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7216     * will forward the intent to the filter's target user.
7217     * Otherwise, returns null.
7218     */
7219    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7220            String resolvedType, int flags, int sourceUserId) {
7221        int targetUserId = filter.getTargetUserId();
7222        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
7223                resolvedType, flags, targetUserId);
7224        if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7225            // If all the matches in the target profile are suspended, return null.
7226            for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7227                if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7228                        & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7229                    return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7230                            targetUserId);
7231                }
7232            }
7233        }
7234        return null;
7235    }
7236
7237    private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7238            int sourceUserId, int targetUserId) {
7239        ResolveInfo forwardingResolveInfo = new ResolveInfo();
7240        long ident = Binder.clearCallingIdentity();
7241        boolean targetIsProfile;
7242        try {
7243            targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7244        } finally {
7245            Binder.restoreCallingIdentity(ident);
7246        }
7247        String className;
7248        if (targetIsProfile) {
7249            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7250        } else {
7251            className = FORWARD_INTENT_TO_PARENT;
7252        }
7253        ComponentName forwardingActivityComponentName = new ComponentName(
7254                mAndroidApplication.packageName, className);
7255        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7256                sourceUserId);
7257        if (!targetIsProfile) {
7258            forwardingActivityInfo.showUserIcon = targetUserId;
7259            forwardingResolveInfo.noResourceId = true;
7260        }
7261        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7262        forwardingResolveInfo.priority = 0;
7263        forwardingResolveInfo.preferredOrder = 0;
7264        forwardingResolveInfo.match = 0;
7265        forwardingResolveInfo.isDefault = true;
7266        forwardingResolveInfo.filter = filter;
7267        forwardingResolveInfo.targetUserId = targetUserId;
7268        return forwardingResolveInfo;
7269    }
7270
7271    @Override
7272    public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7273            Intent[] specifics, String[] specificTypes, Intent intent,
7274            String resolvedType, int flags, int userId) {
7275        return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7276                specificTypes, intent, resolvedType, flags, userId));
7277    }
7278
7279    private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7280            Intent[] specifics, String[] specificTypes, Intent intent,
7281            String resolvedType, int flags, int userId) {
7282        if (!sUserManager.exists(userId)) return Collections.emptyList();
7283        final int callingUid = Binder.getCallingUid();
7284        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7285                false /*includeInstantApps*/);
7286        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7287                false /*requireFullPermission*/, false /*checkShell*/,
7288                "query intent activity options");
7289        final String resultsAction = intent.getAction();
7290
7291        final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7292                | PackageManager.GET_RESOLVED_FILTER, userId);
7293
7294        if (DEBUG_INTENT_MATCHING) {
7295            Log.v(TAG, "Query " + intent + ": " + results);
7296        }
7297
7298        int specificsPos = 0;
7299        int N;
7300
7301        // todo: note that the algorithm used here is O(N^2).  This
7302        // isn't a problem in our current environment, but if we start running
7303        // into situations where we have more than 5 or 10 matches then this
7304        // should probably be changed to something smarter...
7305
7306        // First we go through and resolve each of the specific items
7307        // that were supplied, taking care of removing any corresponding
7308        // duplicate items in the generic resolve list.
7309        if (specifics != null) {
7310            for (int i=0; i<specifics.length; i++) {
7311                final Intent sintent = specifics[i];
7312                if (sintent == null) {
7313                    continue;
7314                }
7315
7316                if (DEBUG_INTENT_MATCHING) {
7317                    Log.v(TAG, "Specific #" + i + ": " + sintent);
7318                }
7319
7320                String action = sintent.getAction();
7321                if (resultsAction != null && resultsAction.equals(action)) {
7322                    // If this action was explicitly requested, then don't
7323                    // remove things that have it.
7324                    action = null;
7325                }
7326
7327                ResolveInfo ri = null;
7328                ActivityInfo ai = null;
7329
7330                ComponentName comp = sintent.getComponent();
7331                if (comp == null) {
7332                    ri = resolveIntent(
7333                        sintent,
7334                        specificTypes != null ? specificTypes[i] : null,
7335                            flags, userId);
7336                    if (ri == null) {
7337                        continue;
7338                    }
7339                    if (ri == mResolveInfo) {
7340                        // ACK!  Must do something better with this.
7341                    }
7342                    ai = ri.activityInfo;
7343                    comp = new ComponentName(ai.applicationInfo.packageName,
7344                            ai.name);
7345                } else {
7346                    ai = getActivityInfo(comp, flags, userId);
7347                    if (ai == null) {
7348                        continue;
7349                    }
7350                }
7351
7352                // Look for any generic query activities that are duplicates
7353                // of this specific one, and remove them from the results.
7354                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
7355                N = results.size();
7356                int j;
7357                for (j=specificsPos; j<N; j++) {
7358                    ResolveInfo sri = results.get(j);
7359                    if ((sri.activityInfo.name.equals(comp.getClassName())
7360                            && sri.activityInfo.applicationInfo.packageName.equals(
7361                                    comp.getPackageName()))
7362                        || (action != null && sri.filter.matchAction(action))) {
7363                        results.remove(j);
7364                        if (DEBUG_INTENT_MATCHING) Log.v(
7365                            TAG, "Removing duplicate item from " + j
7366                            + " due to specific " + specificsPos);
7367                        if (ri == null) {
7368                            ri = sri;
7369                        }
7370                        j--;
7371                        N--;
7372                    }
7373                }
7374
7375                // Add this specific item to its proper place.
7376                if (ri == null) {
7377                    ri = new ResolveInfo();
7378                    ri.activityInfo = ai;
7379                }
7380                results.add(specificsPos, ri);
7381                ri.specificIndex = i;
7382                specificsPos++;
7383            }
7384        }
7385
7386        // Now we go through the remaining generic results and remove any
7387        // duplicate actions that are found here.
7388        N = results.size();
7389        for (int i=specificsPos; i<N-1; i++) {
7390            final ResolveInfo rii = results.get(i);
7391            if (rii.filter == null) {
7392                continue;
7393            }
7394
7395            // Iterate over all of the actions of this result's intent
7396            // filter...  typically this should be just one.
7397            final Iterator<String> it = rii.filter.actionsIterator();
7398            if (it == null) {
7399                continue;
7400            }
7401            while (it.hasNext()) {
7402                final String action = it.next();
7403                if (resultsAction != null && resultsAction.equals(action)) {
7404                    // If this action was explicitly requested, then don't
7405                    // remove things that have it.
7406                    continue;
7407                }
7408                for (int j=i+1; j<N; j++) {
7409                    final ResolveInfo rij = results.get(j);
7410                    if (rij.filter != null && rij.filter.hasAction(action)) {
7411                        results.remove(j);
7412                        if (DEBUG_INTENT_MATCHING) Log.v(
7413                            TAG, "Removing duplicate item from " + j
7414                            + " due to action " + action + " at " + i);
7415                        j--;
7416                        N--;
7417                    }
7418                }
7419            }
7420
7421            // If the caller didn't request filter information, drop it now
7422            // so we don't have to marshall/unmarshall it.
7423            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7424                rii.filter = null;
7425            }
7426        }
7427
7428        // Filter out the caller activity if so requested.
7429        if (caller != null) {
7430            N = results.size();
7431            for (int i=0; i<N; i++) {
7432                ActivityInfo ainfo = results.get(i).activityInfo;
7433                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
7434                        && caller.getClassName().equals(ainfo.name)) {
7435                    results.remove(i);
7436                    break;
7437                }
7438            }
7439        }
7440
7441        // If the caller didn't request filter information,
7442        // drop them now so we don't have to
7443        // marshall/unmarshall it.
7444        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
7445            N = results.size();
7446            for (int i=0; i<N; i++) {
7447                results.get(i).filter = null;
7448            }
7449        }
7450
7451        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
7452        return results;
7453    }
7454
7455    @Override
7456    public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
7457            String resolvedType, int flags, int userId) {
7458        return new ParceledListSlice<>(
7459                queryIntentReceiversInternal(intent, resolvedType, flags, userId,
7460                        false /*allowDynamicSplits*/));
7461    }
7462
7463    private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
7464            String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
7465        if (!sUserManager.exists(userId)) return Collections.emptyList();
7466        final int callingUid = Binder.getCallingUid();
7467        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7468                false /*requireFullPermission*/, false /*checkShell*/,
7469                "query intent receivers");
7470        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7471        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7472                false /*includeInstantApps*/);
7473        ComponentName comp = intent.getComponent();
7474        if (comp == null) {
7475            if (intent.getSelector() != null) {
7476                intent = intent.getSelector();
7477                comp = intent.getComponent();
7478            }
7479        }
7480        if (comp != null) {
7481            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7482            final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
7483            if (ai != null) {
7484                // When specifying an explicit component, we prevent the activity from being
7485                // used when either 1) the calling package is normal and the activity is within
7486                // an instant application or 2) the calling package is ephemeral and the
7487                // activity is not visible to instant applications.
7488                final boolean matchInstantApp =
7489                        (flags & PackageManager.MATCH_INSTANT) != 0;
7490                final boolean matchVisibleToInstantAppOnly =
7491                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7492                final boolean matchExplicitlyVisibleOnly =
7493                        (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7494                final boolean isCallerInstantApp =
7495                        instantAppPkgName != null;
7496                final boolean isTargetSameInstantApp =
7497                        comp.getPackageName().equals(instantAppPkgName);
7498                final boolean isTargetInstantApp =
7499                        (ai.applicationInfo.privateFlags
7500                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7501                final boolean isTargetVisibleToInstantApp =
7502                        (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7503                final boolean isTargetExplicitlyVisibleToInstantApp =
7504                        isTargetVisibleToInstantApp
7505                        && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7506                final boolean isTargetHiddenFromInstantApp =
7507                        !isTargetVisibleToInstantApp
7508                        || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7509                final boolean blockResolution =
7510                        !isTargetSameInstantApp
7511                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7512                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7513                                        && isTargetHiddenFromInstantApp));
7514                if (!blockResolution) {
7515                    ResolveInfo ri = new ResolveInfo();
7516                    ri.activityInfo = ai;
7517                    list.add(ri);
7518                }
7519            }
7520            return applyPostResolutionFilter(
7521                    list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7522        }
7523
7524        // reader
7525        synchronized (mPackages) {
7526            String pkgName = intent.getPackage();
7527            if (pkgName == null) {
7528                final List<ResolveInfo> result =
7529                        mReceivers.queryIntent(intent, resolvedType, flags, userId);
7530                return applyPostResolutionFilter(
7531                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7532            }
7533            final PackageParser.Package pkg = mPackages.get(pkgName);
7534            if (pkg != null) {
7535                final List<ResolveInfo> result = mReceivers.queryIntentForPackage(
7536                        intent, resolvedType, flags, pkg.receivers, userId);
7537                return applyPostResolutionFilter(
7538                        result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent);
7539            }
7540            return Collections.emptyList();
7541        }
7542    }
7543
7544    @Override
7545    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
7546        final int callingUid = Binder.getCallingUid();
7547        return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
7548    }
7549
7550    private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
7551            int userId, int callingUid) {
7552        if (!sUserManager.exists(userId)) return null;
7553        flags = updateFlagsForResolve(
7554                flags, userId, intent, callingUid, false /*includeInstantApps*/);
7555        List<ResolveInfo> query = queryIntentServicesInternal(
7556                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
7557        if (query != null) {
7558            if (query.size() >= 1) {
7559                // If there is more than one service with the same priority,
7560                // just arbitrarily pick the first one.
7561                return query.get(0);
7562            }
7563        }
7564        return null;
7565    }
7566
7567    @Override
7568    public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
7569            String resolvedType, int flags, int userId) {
7570        final int callingUid = Binder.getCallingUid();
7571        return new ParceledListSlice<>(queryIntentServicesInternal(
7572                intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
7573    }
7574
7575    private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
7576            String resolvedType, int flags, int userId, int callingUid,
7577            boolean includeInstantApps) {
7578        if (!sUserManager.exists(userId)) return Collections.emptyList();
7579        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7580                false /*requireFullPermission*/, false /*checkShell*/,
7581                "query intent receivers");
7582        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7583        flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
7584        ComponentName comp = intent.getComponent();
7585        if (comp == null) {
7586            if (intent.getSelector() != null) {
7587                intent = intent.getSelector();
7588                comp = intent.getComponent();
7589            }
7590        }
7591        if (comp != null) {
7592            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7593            final ServiceInfo si = getServiceInfo(comp, flags, userId);
7594            if (si != null) {
7595                // When specifying an explicit component, we prevent the service from being
7596                // used when either 1) the service is in an instant application and the
7597                // caller is not the same instant application or 2) the calling package is
7598                // ephemeral and the activity is not visible to ephemeral applications.
7599                final boolean matchInstantApp =
7600                        (flags & PackageManager.MATCH_INSTANT) != 0;
7601                final boolean matchVisibleToInstantAppOnly =
7602                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7603                final boolean isCallerInstantApp =
7604                        instantAppPkgName != null;
7605                final boolean isTargetSameInstantApp =
7606                        comp.getPackageName().equals(instantAppPkgName);
7607                final boolean isTargetInstantApp =
7608                        (si.applicationInfo.privateFlags
7609                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7610                final boolean isTargetHiddenFromInstantApp =
7611                        (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7612                final boolean blockResolution =
7613                        !isTargetSameInstantApp
7614                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7615                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7616                                        && isTargetHiddenFromInstantApp));
7617                if (!blockResolution) {
7618                    final ResolveInfo ri = new ResolveInfo();
7619                    ri.serviceInfo = si;
7620                    list.add(ri);
7621                }
7622            }
7623            return list;
7624        }
7625
7626        // reader
7627        synchronized (mPackages) {
7628            String pkgName = intent.getPackage();
7629            if (pkgName == null) {
7630                return applyPostServiceResolutionFilter(
7631                        mServices.queryIntent(intent, resolvedType, flags, userId),
7632                        instantAppPkgName);
7633            }
7634            final PackageParser.Package pkg = mPackages.get(pkgName);
7635            if (pkg != null) {
7636                return applyPostServiceResolutionFilter(
7637                        mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
7638                                userId),
7639                        instantAppPkgName);
7640            }
7641            return Collections.emptyList();
7642        }
7643    }
7644
7645    private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
7646            String instantAppPkgName) {
7647        if (instantAppPkgName == null) {
7648            return resolveInfos;
7649        }
7650        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7651            final ResolveInfo info = resolveInfos.get(i);
7652            final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
7653            // allow services that are defined in the provided package
7654            if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
7655                if (info.serviceInfo.splitName != null
7656                        && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
7657                                info.serviceInfo.splitName)) {
7658                    // requested service is defined in a split that hasn't been installed yet.
7659                    // add the installer to the resolve list
7660                    if (DEBUG_INSTANT) {
7661                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7662                    }
7663                    final ResolveInfo installerInfo = new ResolveInfo(
7664                            mInstantAppInstallerInfo);
7665                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7666                            null /* installFailureActivity */,
7667                            info.serviceInfo.packageName,
7668                            info.serviceInfo.applicationInfo.versionCode,
7669                            info.serviceInfo.splitName);
7670                    // add a non-generic filter
7671                    installerInfo.filter = new IntentFilter();
7672                    // load resources from the correct package
7673                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7674                    resolveInfos.set(i, installerInfo);
7675                }
7676                continue;
7677            }
7678            // allow services that have been explicitly exposed to ephemeral apps
7679            if (!isEphemeralApp
7680                    && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7681                continue;
7682            }
7683            resolveInfos.remove(i);
7684        }
7685        return resolveInfos;
7686    }
7687
7688    @Override
7689    public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
7690            String resolvedType, int flags, int userId) {
7691        return new ParceledListSlice<>(
7692                queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
7693    }
7694
7695    private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
7696            Intent intent, String resolvedType, int flags, int userId) {
7697        if (!sUserManager.exists(userId)) return Collections.emptyList();
7698        final int callingUid = Binder.getCallingUid();
7699        final String instantAppPkgName = getInstantAppPackageName(callingUid);
7700        flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7701                false /*includeInstantApps*/);
7702        ComponentName comp = intent.getComponent();
7703        if (comp == null) {
7704            if (intent.getSelector() != null) {
7705                intent = intent.getSelector();
7706                comp = intent.getComponent();
7707            }
7708        }
7709        if (comp != null) {
7710            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
7711            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
7712            if (pi != null) {
7713                // When specifying an explicit component, we prevent the provider from being
7714                // used when either 1) the provider is in an instant application and the
7715                // caller is not the same instant application or 2) the calling package is an
7716                // instant application and the provider is not visible to instant applications.
7717                final boolean matchInstantApp =
7718                        (flags & PackageManager.MATCH_INSTANT) != 0;
7719                final boolean matchVisibleToInstantAppOnly =
7720                        (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7721                final boolean isCallerInstantApp =
7722                        instantAppPkgName != null;
7723                final boolean isTargetSameInstantApp =
7724                        comp.getPackageName().equals(instantAppPkgName);
7725                final boolean isTargetInstantApp =
7726                        (pi.applicationInfo.privateFlags
7727                                & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7728                final boolean isTargetHiddenFromInstantApp =
7729                        (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
7730                final boolean blockResolution =
7731                        !isTargetSameInstantApp
7732                        && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7733                                || (matchVisibleToInstantAppOnly && isCallerInstantApp
7734                                        && isTargetHiddenFromInstantApp));
7735                if (!blockResolution) {
7736                    final ResolveInfo ri = new ResolveInfo();
7737                    ri.providerInfo = pi;
7738                    list.add(ri);
7739                }
7740            }
7741            return list;
7742        }
7743
7744        // reader
7745        synchronized (mPackages) {
7746            String pkgName = intent.getPackage();
7747            if (pkgName == null) {
7748                return applyPostContentProviderResolutionFilter(
7749                        mProviders.queryIntent(intent, resolvedType, flags, userId),
7750                        instantAppPkgName);
7751            }
7752            final PackageParser.Package pkg = mPackages.get(pkgName);
7753            if (pkg != null) {
7754                return applyPostContentProviderResolutionFilter(
7755                        mProviders.queryIntentForPackage(
7756                        intent, resolvedType, flags, pkg.providers, userId),
7757                        instantAppPkgName);
7758            }
7759            return Collections.emptyList();
7760        }
7761    }
7762
7763    private List<ResolveInfo> applyPostContentProviderResolutionFilter(
7764            List<ResolveInfo> resolveInfos, String instantAppPkgName) {
7765        if (instantAppPkgName == null) {
7766            return resolveInfos;
7767        }
7768        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7769            final ResolveInfo info = resolveInfos.get(i);
7770            final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
7771            // allow providers that are defined in the provided package
7772            if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
7773                if (info.providerInfo.splitName != null
7774                        && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
7775                                info.providerInfo.splitName)) {
7776                    // requested provider is defined in a split that hasn't been installed yet.
7777                    // add the installer to the resolve list
7778                    if (DEBUG_INSTANT) {
7779                        Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7780                    }
7781                    final ResolveInfo installerInfo = new ResolveInfo(
7782                            mInstantAppInstallerInfo);
7783                    installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7784                            null /*failureActivity*/,
7785                            info.providerInfo.packageName,
7786                            info.providerInfo.applicationInfo.versionCode,
7787                            info.providerInfo.splitName);
7788                    // add a non-generic filter
7789                    installerInfo.filter = new IntentFilter();
7790                    // load resources from the correct package
7791                    installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7792                    resolveInfos.set(i, installerInfo);
7793                }
7794                continue;
7795            }
7796            // allow providers that have been explicitly exposed to instant applications
7797            if (!isEphemeralApp
7798                    && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7799                continue;
7800            }
7801            resolveInfos.remove(i);
7802        }
7803        return resolveInfos;
7804    }
7805
7806    @Override
7807    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
7808        final int callingUid = Binder.getCallingUid();
7809        if (getInstantAppPackageName(callingUid) != null) {
7810            return ParceledListSlice.emptyList();
7811        }
7812        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7813        flags = updateFlagsForPackage(flags, userId, null);
7814        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7815        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7816                true /* requireFullPermission */, false /* checkShell */,
7817                "get installed packages");
7818
7819        // writer
7820        synchronized (mPackages) {
7821            ArrayList<PackageInfo> list;
7822            if (listUninstalled) {
7823                list = new ArrayList<>(mSettings.mPackages.size());
7824                for (PackageSetting ps : mSettings.mPackages.values()) {
7825                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7826                        continue;
7827                    }
7828                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7829                        continue;
7830                    }
7831                    final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7832                    if (pi != null) {
7833                        list.add(pi);
7834                    }
7835                }
7836            } else {
7837                list = new ArrayList<>(mPackages.size());
7838                for (PackageParser.Package p : mPackages.values()) {
7839                    final PackageSetting ps = (PackageSetting) p.mExtras;
7840                    if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7841                        continue;
7842                    }
7843                    if (filterAppAccessLPr(ps, callingUid, userId)) {
7844                        continue;
7845                    }
7846                    final PackageInfo pi = generatePackageInfo((PackageSetting)
7847                            p.mExtras, flags, userId);
7848                    if (pi != null) {
7849                        list.add(pi);
7850                    }
7851                }
7852            }
7853
7854            return new ParceledListSlice<>(list);
7855        }
7856    }
7857
7858    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
7859            String[] permissions, boolean[] tmp, int flags, int userId) {
7860        int numMatch = 0;
7861        final PermissionsState permissionsState = ps.getPermissionsState();
7862        for (int i=0; i<permissions.length; i++) {
7863            final String permission = permissions[i];
7864            if (permissionsState.hasPermission(permission, userId)) {
7865                tmp[i] = true;
7866                numMatch++;
7867            } else {
7868                tmp[i] = false;
7869            }
7870        }
7871        if (numMatch == 0) {
7872            return;
7873        }
7874        final PackageInfo pi = generatePackageInfo(ps, flags, userId);
7875
7876        // The above might return null in cases of uninstalled apps or install-state
7877        // skew across users/profiles.
7878        if (pi != null) {
7879            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
7880                if (numMatch == permissions.length) {
7881                    pi.requestedPermissions = permissions;
7882                } else {
7883                    pi.requestedPermissions = new String[numMatch];
7884                    numMatch = 0;
7885                    for (int i=0; i<permissions.length; i++) {
7886                        if (tmp[i]) {
7887                            pi.requestedPermissions[numMatch] = permissions[i];
7888                            numMatch++;
7889                        }
7890                    }
7891                }
7892            }
7893            list.add(pi);
7894        }
7895    }
7896
7897    @Override
7898    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
7899            String[] permissions, int flags, int userId) {
7900        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7901        flags = updateFlagsForPackage(flags, userId, permissions);
7902        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7903                true /* requireFullPermission */, false /* checkShell */,
7904                "get packages holding permissions");
7905        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7906
7907        // writer
7908        synchronized (mPackages) {
7909            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
7910            boolean[] tmpBools = new boolean[permissions.length];
7911            if (listUninstalled) {
7912                for (PackageSetting ps : mSettings.mPackages.values()) {
7913                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7914                            userId);
7915                }
7916            } else {
7917                for (PackageParser.Package pkg : mPackages.values()) {
7918                    PackageSetting ps = (PackageSetting)pkg.mExtras;
7919                    if (ps != null) {
7920                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
7921                                userId);
7922                    }
7923                }
7924            }
7925
7926            return new ParceledListSlice<PackageInfo>(list);
7927        }
7928    }
7929
7930    @Override
7931    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
7932        final int callingUid = Binder.getCallingUid();
7933        if (getInstantAppPackageName(callingUid) != null) {
7934            return ParceledListSlice.emptyList();
7935        }
7936        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
7937        flags = updateFlagsForApplication(flags, userId, null);
7938        final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
7939
7940        // writer
7941        synchronized (mPackages) {
7942            ArrayList<ApplicationInfo> list;
7943            if (listUninstalled) {
7944                list = new ArrayList<>(mSettings.mPackages.size());
7945                for (PackageSetting ps : mSettings.mPackages.values()) {
7946                    ApplicationInfo ai;
7947                    int effectiveFlags = flags;
7948                    if (ps.isSystem()) {
7949                        effectiveFlags |= PackageManager.MATCH_ANY_USER;
7950                    }
7951                    if (ps.pkg != null) {
7952                        if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
7953                            continue;
7954                        }
7955                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7956                            continue;
7957                        }
7958                        ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
7959                                ps.readUserState(userId), userId);
7960                        if (ai != null) {
7961                            ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
7962                        }
7963                    } else {
7964                        // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
7965                        // and already converts to externally visible package name
7966                        ai = generateApplicationInfoFromSettingsLPw(ps.name,
7967                                callingUid, effectiveFlags, userId);
7968                    }
7969                    if (ai != null) {
7970                        list.add(ai);
7971                    }
7972                }
7973            } else {
7974                list = new ArrayList<>(mPackages.size());
7975                for (PackageParser.Package p : mPackages.values()) {
7976                    if (p.mExtras != null) {
7977                        PackageSetting ps = (PackageSetting) p.mExtras;
7978                        if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
7979                            continue;
7980                        }
7981                        if (filterAppAccessLPr(ps, callingUid, userId)) {
7982                            continue;
7983                        }
7984                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
7985                                ps.readUserState(userId), userId);
7986                        if (ai != null) {
7987                            ai.packageName = resolveExternalPackageNameLPr(p);
7988                            list.add(ai);
7989                        }
7990                    }
7991                }
7992            }
7993
7994            return new ParceledListSlice<>(list);
7995        }
7996    }
7997
7998    @Override
7999    public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8000        if (HIDE_EPHEMERAL_APIS) {
8001            return null;
8002        }
8003        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8004            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8005                    "getEphemeralApplications");
8006        }
8007        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8008                true /* requireFullPermission */, false /* checkShell */,
8009                "getEphemeralApplications");
8010        synchronized (mPackages) {
8011            List<InstantAppInfo> instantApps = mInstantAppRegistry
8012                    .getInstantAppsLPr(userId);
8013            if (instantApps != null) {
8014                return new ParceledListSlice<>(instantApps);
8015            }
8016        }
8017        return null;
8018    }
8019
8020    @Override
8021    public boolean isInstantApp(String packageName, int userId) {
8022        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8023                true /* requireFullPermission */, false /* checkShell */,
8024                "isInstantApp");
8025        if (HIDE_EPHEMERAL_APIS) {
8026            return false;
8027        }
8028
8029        synchronized (mPackages) {
8030            int callingUid = Binder.getCallingUid();
8031            if (Process.isIsolated(callingUid)) {
8032                callingUid = mIsolatedOwners.get(callingUid);
8033            }
8034            final PackageSetting ps = mSettings.mPackages.get(packageName);
8035            PackageParser.Package pkg = mPackages.get(packageName);
8036            final boolean returnAllowed =
8037                    ps != null
8038                    && (isCallerSameApp(packageName, callingUid)
8039                            || canViewInstantApps(callingUid, userId)
8040                            || mInstantAppRegistry.isInstantAccessGranted(
8041                                    userId, UserHandle.getAppId(callingUid), ps.appId));
8042            if (returnAllowed) {
8043                return ps.getInstantApp(userId);
8044            }
8045        }
8046        return false;
8047    }
8048
8049    @Override
8050    public byte[] getInstantAppCookie(String packageName, int userId) {
8051        if (HIDE_EPHEMERAL_APIS) {
8052            return null;
8053        }
8054
8055        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8056                true /* requireFullPermission */, false /* checkShell */,
8057                "getInstantAppCookie");
8058        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8059            return null;
8060        }
8061        synchronized (mPackages) {
8062            return mInstantAppRegistry.getInstantAppCookieLPw(
8063                    packageName, userId);
8064        }
8065    }
8066
8067    @Override
8068    public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8069        if (HIDE_EPHEMERAL_APIS) {
8070            return true;
8071        }
8072
8073        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8074                true /* requireFullPermission */, true /* checkShell */,
8075                "setInstantAppCookie");
8076        if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8077            return false;
8078        }
8079        synchronized (mPackages) {
8080            return mInstantAppRegistry.setInstantAppCookieLPw(
8081                    packageName, cookie, userId);
8082        }
8083    }
8084
8085    @Override
8086    public Bitmap getInstantAppIcon(String packageName, int userId) {
8087        if (HIDE_EPHEMERAL_APIS) {
8088            return null;
8089        }
8090
8091        if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8092            mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8093                    "getInstantAppIcon");
8094        }
8095        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8096                true /* requireFullPermission */, false /* checkShell */,
8097                "getInstantAppIcon");
8098
8099        synchronized (mPackages) {
8100            return mInstantAppRegistry.getInstantAppIconLPw(
8101                    packageName, userId);
8102        }
8103    }
8104
8105    private boolean isCallerSameApp(String packageName, int uid) {
8106        PackageParser.Package pkg = mPackages.get(packageName);
8107        return pkg != null
8108                && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8109    }
8110
8111    @Override
8112    public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8113        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8114            return ParceledListSlice.emptyList();
8115        }
8116        return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8117    }
8118
8119    private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8120        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
8121
8122        // reader
8123        synchronized (mPackages) {
8124            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8125            final int userId = UserHandle.getCallingUserId();
8126            while (i.hasNext()) {
8127                final PackageParser.Package p = i.next();
8128                if (p.applicationInfo == null) continue;
8129
8130                final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8131                        && !p.applicationInfo.isDirectBootAware();
8132                final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8133                        && p.applicationInfo.isDirectBootAware();
8134
8135                if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8136                        && (!mSafeMode || isSystemApp(p))
8137                        && (matchesUnaware || matchesAware)) {
8138                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
8139                    if (ps != null) {
8140                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8141                                ps.readUserState(userId), userId);
8142                        if (ai != null) {
8143                            finalList.add(ai);
8144                        }
8145                    }
8146                }
8147            }
8148        }
8149
8150        return finalList;
8151    }
8152
8153    @Override
8154    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8155        return resolveContentProviderInternal(name, flags, userId);
8156    }
8157
8158    private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8159        if (!sUserManager.exists(userId)) return null;
8160        flags = updateFlagsForComponent(flags, userId, name);
8161        final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid());
8162        // reader
8163        synchronized (mPackages) {
8164            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
8165            PackageSetting ps = provider != null
8166                    ? mSettings.mPackages.get(provider.owner.packageName)
8167                    : null;
8168            if (ps != null) {
8169                final boolean isInstantApp = ps.getInstantApp(userId);
8170                // normal application; filter out instant application provider
8171                if (instantAppPkgName == null && isInstantApp) {
8172                    return null;
8173                }
8174                // instant application; filter out other instant applications
8175                if (instantAppPkgName != null
8176                        && isInstantApp
8177                        && !provider.owner.packageName.equals(instantAppPkgName)) {
8178                    return null;
8179                }
8180                // instant application; filter out non-exposed provider
8181                if (instantAppPkgName != null
8182                        && !isInstantApp
8183                        && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) {
8184                    return null;
8185                }
8186                // provider not enabled
8187                if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) {
8188                    return null;
8189                }
8190                return PackageParser.generateProviderInfo(
8191                        provider, flags, ps.readUserState(userId), userId);
8192            }
8193            return null;
8194        }
8195    }
8196
8197    /**
8198     * @deprecated
8199     */
8200    @Deprecated
8201    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8202        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8203            return;
8204        }
8205        // reader
8206        synchronized (mPackages) {
8207            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
8208                    .entrySet().iterator();
8209            final int userId = UserHandle.getCallingUserId();
8210            while (i.hasNext()) {
8211                Map.Entry<String, PackageParser.Provider> entry = i.next();
8212                PackageParser.Provider p = entry.getValue();
8213                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8214
8215                if (ps != null && p.syncable
8216                        && (!mSafeMode || (p.info.applicationInfo.flags
8217                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
8218                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
8219                            ps.readUserState(userId), userId);
8220                    if (info != null) {
8221                        outNames.add(entry.getKey());
8222                        outInfo.add(info);
8223                    }
8224                }
8225            }
8226        }
8227    }
8228
8229    @Override
8230    public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8231            int uid, int flags, String metaDataKey) {
8232        final int callingUid = Binder.getCallingUid();
8233        final int userId = processName != null ? UserHandle.getUserId(uid)
8234                : UserHandle.getCallingUserId();
8235        if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8236        flags = updateFlagsForComponent(flags, userId, processName);
8237        ArrayList<ProviderInfo> finalList = null;
8238        // reader
8239        synchronized (mPackages) {
8240            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
8241            while (i.hasNext()) {
8242                final PackageParser.Provider p = i.next();
8243                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
8244                if (ps != null && p.info.authority != null
8245                        && (processName == null
8246                                || (p.info.processName.equals(processName)
8247                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
8248                        && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
8249
8250                    // See PM.queryContentProviders()'s javadoc for why we have the metaData
8251                    // parameter.
8252                    if (metaDataKey != null
8253                            && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) {
8254                        continue;
8255                    }
8256                    final ComponentName component =
8257                            new ComponentName(p.info.packageName, p.info.name);
8258                    if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8259                        continue;
8260                    }
8261                    if (finalList == null) {
8262                        finalList = new ArrayList<ProviderInfo>(3);
8263                    }
8264                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
8265                            ps.readUserState(userId), userId);
8266                    if (info != null) {
8267                        finalList.add(info);
8268                    }
8269                }
8270            }
8271        }
8272
8273        if (finalList != null) {
8274            Collections.sort(finalList, mProviderInitOrderSorter);
8275            return new ParceledListSlice<ProviderInfo>(finalList);
8276        }
8277
8278        return ParceledListSlice.emptyList();
8279    }
8280
8281    @Override
8282    public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8283        // reader
8284        synchronized (mPackages) {
8285            final int callingUid = Binder.getCallingUid();
8286            final int callingUserId = UserHandle.getUserId(callingUid);
8287            final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8288            if (ps == null) return null;
8289            if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8290                return null;
8291            }
8292            final PackageParser.Instrumentation i = mInstrumentation.get(component);
8293            return PackageParser.generateInstrumentationInfo(i, flags);
8294        }
8295    }
8296
8297    @Override
8298    public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8299            String targetPackage, int flags) {
8300        final int callingUid = Binder.getCallingUid();
8301        final int callingUserId = UserHandle.getUserId(callingUid);
8302        final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8303        if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8304            return ParceledListSlice.emptyList();
8305        }
8306        return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8307    }
8308
8309    private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8310            int flags) {
8311        ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>();
8312
8313        // reader
8314        synchronized (mPackages) {
8315            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8316            while (i.hasNext()) {
8317                final PackageParser.Instrumentation p = i.next();
8318                if (targetPackage == null
8319                        || targetPackage.equals(p.info.targetPackage)) {
8320                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
8321                            flags);
8322                    if (ii != null) {
8323                        finalList.add(ii);
8324                    }
8325                }
8326            }
8327        }
8328
8329        return finalList;
8330    }
8331
8332    private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
8333        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
8334        try {
8335            scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
8336        } finally {
8337            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8338        }
8339    }
8340
8341    private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
8342        final File[] files = scanDir.listFiles();
8343        if (ArrayUtils.isEmpty(files)) {
8344            Log.d(TAG, "No files in app dir " + scanDir);
8345            return;
8346        }
8347
8348        if (DEBUG_PACKAGE_SCANNING) {
8349            Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
8350                    + " flags=0x" + Integer.toHexString(parseFlags));
8351        }
8352        try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
8353                mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
8354                mParallelPackageParserCallback)) {
8355            // Submit files for parsing in parallel
8356            int fileCount = 0;
8357            for (File file : files) {
8358                final boolean isPackage = (isApkFile(file) || file.isDirectory())
8359                        && !PackageInstallerService.isStageName(file.getName());
8360                if (!isPackage) {
8361                    // Ignore entries which are not packages
8362                    continue;
8363                }
8364                parallelPackageParser.submit(file, parseFlags);
8365                fileCount++;
8366            }
8367
8368            // Process results one by one
8369            for (; fileCount > 0; fileCount--) {
8370                ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
8371                Throwable throwable = parseResult.throwable;
8372                int errorCode = PackageManager.INSTALL_SUCCEEDED;
8373
8374                if (throwable == null) {
8375                    // TODO(toddke): move lower in the scan chain
8376                    // Static shared libraries have synthetic package names
8377                    if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
8378                        renameStaticSharedLibraryPackage(parseResult.pkg);
8379                    }
8380                    try {
8381                        if (errorCode == PackageManager.INSTALL_SUCCEEDED) {
8382                            scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
8383                                    currentTime, null);
8384                        }
8385                    } catch (PackageManagerException e) {
8386                        errorCode = e.error;
8387                        Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
8388                    }
8389                } else if (throwable instanceof PackageParser.PackageParserException) {
8390                    PackageParser.PackageParserException e = (PackageParser.PackageParserException)
8391                            throwable;
8392                    errorCode = e.error;
8393                    Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
8394                } else {
8395                    throw new IllegalStateException("Unexpected exception occurred while parsing "
8396                            + parseResult.scanFile, throwable);
8397                }
8398
8399                // Delete invalid userdata apps
8400                if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
8401                        errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) {
8402                    logCriticalInfo(Log.WARN,
8403                            "Deleting invalid package at " + parseResult.scanFile);
8404                    removeCodePathLI(parseResult.scanFile);
8405                }
8406            }
8407        }
8408    }
8409
8410    public static void reportSettingsProblem(int priority, String msg) {
8411        logCriticalInfo(priority, msg);
8412    }
8413
8414    private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
8415            boolean forceCollect, boolean skipVerify) throws PackageManagerException {
8416        // When upgrading from pre-N MR1, verify the package time stamp using the package
8417        // directory and not the APK file.
8418        final long lastModifiedTime = mIsPreNMR1Upgrade
8419                ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
8420        if (ps != null && !forceCollect
8421                && ps.codePathString.equals(pkg.codePath)
8422                && ps.timeStamp == lastModifiedTime
8423                && !isCompatSignatureUpdateNeeded(pkg)
8424                && !isRecoverSignatureUpdateNeeded(pkg)) {
8425            if (ps.signatures.mSigningDetails.signatures != null
8426                    && ps.signatures.mSigningDetails.signatures.length != 0
8427                    && ps.signatures.mSigningDetails.signatureSchemeVersion
8428                            != SignatureSchemeVersion.UNKNOWN) {
8429                // Optimization: reuse the existing cached signing data
8430                // if the package appears to be unchanged.
8431                pkg.mSigningDetails =
8432                        new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
8433                return;
8434            }
8435
8436            Slog.w(TAG, "PackageSetting for " + ps.name
8437                    + " is missing signatures.  Collecting certs again to recover them.");
8438        } else {
8439            Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
8440                    (forceCollect ? " (forced)" : ""));
8441        }
8442
8443        try {
8444            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
8445            PackageParser.collectCertificates(pkg, skipVerify);
8446        } catch (PackageParserException e) {
8447            throw PackageManagerException.from(e);
8448        } finally {
8449            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8450        }
8451    }
8452
8453    /**
8454     *  Traces a package scan.
8455     *  @see #scanPackageLI(File, int, int, long, UserHandle)
8456     */
8457    private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
8458            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
8459        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
8460        try {
8461            return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
8462        } finally {
8463            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8464        }
8465    }
8466
8467    /**
8468     *  Scans a package and returns the newly parsed package.
8469     *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
8470     */
8471    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
8472            long currentTime, UserHandle user) throws PackageManagerException {
8473        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
8474        PackageParser pp = new PackageParser();
8475        pp.setSeparateProcesses(mSeparateProcesses);
8476        pp.setOnlyCoreApps(mOnlyCore);
8477        pp.setDisplayMetrics(mMetrics);
8478        pp.setCallback(mPackageParserCallback);
8479
8480        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
8481        final PackageParser.Package pkg;
8482        try {
8483            pkg = pp.parsePackage(scanFile, parseFlags);
8484        } catch (PackageParserException e) {
8485            throw PackageManagerException.from(e);
8486        } finally {
8487            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
8488        }
8489
8490        // Static shared libraries have synthetic package names
8491        if (pkg.applicationInfo.isStaticSharedLibrary()) {
8492            renameStaticSharedLibraryPackage(pkg);
8493        }
8494
8495        return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8496    }
8497
8498    /**
8499     *  Scans a package and returns the newly parsed package.
8500     *  @throws PackageManagerException on a parse error.
8501     */
8502    private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
8503            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8504            @Nullable UserHandle user)
8505                    throws PackageManagerException {
8506        // If the package has children and this is the first dive in the function
8507        // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
8508        // packages (parent and children) would be successfully scanned before the
8509        // actual scan since scanning mutates internal state and we want to atomically
8510        // install the package and its children.
8511        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
8512            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
8513                scanFlags |= SCAN_CHECK_ONLY;
8514            }
8515        } else {
8516            scanFlags &= ~SCAN_CHECK_ONLY;
8517        }
8518
8519        // Scan the parent
8520        PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
8521                scanFlags, currentTime, user);
8522
8523        // Scan the children
8524        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
8525        for (int i = 0; i < childCount; i++) {
8526            PackageParser.Package childPackage = pkg.childPackages.get(i);
8527            addForInitLI(childPackage, parseFlags, scanFlags,
8528                    currentTime, user);
8529        }
8530
8531
8532        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
8533            return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
8534        }
8535
8536        return scannedPkg;
8537    }
8538
8539    /**
8540     * Returns if full apk verification can be skipped for the whole package, including the splits.
8541     */
8542    private boolean canSkipFullPackageVerification(PackageParser.Package pkg) {
8543        if (!canSkipFullApkVerification(pkg.baseCodePath)) {
8544            return false;
8545        }
8546        // TODO: Allow base and splits to be verified individually.
8547        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
8548            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
8549                if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) {
8550                    return false;
8551                }
8552            }
8553        }
8554        return true;
8555    }
8556
8557    /**
8558     * Returns if full apk verification can be skipped, depending on current FSVerity setup and
8559     * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
8560     * match one in a trusted source, and should be done separately.
8561     */
8562    private boolean canSkipFullApkVerification(String apkPath) {
8563        byte[] rootHashObserved = null;
8564        try {
8565            rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath);
8566            if (rootHashObserved == null) {
8567                return false;  // APK does not contain Merkle tree root hash.
8568            }
8569            synchronized (mInstallLock) {
8570                // Returns whether the observed root hash matches what kernel has.
8571                mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
8572                return true;
8573            }
8574        } catch (InstallerException | IOException | DigestException |
8575                NoSuchAlgorithmException e) {
8576            Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
8577        }
8578        return false;
8579    }
8580
8581    /**
8582     * Adds a new package to the internal data structures during platform initialization.
8583     * <p>After adding, the package is known to the system and available for querying.
8584     * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
8585     * etc...], additional checks are performed. Basic verification [such as ensuring
8586     * matching signatures, checking version codes, etc...] occurs if the package is
8587     * identical to a previously known package. If the package fails a signature check,
8588     * the version installed on /data will be removed. If the version of the new package
8589     * is less than or equal than the version on /data, it will be ignored.
8590     * <p>Regardless of the package location, the results are applied to the internal
8591     * structures and the package is made available to the rest of the system.
8592     * <p>NOTE: The return value should be removed. It's the passed in package object.
8593     */
8594    private PackageParser.Package addForInitLI(PackageParser.Package pkg,
8595            @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
8596            @Nullable UserHandle user)
8597                    throws PackageManagerException {
8598        final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
8599        final String renamedPkgName;
8600        final PackageSetting disabledPkgSetting;
8601        final boolean isSystemPkgUpdated;
8602        final boolean pkgAlreadyExists;
8603        PackageSetting pkgSetting;
8604
8605        // NOTE: installPackageLI() has the same code to setup the package's
8606        // application info. This probably should be done lower in the call
8607        // stack [such as scanPackageOnly()]. However, we verify the application
8608        // info prior to that [in scanPackageNew()] and thus have to setup
8609        // the application info early.
8610        pkg.setApplicationVolumeUuid(pkg.volumeUuid);
8611        pkg.setApplicationInfoCodePath(pkg.codePath);
8612        pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
8613        pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
8614        pkg.setApplicationInfoResourcePath(pkg.codePath);
8615        pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
8616        pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
8617
8618        synchronized (mPackages) {
8619            renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
8620            final String realPkgName = getRealPackageName(pkg, renamedPkgName);
8621            if (realPkgName != null) {
8622                ensurePackageRenamed(pkg, renamedPkgName);
8623            }
8624            final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
8625            final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
8626            pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
8627            pkgAlreadyExists = pkgSetting != null;
8628            final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
8629            disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
8630            isSystemPkgUpdated = disabledPkgSetting != null;
8631
8632            if (DEBUG_INSTALL && isSystemPkgUpdated) {
8633                Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
8634            }
8635
8636            final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
8637                    ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
8638                            0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
8639                    : null;
8640            if (DEBUG_PACKAGE_SCANNING
8641                    && (parseFlags & PackageParser.PARSE_CHATTY) != 0
8642                    && sharedUserSetting != null) {
8643                Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
8644                        + " (uid=" + sharedUserSetting.userId + "):"
8645                        + " packages=" + sharedUserSetting.packages);
8646            }
8647
8648            if (scanSystemPartition) {
8649                // Potentially prune child packages. If the application on the /system
8650                // partition has been updated via OTA, but, is still disabled by a
8651                // version on /data, cycle through all of its children packages and
8652                // remove children that are no longer defined.
8653                if (isSystemPkgUpdated) {
8654                    final int scannedChildCount = (pkg.childPackages != null)
8655                            ? pkg.childPackages.size() : 0;
8656                    final int disabledChildCount = disabledPkgSetting.childPackageNames != null
8657                            ? disabledPkgSetting.childPackageNames.size() : 0;
8658                    for (int i = 0; i < disabledChildCount; i++) {
8659                        String disabledChildPackageName =
8660                                disabledPkgSetting.childPackageNames.get(i);
8661                        boolean disabledPackageAvailable = false;
8662                        for (int j = 0; j < scannedChildCount; j++) {
8663                            PackageParser.Package childPkg = pkg.childPackages.get(j);
8664                            if (childPkg.packageName.equals(disabledChildPackageName)) {
8665                                disabledPackageAvailable = true;
8666                                break;
8667                            }
8668                        }
8669                        if (!disabledPackageAvailable) {
8670                            mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
8671                        }
8672                    }
8673                    // we're updating the disabled package, so, scan it as the package setting
8674                    final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
8675                            disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
8676                            null /* originalPkgSetting */, null, parseFlags, scanFlags,
8677                            (pkg == mPlatformPackage), user);
8678                    scanPackageOnlyLI(request, mFactoryTest, -1L);
8679                }
8680            }
8681        }
8682
8683        final boolean newPkgChangedPaths =
8684                pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
8685        final boolean newPkgVersionGreater =
8686                pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
8687        final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
8688                && newPkgChangedPaths && newPkgVersionGreater;
8689        if (isSystemPkgBetter) {
8690            // The version of the application on /system is greater than the version on
8691            // /data. Switch back to the application on /system.
8692            // It's safe to assume the application on /system will correctly scan. If not,
8693            // there won't be a working copy of the application.
8694            synchronized (mPackages) {
8695                // just remove the loaded entries from package lists
8696                mPackages.remove(pkgSetting.name);
8697            }
8698
8699            logCriticalInfo(Log.WARN,
8700                    "System package updated;"
8701                    + " name: " + pkgSetting.name
8702                    + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8703                    + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8704
8705            final InstallArgs args = createInstallArgsForExisting(
8706                    packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8707                    pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8708            args.cleanUpResourcesLI();
8709            synchronized (mPackages) {
8710                mSettings.enableSystemPackageLPw(pkgSetting.name);
8711            }
8712        }
8713
8714        if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
8715            // The version of the application on the /system partition is less than or
8716            // equal to the version on the /data partition. Throw an exception and use
8717            // the application already installed on the /data partition.
8718            throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
8719                    + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode
8720                    + " better than this " + pkg.getLongVersionCode());
8721        }
8722
8723        // Verify certificates against what was last scanned. If it is an updated priv app, we will
8724        // force re-collecting certificate.
8725        final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced(
8726                disabledPkgSetting);
8727        // Full APK verification can be skipped during certificate collection, only if the file is
8728        // in verified partition, or can be verified on access (when apk verity is enabled). In both
8729        // cases, only data in Signing Block is verified instead of the whole file.
8730        final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) ||
8731                (forceCollect && canSkipFullPackageVerification(pkg));
8732        collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
8733
8734        boolean shouldHideSystemApp = false;
8735        // A new application appeared on /system, but, we already have a copy of
8736        // the application installed on /data.
8737        if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
8738                && !pkgSetting.isSystem()) {
8739
8740            if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
8741                    PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
8742                logCriticalInfo(Log.WARN,
8743                        "System package signature mismatch;"
8744                        + " name: " + pkgSetting.name);
8745                try (PackageFreezer freezer = freezePackage(pkg.packageName,
8746                        "scanPackageInternalLI")) {
8747                    deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
8748                }
8749                pkgSetting = null;
8750            } else if (newPkgVersionGreater) {
8751                // The application on /system is newer than the application on /data.
8752                // Simply remove the application on /data [keeping application data]
8753                // and replace it with the version on /system.
8754                logCriticalInfo(Log.WARN,
8755                        "System package enabled;"
8756                        + " name: " + pkgSetting.name
8757                        + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
8758                        + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
8759                InstallArgs args = createInstallArgsForExisting(
8760                        packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString,
8761                        pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
8762                synchronized (mInstallLock) {
8763                    args.cleanUpResourcesLI();
8764                }
8765            } else {
8766                // The application on /system is older than the application on /data. Hide
8767                // the application on /system and the version on /data will be scanned later
8768                // and re-added like an update.
8769                shouldHideSystemApp = true;
8770                logCriticalInfo(Log.INFO,
8771                        "System package disabled;"
8772                        + " name: " + pkgSetting.name
8773                        + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
8774                        + "; new: " + pkg.codePath + " @ " + pkg.codePath);
8775            }
8776        }
8777
8778        final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags
8779                | SCAN_UPDATE_SIGNATURE, currentTime, user);
8780
8781        if (shouldHideSystemApp) {
8782            synchronized (mPackages) {
8783                mSettings.disableSystemPackageLPw(pkg.packageName, true);
8784            }
8785        }
8786        return scannedPkg;
8787    }
8788
8789    private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
8790        // Derive the new package synthetic package name
8791        pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
8792                + pkg.staticSharedLibVersion);
8793    }
8794
8795    private static String fixProcessName(String defProcessName,
8796            String processName) {
8797        if (processName == null) {
8798            return defProcessName;
8799        }
8800        return processName;
8801    }
8802
8803    /**
8804     * Enforces that only the system UID or root's UID can call a method exposed
8805     * via Binder.
8806     *
8807     * @param message used as message if SecurityException is thrown
8808     * @throws SecurityException if the caller is not system or root
8809     */
8810    private static final void enforceSystemOrRoot(String message) {
8811        final int uid = Binder.getCallingUid();
8812        if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
8813            throw new SecurityException(message);
8814        }
8815    }
8816
8817    @Override
8818    public void performFstrimIfNeeded() {
8819        enforceSystemOrRoot("Only the system can request fstrim");
8820
8821        // Before everything else, see whether we need to fstrim.
8822        try {
8823            IStorageManager sm = PackageHelper.getStorageManager();
8824            if (sm != null) {
8825                boolean doTrim = false;
8826                final long interval = android.provider.Settings.Global.getLong(
8827                        mContext.getContentResolver(),
8828                        android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
8829                        DEFAULT_MANDATORY_FSTRIM_INTERVAL);
8830                if (interval > 0) {
8831                    final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
8832                    if (timeSinceLast > interval) {
8833                        doTrim = true;
8834                        Slog.w(TAG, "No disk maintenance in " + timeSinceLast
8835                                + "; running immediately");
8836                    }
8837                }
8838                if (doTrim) {
8839                    final boolean dexOptDialogShown;
8840                    synchronized (mPackages) {
8841                        dexOptDialogShown = mDexOptDialogShown;
8842                    }
8843                    if (!isFirstBoot() && dexOptDialogShown) {
8844                        try {
8845                            ActivityManager.getService().showBootMessage(
8846                                    mContext.getResources().getString(
8847                                            R.string.android_upgrading_fstrim), true);
8848                        } catch (RemoteException e) {
8849                        }
8850                    }
8851                    sm.runMaintenance();
8852                }
8853            } else {
8854                Slog.e(TAG, "storageManager service unavailable!");
8855            }
8856        } catch (RemoteException e) {
8857            // Can't happen; StorageManagerService is local
8858        }
8859    }
8860
8861    @Override
8862    public void updatePackagesIfNeeded() {
8863        enforceSystemOrRoot("Only the system can request package update");
8864
8865        // We need to re-extract after an OTA.
8866        boolean causeUpgrade = isUpgrade();
8867
8868        // First boot or factory reset.
8869        // Note: we also handle devices that are upgrading to N right now as if it is their
8870        //       first boot, as they do not have profile data.
8871        boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
8872
8873        // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
8874        boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
8875
8876        if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
8877            return;
8878        }
8879
8880        List<PackageParser.Package> pkgs;
8881        synchronized (mPackages) {
8882            pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
8883        }
8884
8885        final long startTime = System.nanoTime();
8886        final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
8887                    causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
8888                    false /* bootComplete */);
8889
8890        final int elapsedTimeSeconds =
8891                (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
8892
8893        MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
8894        MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
8895        MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
8896        MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
8897        MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
8898    }
8899
8900    /*
8901     * Return the prebuilt profile path given a package base code path.
8902     */
8903    private static String getPrebuildProfilePath(PackageParser.Package pkg) {
8904        return pkg.baseCodePath + ".prof";
8905    }
8906
8907    /**
8908     * Performs dexopt on the set of packages in {@code packages} and returns an int array
8909     * containing statistics about the invocation. The array consists of three elements,
8910     * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
8911     * and {@code numberOfPackagesFailed}.
8912     */
8913    private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
8914            final int compilationReason, boolean bootComplete) {
8915
8916        int numberOfPackagesVisited = 0;
8917        int numberOfPackagesOptimized = 0;
8918        int numberOfPackagesSkipped = 0;
8919        int numberOfPackagesFailed = 0;
8920        final int numberOfPackagesToDexopt = pkgs.size();
8921
8922        for (PackageParser.Package pkg : pkgs) {
8923            numberOfPackagesVisited++;
8924
8925            boolean useProfileForDexopt = false;
8926
8927            if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) {
8928                // Copy over initial preopt profiles since we won't get any JIT samples for methods
8929                // that are already compiled.
8930                File profileFile = new File(getPrebuildProfilePath(pkg));
8931                // Copy profile if it exists.
8932                if (profileFile.exists()) {
8933                    try {
8934                        // We could also do this lazily before calling dexopt in
8935                        // PackageDexOptimizer to prevent this happening on first boot. The issue
8936                        // is that we don't have a good way to say "do this only once".
8937                        if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8938                                pkg.applicationInfo.uid, pkg.packageName,
8939                                ArtManager.getProfileName(null))) {
8940                            Log.e(TAG, "Installer failed to copy system profile!");
8941                        } else {
8942                            // Disabled as this causes speed-profile compilation during first boot
8943                            // even if things are already compiled.
8944                            // useProfileForDexopt = true;
8945                        }
8946                    } catch (Exception e) {
8947                        Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
8948                                e);
8949                    }
8950                } else {
8951                    PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
8952                    // Handle compressed APKs in this path. Only do this for stubs with profiles to
8953                    // minimize the number off apps being speed-profile compiled during first boot.
8954                    // The other paths will not change the filter.
8955                    if (disabledPs != null && disabledPs.pkg.isStub) {
8956                        // The package is the stub one, remove the stub suffix to get the normal
8957                        // package and APK names.
8958                        String systemProfilePath =
8959                                getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
8960                        profileFile = new File(systemProfilePath);
8961                        // If we have a profile for a compressed APK, copy it to the reference
8962                        // location.
8963                        // Note that copying the profile here will cause it to override the
8964                        // reference profile every OTA even though the existing reference profile
8965                        // may have more data. We can't copy during decompression since the
8966                        // directories are not set up at that point.
8967                        if (profileFile.exists()) {
8968                            try {
8969                                // We could also do this lazily before calling dexopt in
8970                                // PackageDexOptimizer to prevent this happening on first boot. The
8971                                // issue is that we don't have a good way to say "do this only
8972                                // once".
8973                                if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
8974                                        pkg.applicationInfo.uid, pkg.packageName,
8975                                        ArtManager.getProfileName(null))) {
8976                                    Log.e(TAG, "Failed to copy system profile for stub package!");
8977                                } else {
8978                                    useProfileForDexopt = true;
8979                                }
8980                            } catch (Exception e) {
8981                                Log.e(TAG, "Failed to copy profile " +
8982                                        profileFile.getAbsolutePath() + " ", e);
8983                            }
8984                        }
8985                    }
8986                }
8987            }
8988
8989            if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
8990                if (DEBUG_DEXOPT) {
8991                    Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
8992                }
8993                numberOfPackagesSkipped++;
8994                continue;
8995            }
8996
8997            if (DEBUG_DEXOPT) {
8998                Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
8999                        numberOfPackagesToDexopt + ": " + pkg.packageName);
9000            }
9001
9002            if (showDialog) {
9003                try {
9004                    ActivityManager.getService().showBootMessage(
9005                            mContext.getResources().getString(R.string.android_upgrading_apk,
9006                                    numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9007                } catch (RemoteException e) {
9008                }
9009                synchronized (mPackages) {
9010                    mDexOptDialogShown = true;
9011                }
9012            }
9013
9014            int pkgCompilationReason = compilationReason;
9015            if (useProfileForDexopt) {
9016                // Use background dexopt mode to try and use the profile. Note that this does not
9017                // guarantee usage of the profile.
9018                pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9019            }
9020
9021            // checkProfiles is false to avoid merging profiles during boot which
9022            // might interfere with background compilation (b/28612421).
9023            // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9024            // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9025            // trade-off worth doing to save boot time work.
9026            int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9027            if (compilationReason == REASON_FIRST_BOOT) {
9028                // TODO: This doesn't cover the upgrade case, we should check for this too.
9029                dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9030            }
9031            int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9032                    pkg.packageName,
9033                    pkgCompilationReason,
9034                    dexoptFlags));
9035
9036            switch (primaryDexOptStaus) {
9037                case PackageDexOptimizer.DEX_OPT_PERFORMED:
9038                    numberOfPackagesOptimized++;
9039                    break;
9040                case PackageDexOptimizer.DEX_OPT_SKIPPED:
9041                    numberOfPackagesSkipped++;
9042                    break;
9043                case PackageDexOptimizer.DEX_OPT_FAILED:
9044                    numberOfPackagesFailed++;
9045                    break;
9046                default:
9047                    Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9048                    break;
9049            }
9050        }
9051
9052        return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9053                numberOfPackagesFailed };
9054    }
9055
9056    @Override
9057    public void notifyPackageUse(String packageName, int reason) {
9058        synchronized (mPackages) {
9059            final int callingUid = Binder.getCallingUid();
9060            final int callingUserId = UserHandle.getUserId(callingUid);
9061            if (getInstantAppPackageName(callingUid) != null) {
9062                if (!isCallerSameApp(packageName, callingUid)) {
9063                    return;
9064                }
9065            } else {
9066                if (isInstantApp(packageName, callingUserId)) {
9067                    return;
9068                }
9069            }
9070            notifyPackageUseLocked(packageName, reason);
9071        }
9072    }
9073
9074    @GuardedBy("mPackages")
9075    private void notifyPackageUseLocked(String packageName, int reason) {
9076        final PackageParser.Package p = mPackages.get(packageName);
9077        if (p == null) {
9078            return;
9079        }
9080        p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9081    }
9082
9083    @Override
9084    public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9085            List<String> classPaths, String loaderIsa) {
9086        int userId = UserHandle.getCallingUserId();
9087        ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9088        if (ai == null) {
9089            Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9090                + loadingPackageName + ", user=" + userId);
9091            return;
9092        }
9093        mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9094    }
9095
9096    @Override
9097    public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9098            IDexModuleRegisterCallback callback) {
9099        int userId = UserHandle.getCallingUserId();
9100        ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9101        DexManager.RegisterDexModuleResult result;
9102        if (ai == null) {
9103            Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9104                     " calling user. package=" + packageName + ", user=" + userId);
9105            result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9106        } else {
9107            result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9108        }
9109
9110        if (callback != null) {
9111            mHandler.post(() -> {
9112                try {
9113                    callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9114                } catch (RemoteException e) {
9115                    Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9116                }
9117            });
9118        }
9119    }
9120
9121    /**
9122     * Ask the package manager to perform a dex-opt with the given compiler filter.
9123     *
9124     * Note: exposed only for the shell command to allow moving packages explicitly to a
9125     *       definite state.
9126     */
9127    @Override
9128    public boolean performDexOptMode(String packageName,
9129            boolean checkProfiles, String targetCompilerFilter, boolean force,
9130            boolean bootComplete, String splitName) {
9131        int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9132                (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9133                (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9134        return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9135                targetCompilerFilter, splitName, flags));
9136    }
9137
9138    /**
9139     * Ask the package manager to perform a dex-opt with the given compiler filter on the
9140     * secondary dex files belonging to the given package.
9141     *
9142     * Note: exposed only for the shell command to allow moving packages explicitly to a
9143     *       definite state.
9144     */
9145    @Override
9146    public boolean performDexOptSecondary(String packageName, String compilerFilter,
9147            boolean force) {
9148        int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9149                DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9150                DexoptOptions.DEXOPT_BOOT_COMPLETE |
9151                (force ? DexoptOptions.DEXOPT_FORCE : 0);
9152        return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9153    }
9154
9155    /*package*/ boolean performDexOpt(DexoptOptions options) {
9156        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9157            return false;
9158        } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9159            return false;
9160        }
9161
9162        if (options.isDexoptOnlySecondaryDex()) {
9163            return mDexManager.dexoptSecondaryDex(options);
9164        } else {
9165            int dexoptStatus = performDexOptWithStatus(options);
9166            return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9167        }
9168    }
9169
9170    /**
9171     * Perform dexopt on the given package and return one of following result:
9172     *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9173     *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9174     *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9175     */
9176    /* package */ int performDexOptWithStatus(DexoptOptions options) {
9177        return performDexOptTraced(options);
9178    }
9179
9180    private int performDexOptTraced(DexoptOptions options) {
9181        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9182        try {
9183            return performDexOptInternal(options);
9184        } finally {
9185            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9186        }
9187    }
9188
9189    // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9190    // if the package can now be considered up to date for the given filter.
9191    private int performDexOptInternal(DexoptOptions options) {
9192        PackageParser.Package p;
9193        synchronized (mPackages) {
9194            p = mPackages.get(options.getPackageName());
9195            if (p == null) {
9196                // Package could not be found. Report failure.
9197                return PackageDexOptimizer.DEX_OPT_FAILED;
9198            }
9199            mPackageUsage.maybeWriteAsync(mPackages);
9200            mCompilerStats.maybeWriteAsync();
9201        }
9202        long callingId = Binder.clearCallingIdentity();
9203        try {
9204            synchronized (mInstallLock) {
9205                return performDexOptInternalWithDependenciesLI(p, options);
9206            }
9207        } finally {
9208            Binder.restoreCallingIdentity(callingId);
9209        }
9210    }
9211
9212    public ArraySet<String> getOptimizablePackages() {
9213        ArraySet<String> pkgs = new ArraySet<String>();
9214        synchronized (mPackages) {
9215            for (PackageParser.Package p : mPackages.values()) {
9216                if (PackageDexOptimizer.canOptimizePackage(p)) {
9217                    pkgs.add(p.packageName);
9218                }
9219            }
9220        }
9221        return pkgs;
9222    }
9223
9224    private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
9225            DexoptOptions options) {
9226        // Select the dex optimizer based on the force parameter.
9227        // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
9228        //       allocate an object here.
9229        PackageDexOptimizer pdo = options.isForce()
9230                ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
9231                : mPackageDexOptimizer;
9232
9233        // Dexopt all dependencies first. Note: we ignore the return value and march on
9234        // on errors.
9235        // Note that we are going to call performDexOpt on those libraries as many times as
9236        // they are referenced in packages. When we do a batch of performDexOpt (for example
9237        // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
9238        // and the first package that uses the library will dexopt it. The
9239        // others will see that the compiled code for the library is up to date.
9240        Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p);
9241        final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
9242        if (!deps.isEmpty()) {
9243            DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
9244                    options.getCompilationReason(), options.getCompilerFilter(),
9245                    options.getSplitName(),
9246                    options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
9247            for (PackageParser.Package depPackage : deps) {
9248                // TODO: Analyze and investigate if we (should) profile libraries.
9249                pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets,
9250                        getOrCreateCompilerPackageStats(depPackage),
9251                    mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions);
9252            }
9253        }
9254        return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets,
9255                getOrCreateCompilerPackageStats(p),
9256                mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
9257    }
9258
9259    /**
9260     * Reconcile the information we have about the secondary dex files belonging to
9261     * {@code packagName} and the actual dex files. For all dex files that were
9262     * deleted, update the internal records and delete the generated oat files.
9263     */
9264    @Override
9265    public void reconcileSecondaryDexFiles(String packageName) {
9266        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9267            return;
9268        } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
9269            return;
9270        }
9271        mDexManager.reconcileSecondaryDexFiles(packageName);
9272    }
9273
9274    // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
9275    // a reference there.
9276    /*package*/ DexManager getDexManager() {
9277        return mDexManager;
9278    }
9279
9280    /**
9281     * Execute the background dexopt job immediately.
9282     */
9283    @Override
9284    public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
9285        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9286            return false;
9287        }
9288        return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
9289    }
9290
9291    List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) {
9292        if (p.usesLibraries != null || p.usesOptionalLibraries != null
9293                || p.usesStaticLibraries != null) {
9294            ArrayList<PackageParser.Package> retValue = new ArrayList<>();
9295            Set<String> collectedNames = new HashSet<>();
9296            findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames);
9297
9298            retValue.remove(p);
9299
9300            return retValue;
9301        } else {
9302            return Collections.emptyList();
9303        }
9304    }
9305
9306    private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p,
9307            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9308        if (!collectedNames.contains(p.packageName)) {
9309            collectedNames.add(p.packageName);
9310            collected.add(p);
9311
9312            if (p.usesLibraries != null) {
9313                findSharedNonSystemLibrariesRecursive(p.usesLibraries,
9314                        null, collected, collectedNames);
9315            }
9316            if (p.usesOptionalLibraries != null) {
9317                findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries,
9318                        null, collected, collectedNames);
9319            }
9320            if (p.usesStaticLibraries != null) {
9321                findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries,
9322                        p.usesStaticLibrariesVersions, collected, collectedNames);
9323            }
9324        }
9325    }
9326
9327    private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions,
9328            ArrayList<PackageParser.Package> collected, Set<String> collectedNames) {
9329        final int libNameCount = libs.size();
9330        for (int i = 0; i < libNameCount; i++) {
9331            String libName = libs.get(i);
9332            long version = (versions != null && versions.length == libNameCount)
9333                    ? versions[i] : PackageManager.VERSION_CODE_HIGHEST;
9334            PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version);
9335            if (libPkg != null) {
9336                findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames);
9337            }
9338        }
9339    }
9340
9341    private PackageParser.Package findSharedNonSystemLibrary(String name, long version) {
9342        synchronized (mPackages) {
9343            SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version);
9344            if (libEntry != null) {
9345                return mPackages.get(libEntry.apk);
9346            }
9347            return null;
9348        }
9349    }
9350
9351    private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) {
9352        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
9353        if (versionedLib == null) {
9354            return null;
9355        }
9356        return versionedLib.get(version);
9357    }
9358
9359    private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
9360        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
9361                pkg.staticSharedLibName);
9362        if (versionedLib == null) {
9363            return null;
9364        }
9365        long previousLibVersion = -1;
9366        final int versionCount = versionedLib.size();
9367        for (int i = 0; i < versionCount; i++) {
9368            final long libVersion = versionedLib.keyAt(i);
9369            if (libVersion < pkg.staticSharedLibVersion) {
9370                previousLibVersion = Math.max(previousLibVersion, libVersion);
9371            }
9372        }
9373        if (previousLibVersion >= 0) {
9374            return versionedLib.get(previousLibVersion);
9375        }
9376        return null;
9377    }
9378
9379    public void shutdown() {
9380        mPackageUsage.writeNow(mPackages);
9381        mCompilerStats.writeNow();
9382        mDexManager.writePackageDexUsageNow();
9383    }
9384
9385    @Override
9386    public void dumpProfiles(String packageName) {
9387        PackageParser.Package pkg;
9388        synchronized (mPackages) {
9389            pkg = mPackages.get(packageName);
9390            if (pkg == null) {
9391                throw new IllegalArgumentException("Unknown package: " + packageName);
9392            }
9393        }
9394        /* Only the shell, root, or the app user should be able to dump profiles. */
9395        int callingUid = Binder.getCallingUid();
9396        if (callingUid != Process.SHELL_UID &&
9397            callingUid != Process.ROOT_UID &&
9398            callingUid != pkg.applicationInfo.uid) {
9399            throw new SecurityException("dumpProfiles");
9400        }
9401
9402        synchronized (mInstallLock) {
9403            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
9404            mArtManagerService.dumpProfiles(pkg);
9405            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9406        }
9407    }
9408
9409    @Override
9410    public void forceDexOpt(String packageName) {
9411        enforceSystemOrRoot("forceDexOpt");
9412
9413        PackageParser.Package pkg;
9414        synchronized (mPackages) {
9415            pkg = mPackages.get(packageName);
9416            if (pkg == null) {
9417                throw new IllegalArgumentException("Unknown package: " + packageName);
9418            }
9419        }
9420
9421        synchronized (mInstallLock) {
9422            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9423
9424            // Whoever is calling forceDexOpt wants a compiled package.
9425            // Don't use profiles since that may cause compilation to be skipped.
9426            final int res = performDexOptInternalWithDependenciesLI(
9427                    pkg,
9428                    new DexoptOptions(packageName,
9429                            getDefaultCompilerFilter(),
9430                            DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
9431
9432            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9433            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
9434                throw new IllegalStateException("Failed to dexopt: " + res);
9435            }
9436        }
9437    }
9438
9439    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
9440        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
9441            Slog.w(TAG, "Unable to update from " + oldPkg.name
9442                    + " to " + newPkg.packageName
9443                    + ": old package not in system partition");
9444            return false;
9445        } else if (mPackages.get(oldPkg.name) != null) {
9446            Slog.w(TAG, "Unable to update from " + oldPkg.name
9447                    + " to " + newPkg.packageName
9448                    + ": old package still exists");
9449            return false;
9450        }
9451        return true;
9452    }
9453
9454    void removeCodePathLI(File codePath) {
9455        if (codePath.isDirectory()) {
9456            try {
9457                mInstaller.rmPackageDir(codePath.getAbsolutePath());
9458            } catch (InstallerException e) {
9459                Slog.w(TAG, "Failed to remove code path", e);
9460            }
9461        } else {
9462            codePath.delete();
9463        }
9464    }
9465
9466    private int[] resolveUserIds(int userId) {
9467        return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
9468    }
9469
9470    private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9471        if (pkg == null) {
9472            Slog.wtf(TAG, "Package was null!", new Throwable());
9473            return;
9474        }
9475        clearAppDataLeafLIF(pkg, userId, flags);
9476        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9477        for (int i = 0; i < childCount; i++) {
9478            clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9479        }
9480
9481        clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
9482    }
9483
9484    private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9485        final PackageSetting ps;
9486        synchronized (mPackages) {
9487            ps = mSettings.mPackages.get(pkg.packageName);
9488        }
9489        for (int realUserId : resolveUserIds(userId)) {
9490            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9491            try {
9492                mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9493                        ceDataInode);
9494            } catch (InstallerException e) {
9495                Slog.w(TAG, String.valueOf(e));
9496            }
9497        }
9498    }
9499
9500    private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
9501        if (pkg == null) {
9502            Slog.wtf(TAG, "Package was null!", new Throwable());
9503            return;
9504        }
9505        destroyAppDataLeafLIF(pkg, userId, flags);
9506        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9507        for (int i = 0; i < childCount; i++) {
9508            destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
9509        }
9510    }
9511
9512    private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
9513        final PackageSetting ps;
9514        synchronized (mPackages) {
9515            ps = mSettings.mPackages.get(pkg.packageName);
9516        }
9517        for (int realUserId : resolveUserIds(userId)) {
9518            final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
9519            try {
9520                mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
9521                        ceDataInode);
9522            } catch (InstallerException e) {
9523                Slog.w(TAG, String.valueOf(e));
9524            }
9525            mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
9526        }
9527    }
9528
9529    private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) {
9530        if (pkg == null) {
9531            Slog.wtf(TAG, "Package was null!", new Throwable());
9532            return;
9533        }
9534        destroyAppProfilesLeafLIF(pkg);
9535        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9536        for (int i = 0; i < childCount; i++) {
9537            destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
9538        }
9539    }
9540
9541    private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
9542        try {
9543            mInstaller.destroyAppProfiles(pkg.packageName);
9544        } catch (InstallerException e) {
9545            Slog.w(TAG, String.valueOf(e));
9546        }
9547    }
9548
9549    private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
9550        if (pkg == null) {
9551            Slog.wtf(TAG, "Package was null!", new Throwable());
9552            return;
9553        }
9554        mArtManagerService.clearAppProfiles(pkg);
9555        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9556        for (int i = 0; i < childCount; i++) {
9557            mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
9558        }
9559    }
9560
9561    private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
9562            long lastUpdateTime) {
9563        // Set parent install/update time
9564        PackageSetting ps = (PackageSetting) pkg.mExtras;
9565        if (ps != null) {
9566            ps.firstInstallTime = firstInstallTime;
9567            ps.lastUpdateTime = lastUpdateTime;
9568        }
9569        // Set children install/update time
9570        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9571        for (int i = 0; i < childCount; i++) {
9572            PackageParser.Package childPkg = pkg.childPackages.get(i);
9573            ps = (PackageSetting) childPkg.mExtras;
9574            if (ps != null) {
9575                ps.firstInstallTime = firstInstallTime;
9576                ps.lastUpdateTime = lastUpdateTime;
9577            }
9578        }
9579    }
9580
9581    private void addSharedLibraryLPr(Set<String> usesLibraryFiles,
9582            SharedLibraryEntry file,
9583            PackageParser.Package changingLib) {
9584        if (file.path != null) {
9585            usesLibraryFiles.add(file.path);
9586            return;
9587        }
9588        PackageParser.Package p = mPackages.get(file.apk);
9589        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
9590            // If we are doing this while in the middle of updating a library apk,
9591            // then we need to make sure to use that new apk for determining the
9592            // dependencies here.  (We haven't yet finished committing the new apk
9593            // to the package manager state.)
9594            if (p == null || p.packageName.equals(changingLib.packageName)) {
9595                p = changingLib;
9596            }
9597        }
9598        if (p != null) {
9599            usesLibraryFiles.addAll(p.getAllCodePaths());
9600            if (p.usesLibraryFiles != null) {
9601                Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
9602            }
9603        }
9604    }
9605
9606    private void updateSharedLibrariesLPr(PackageParser.Package pkg,
9607            PackageParser.Package changingLib) throws PackageManagerException {
9608        if (pkg == null) {
9609            return;
9610        }
9611        // The collection used here must maintain the order of addition (so
9612        // that libraries are searched in the correct order) and must have no
9613        // duplicates.
9614        Set<String> usesLibraryFiles = null;
9615        if (pkg.usesLibraries != null) {
9616            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries,
9617                    null, null, pkg.packageName, changingLib, true,
9618                    pkg.applicationInfo.targetSdkVersion, null);
9619        }
9620        if (pkg.usesStaticLibraries != null) {
9621            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries,
9622                    pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
9623                    pkg.packageName, changingLib, true,
9624                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9625        }
9626        if (pkg.usesOptionalLibraries != null) {
9627            usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries,
9628                    null, null, pkg.packageName, changingLib, false,
9629                    pkg.applicationInfo.targetSdkVersion, usesLibraryFiles);
9630        }
9631        if (!ArrayUtils.isEmpty(usesLibraryFiles)) {
9632            pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
9633        } else {
9634            pkg.usesLibraryFiles = null;
9635        }
9636    }
9637
9638    private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries,
9639            @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
9640            @NonNull String packageName, @Nullable PackageParser.Package changingLib,
9641            boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries)
9642            throws PackageManagerException {
9643        final int libCount = requestedLibraries.size();
9644        for (int i = 0; i < libCount; i++) {
9645            final String libName = requestedLibraries.get(i);
9646            final long libVersion = requiredVersions != null ? requiredVersions[i]
9647                    : SharedLibraryInfo.VERSION_UNDEFINED;
9648            final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion);
9649            if (libEntry == null) {
9650                if (required) {
9651                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9652                            "Package " + packageName + " requires unavailable shared library "
9653                                    + libName + "; failing!");
9654                } else if (DEBUG_SHARED_LIBRARIES) {
9655                    Slog.i(TAG, "Package " + packageName
9656                            + " desires unavailable shared library "
9657                            + libName + "; ignoring!");
9658                }
9659            } else {
9660                if (requiredVersions != null && requiredCertDigests != null) {
9661                    if (libEntry.info.getLongVersion() != requiredVersions[i]) {
9662                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9663                            "Package " + packageName + " requires unavailable static shared"
9664                                    + " library " + libName + " version "
9665                                    + libEntry.info.getLongVersion() + "; failing!");
9666                    }
9667
9668                    PackageParser.Package libPkg = mPackages.get(libEntry.apk);
9669                    if (libPkg == null) {
9670                        throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9671                                "Package " + packageName + " requires unavailable static shared"
9672                                        + " library; failing!");
9673                    }
9674
9675                    final String[] expectedCertDigests = requiredCertDigests[i];
9676
9677
9678                    if (expectedCertDigests.length > 1) {
9679
9680                        // For apps targeting O MR1 we require explicit enumeration of all certs.
9681                        final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O)
9682                                ? PackageUtils.computeSignaturesSha256Digests(
9683                                libPkg.mSigningDetails.signatures)
9684                                : PackageUtils.computeSignaturesSha256Digests(
9685                                        new Signature[]{libPkg.mSigningDetails.signatures[0]});
9686
9687                        // Take a shortcut if sizes don't match. Note that if an app doesn't
9688                        // target O we don't parse the "additional-certificate" tags similarly
9689                        // how we only consider all certs only for apps targeting O (see above).
9690                        // Therefore, the size check is safe to make.
9691                        if (expectedCertDigests.length != libCertDigests.length) {
9692                            throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9693                                    "Package " + packageName + " requires differently signed" +
9694                                            " static shared library; failing!");
9695                        }
9696
9697                        // Use a predictable order as signature order may vary
9698                        Arrays.sort(libCertDigests);
9699                        Arrays.sort(expectedCertDigests);
9700
9701                        final int certCount = libCertDigests.length;
9702                        for (int j = 0; j < certCount; j++) {
9703                            if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
9704                                throw new PackageManagerException(
9705                                        INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9706                                        "Package " + packageName + " requires differently signed" +
9707                                                " static shared library; failing!");
9708                            }
9709                        }
9710                    } else {
9711
9712                        // lib signing cert could have rotated beyond the one expected, check to see
9713                        // if the new one has been blessed by the old
9714                        if (!libPkg.mSigningDetails.hasSha256Certificate(
9715                                ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
9716                            throw new PackageManagerException(
9717                                    INSTALL_FAILED_MISSING_SHARED_LIBRARY,
9718                                    "Package " + packageName + " requires differently signed" +
9719                                            " static shared library; failing!");
9720                        }
9721                    }
9722                }
9723
9724                if (outUsedLibraries == null) {
9725                    // Use LinkedHashSet to preserve the order of files added to
9726                    // usesLibraryFiles while eliminating duplicates.
9727                    outUsedLibraries = new LinkedHashSet<>();
9728                }
9729                addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib);
9730            }
9731        }
9732        return outUsedLibraries;
9733    }
9734
9735    private static boolean hasString(List<String> list, List<String> which) {
9736        if (list == null) {
9737            return false;
9738        }
9739        for (int i=list.size()-1; i>=0; i--) {
9740            for (int j=which.size()-1; j>=0; j--) {
9741                if (which.get(j).equals(list.get(i))) {
9742                    return true;
9743                }
9744            }
9745        }
9746        return false;
9747    }
9748
9749    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
9750            PackageParser.Package changingPkg) {
9751        ArrayList<PackageParser.Package> res = null;
9752        for (PackageParser.Package pkg : mPackages.values()) {
9753            if (changingPkg != null
9754                    && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
9755                    && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
9756                    && !ArrayUtils.contains(pkg.usesStaticLibraries,
9757                            changingPkg.staticSharedLibName)) {
9758                return null;
9759            }
9760            if (res == null) {
9761                res = new ArrayList<>();
9762            }
9763            res.add(pkg);
9764            try {
9765                updateSharedLibrariesLPr(pkg, changingPkg);
9766            } catch (PackageManagerException e) {
9767                // If a system app update or an app and a required lib missing we
9768                // delete the package and for updated system apps keep the data as
9769                // it is better for the user to reinstall than to be in an limbo
9770                // state. Also libs disappearing under an app should never happen
9771                // - just in case.
9772                if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
9773                    final int flags = pkg.isUpdatedSystemApp()
9774                            ? PackageManager.DELETE_KEEP_DATA : 0;
9775                    deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
9776                            flags , null, true, null);
9777                }
9778                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
9779            }
9780        }
9781        return res;
9782    }
9783
9784    private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg,
9785            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9786            @Nullable UserHandle user) throws PackageManagerException {
9787        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
9788        // If the package has children and this is the first dive in the function
9789        // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
9790        // whether all packages (parent and children) would be successfully scanned
9791        // before the actual scan since scanning mutates internal state and we want
9792        // to atomically install the package and its children.
9793        if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9794            if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9795                scanFlags |= SCAN_CHECK_ONLY;
9796            }
9797        } else {
9798            scanFlags &= ~SCAN_CHECK_ONLY;
9799        }
9800
9801        final PackageParser.Package scannedPkg;
9802        try {
9803            // Scan the parent
9804            scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user);
9805            // Scan the children
9806            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9807            for (int i = 0; i < childCount; i++) {
9808                PackageParser.Package childPkg = pkg.childPackages.get(i);
9809                scanPackageNewLI(childPkg, parseFlags,
9810                        scanFlags, currentTime, user);
9811            }
9812        } finally {
9813            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9814        }
9815
9816        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9817            return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
9818        }
9819
9820        return scannedPkg;
9821    }
9822
9823    /** The result of a package scan. */
9824    private static class ScanResult {
9825        /** Whether or not the package scan was successful */
9826        public final boolean success;
9827        /**
9828         * The final package settings. This may be the same object passed in
9829         * the {@link ScanRequest}, but, with modified values.
9830         */
9831        @Nullable public final PackageSetting pkgSetting;
9832        /** ABI code paths that have changed in the package scan */
9833        @Nullable public final List<String> changedAbiCodePath;
9834        public ScanResult(
9835                boolean success,
9836                @Nullable PackageSetting pkgSetting,
9837                @Nullable List<String> changedAbiCodePath) {
9838            this.success = success;
9839            this.pkgSetting = pkgSetting;
9840            this.changedAbiCodePath = changedAbiCodePath;
9841        }
9842    }
9843
9844    /** A package to be scanned */
9845    private static class ScanRequest {
9846        /** The parsed package */
9847        @NonNull public final PackageParser.Package pkg;
9848        /** Shared user settings, if the package has a shared user */
9849        @Nullable public final SharedUserSetting sharedUserSetting;
9850        /**
9851         * Package settings of the currently installed version.
9852         * <p><em>IMPORTANT:</em> The contents of this object may be modified
9853         * during scan.
9854         */
9855        @Nullable public final PackageSetting pkgSetting;
9856        /** A copy of the settings for the currently installed version */
9857        @Nullable public final PackageSetting oldPkgSetting;
9858        /** Package settings for the disabled version on the /system partition */
9859        @Nullable public final PackageSetting disabledPkgSetting;
9860        /** Package settings for the installed version under its original package name */
9861        @Nullable public final PackageSetting originalPkgSetting;
9862        /** The real package name of a renamed application */
9863        @Nullable public final String realPkgName;
9864        public final @ParseFlags int parseFlags;
9865        public final @ScanFlags int scanFlags;
9866        /** The user for which the package is being scanned */
9867        @Nullable public final UserHandle user;
9868        /** Whether or not the platform package is being scanned */
9869        public final boolean isPlatformPackage;
9870        public ScanRequest(
9871                @NonNull PackageParser.Package pkg,
9872                @Nullable SharedUserSetting sharedUserSetting,
9873                @Nullable PackageSetting pkgSetting,
9874                @Nullable PackageSetting disabledPkgSetting,
9875                @Nullable PackageSetting originalPkgSetting,
9876                @Nullable String realPkgName,
9877                @ParseFlags int parseFlags,
9878                @ScanFlags int scanFlags,
9879                boolean isPlatformPackage,
9880                @Nullable UserHandle user) {
9881            this.pkg = pkg;
9882            this.pkgSetting = pkgSetting;
9883            this.sharedUserSetting = sharedUserSetting;
9884            this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
9885            this.disabledPkgSetting = disabledPkgSetting;
9886            this.originalPkgSetting = originalPkgSetting;
9887            this.realPkgName = realPkgName;
9888            this.parseFlags = parseFlags;
9889            this.scanFlags = scanFlags;
9890            this.isPlatformPackage = isPlatformPackage;
9891            this.user = user;
9892        }
9893    }
9894
9895    /**
9896     * Returns the actual scan flags depending upon the state of the other settings.
9897     * <p>Updated system applications will not have the following flags set
9898     * by default and need to be adjusted after the fact:
9899     * <ul>
9900     * <li>{@link #SCAN_AS_SYSTEM}</li>
9901     * <li>{@link #SCAN_AS_PRIVILEGED}</li>
9902     * <li>{@link #SCAN_AS_OEM}</li>
9903     * <li>{@link #SCAN_AS_VENDOR}</li>
9904     * <li>{@link #SCAN_AS_PRODUCT}</li>
9905     * <li>{@link #SCAN_AS_INSTANT_APP}</li>
9906     * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
9907     * </ul>
9908     */
9909    private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
9910            PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
9911            PackageParser.Package pkg) {
9912        if (disabledPkgSetting != null) {
9913            // updated system application, must at least have SCAN_AS_SYSTEM
9914            scanFlags |= SCAN_AS_SYSTEM;
9915            if ((disabledPkgSetting.pkgPrivateFlags
9916                    & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
9917                scanFlags |= SCAN_AS_PRIVILEGED;
9918            }
9919            if ((disabledPkgSetting.pkgPrivateFlags
9920                    & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
9921                scanFlags |= SCAN_AS_OEM;
9922            }
9923            if ((disabledPkgSetting.pkgPrivateFlags
9924                    & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
9925                scanFlags |= SCAN_AS_VENDOR;
9926            }
9927            if ((disabledPkgSetting.pkgPrivateFlags
9928                    & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
9929                scanFlags |= SCAN_AS_PRODUCT;
9930            }
9931        }
9932        if (pkgSetting != null) {
9933            final int userId = ((user == null) ? 0 : user.getIdentifier());
9934            if (pkgSetting.getInstantApp(userId)) {
9935                scanFlags |= SCAN_AS_INSTANT_APP;
9936            }
9937            if (pkgSetting.getVirtulalPreload(userId)) {
9938                scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
9939            }
9940        }
9941
9942        // Scan as privileged apps that share a user with a priv-app.
9943        if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged()
9944                && (pkg.mSharedUserId != null)) {
9945            SharedUserSetting sharedUserSetting = null;
9946            try {
9947                sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
9948            } catch (PackageManagerException ignore) {}
9949            if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
9950                // Exempt SharedUsers signed with the platform key.
9951                // TODO(b/72378145) Fix this exemption. Force signature apps
9952                // to whitelist their privileged permissions just like other
9953                // priv-apps.
9954                synchronized (mPackages) {
9955                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
9956                    if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
9957                                pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
9958                        scanFlags |= SCAN_AS_PRIVILEGED;
9959                    }
9960                }
9961            }
9962        }
9963
9964        return scanFlags;
9965    }
9966
9967    @GuardedBy("mInstallLock")
9968    private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg,
9969            final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9970            @Nullable UserHandle user) throws PackageManagerException {
9971
9972        final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9973        final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9974        if (realPkgName != null) {
9975            ensurePackageRenamed(pkg, renamedPkgName);
9976        }
9977        final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9978        final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
9979        final PackageSetting disabledPkgSetting =
9980                mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9981
9982        if (mTransferedPackages.contains(pkg.packageName)) {
9983            Slog.w(TAG, "Package " + pkg.packageName
9984                    + " was transferred to another, but its .apk remains");
9985        }
9986
9987        scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
9988        synchronized (mPackages) {
9989            applyPolicy(pkg, parseFlags, scanFlags);
9990            assertPackageIsValid(pkg, parseFlags, scanFlags);
9991
9992            SharedUserSetting sharedUserSetting = null;
9993            if (pkg.mSharedUserId != null) {
9994                // SIDE EFFECTS; may potentially allocate a new shared user
9995                sharedUserSetting = mSettings.getSharedUserLPw(
9996                        pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
9997                if (DEBUG_PACKAGE_SCANNING) {
9998                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
9999                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10000                                + " (uid=" + sharedUserSetting.userId + "):"
10001                                + " packages=" + sharedUserSetting.packages);
10002                }
10003            }
10004
10005            boolean scanSucceeded = false;
10006            try {
10007                final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting,
10008                        disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags,
10009                        (pkg == mPlatformPackage), user);
10010                final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime);
10011                if (result.success) {
10012                    commitScanResultsLocked(request, result);
10013                }
10014                scanSucceeded = true;
10015            } finally {
10016                  if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
10017                      // DELETE_DATA_ON_FAILURES is only used by frozen paths
10018                      destroyAppDataLIF(pkg, UserHandle.USER_ALL,
10019                              StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
10020                      destroyAppProfilesLIF(pkg, UserHandle.USER_ALL);
10021                  }
10022            }
10023        }
10024        return pkg;
10025    }
10026
10027    /**
10028     * Commits the package scan and modifies system state.
10029     * <p><em>WARNING:</em> The method may throw an excpetion in the middle
10030     * of committing the package, leaving the system in an inconsistent state.
10031     * This needs to be fixed so, once we get to this point, no errors are
10032     * possible and the system is not left in an inconsistent state.
10033     */
10034    @GuardedBy("mPackages")
10035    private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result)
10036            throws PackageManagerException {
10037        final PackageParser.Package pkg = request.pkg;
10038        final @ParseFlags int parseFlags = request.parseFlags;
10039        final @ScanFlags int scanFlags = request.scanFlags;
10040        final PackageSetting oldPkgSetting = request.oldPkgSetting;
10041        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10042        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10043        final UserHandle user = request.user;
10044        final String realPkgName = request.realPkgName;
10045        final PackageSetting pkgSetting = result.pkgSetting;
10046        final List<String> changedAbiCodePath = result.changedAbiCodePath;
10047        final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting);
10048
10049        if (newPkgSettingCreated) {
10050            if (originalPkgSetting != null) {
10051                mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
10052            }
10053            // THROWS: when we can't allocate a user id. add call to check if there's
10054            // enough space to ensure we won't throw; otherwise, don't modify state
10055            mSettings.addUserToSettingLPw(pkgSetting);
10056
10057            if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
10058                mTransferedPackages.add(originalPkgSetting.name);
10059            }
10060        }
10061        // TODO(toddke): Consider a method specifically for modifying the Package object
10062        // post scan; or, moving this stuff out of the Package object since it has nothing
10063        // to do with the package on disk.
10064        // We need to have this here because addUserToSettingLPw() is sometimes responsible
10065        // for creating the application ID. If we did this earlier, we would be saving the
10066        // correct ID.
10067        pkg.applicationInfo.uid = pkgSetting.appId;
10068
10069        mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
10070
10071        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
10072            mTransferedPackages.add(pkg.packageName);
10073        }
10074
10075        // THROWS: when requested libraries that can't be found. it only changes
10076        // the state of the passed in pkg object, so, move to the top of the method
10077        // and allow it to abort
10078        if ((scanFlags & SCAN_BOOTING) == 0
10079                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10080            // Check all shared libraries and map to their actual file path.
10081            // We only do this here for apps not on a system dir, because those
10082            // are the only ones that can fail an install due to this.  We
10083            // will take care of the system apps by updating all of their
10084            // library paths after the scan is done. Also during the initial
10085            // scan don't update any libs as we do this wholesale after all
10086            // apps are scanned to avoid dependency based scanning.
10087            updateSharedLibrariesLPr(pkg, null);
10088        }
10089
10090        // All versions of a static shared library are referenced with the same
10091        // package name. Internally, we use a synthetic package name to allow
10092        // multiple versions of the same shared library to be installed. So,
10093        // we need to generate the synthetic package name of the latest shared
10094        // library in order to compare signatures.
10095        PackageSetting signatureCheckPs = pkgSetting;
10096        if (pkg.applicationInfo.isStaticSharedLibrary()) {
10097            SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
10098            if (libraryEntry != null) {
10099                signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
10100            }
10101        }
10102
10103        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10104        if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
10105            if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
10106                // We just determined the app is signed correctly, so bring
10107                // over the latest parsed certs.
10108                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10109            } else {
10110                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10111                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10112                            "Package " + pkg.packageName + " upgrade keys do not match the "
10113                                    + "previously installed version");
10114                } else {
10115                    pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10116                    String msg = "System package " + pkg.packageName
10117                            + " signature changed; retaining data.";
10118                    reportSettingsProblem(Log.WARN, msg);
10119                }
10120            }
10121        } else {
10122            try {
10123                final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
10124                final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
10125                final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting,
10126                        pkg.mSigningDetails, compareCompat, compareRecover);
10127                // The new KeySets will be re-added later in the scanning process.
10128                if (compatMatch) {
10129                    synchronized (mPackages) {
10130                        ksms.removeAppKeySetDataLPw(pkg.packageName);
10131                    }
10132                }
10133                // We just determined the app is signed correctly, so bring
10134                // over the latest parsed certs.
10135                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10136
10137
10138                // if this is is a sharedUser, check to see if the new package is signed by a newer
10139                // signing certificate than the existing one, and if so, copy over the new details
10140                if (signatureCheckPs.sharedUser != null
10141                        && pkg.mSigningDetails.hasAncestor(
10142                                signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
10143                    signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails;
10144                }
10145            } catch (PackageManagerException e) {
10146                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
10147                    throw e;
10148                }
10149                // The signature has changed, but this package is in the system
10150                // image...  let's recover!
10151                pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails;
10152                // However...  if this package is part of a shared user, but it
10153                // doesn't match the signature of the shared user, let's fail.
10154                // What this means is that you can't change the signatures
10155                // associated with an overall shared user, which doesn't seem all
10156                // that unreasonable.
10157                if (signatureCheckPs.sharedUser != null) {
10158                    if (compareSignatures(
10159                            signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures,
10160                            pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) {
10161                        throw new PackageManagerException(
10162                                INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10163                                "Signature mismatch for shared user: "
10164                                        + pkgSetting.sharedUser);
10165                    }
10166                }
10167                // File a report about this.
10168                String msg = "System package " + pkg.packageName
10169                        + " signature changed; retaining data.";
10170                reportSettingsProblem(Log.WARN, msg);
10171            } catch (IllegalArgumentException e) {
10172
10173                // should never happen: certs matched when checking, but not when comparing
10174                // old to new for sharedUser
10175                throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10176                        "Signing certificates comparison made on incomparable signing details"
10177                        + " but somehow passed verifySignatures!");
10178            }
10179        }
10180
10181        if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
10182            // This package wants to adopt ownership of permissions from
10183            // another package.
10184            for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
10185                final String origName = pkg.mAdoptPermissions.get(i);
10186                final PackageSetting orig = mSettings.getPackageLPr(origName);
10187                if (orig != null) {
10188                    if (verifyPackageUpdateLPr(orig, pkg)) {
10189                        Slog.i(TAG, "Adopting permissions from " + origName + " to "
10190                                + pkg.packageName);
10191                        mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
10192                    }
10193                }
10194            }
10195        }
10196
10197        if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
10198            for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) {
10199                final String codePathString = changedAbiCodePath.get(i);
10200                try {
10201                    mInstaller.rmdex(codePathString,
10202                            getDexCodeInstructionSet(getPreferredInstructionSet()));
10203                } catch (InstallerException ignored) {
10204                }
10205            }
10206        }
10207
10208        if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10209            if (oldPkgSetting != null) {
10210                synchronized (mPackages) {
10211                    mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
10212                }
10213            }
10214        } else {
10215            final int userId = user == null ? 0 : user.getIdentifier();
10216            // Modify state for the given package setting
10217            commitPackageSettings(pkg, pkgSetting, user, scanFlags,
10218                    (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/);
10219            if (pkgSetting.getInstantApp(userId)) {
10220                mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
10221            }
10222        }
10223    }
10224
10225    /**
10226     * Returns the "real" name of the package.
10227     * <p>This may differ from the package's actual name if the application has already
10228     * been installed under one of this package's original names.
10229     */
10230    private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
10231            @Nullable String renamedPkgName) {
10232        if (isPackageRenamed(pkg, renamedPkgName)) {
10233            return pkg.mRealPackage;
10234        }
10235        return null;
10236    }
10237
10238    /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
10239    private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
10240            @Nullable String renamedPkgName) {
10241        return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
10242    }
10243
10244    /**
10245     * Returns the original package setting.
10246     * <p>A package can migrate its name during an update. In this scenario, a package
10247     * designates a set of names that it considers as one of its original names.
10248     * <p>An original package must be signed identically and it must have the same
10249     * shared user [if any].
10250     */
10251    @GuardedBy("mPackages")
10252    private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
10253            @Nullable String renamedPkgName) {
10254        if (!isPackageRenamed(pkg, renamedPkgName)) {
10255            return null;
10256        }
10257        for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
10258            final PackageSetting originalPs =
10259                    mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
10260            if (originalPs != null) {
10261                // the package is already installed under its original name...
10262                // but, should we use it?
10263                if (!verifyPackageUpdateLPr(originalPs, pkg)) {
10264                    // the new package is incompatible with the original
10265                    continue;
10266                } else if (originalPs.sharedUser != null) {
10267                    if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
10268                        // the shared user id is incompatible with the original
10269                        Slog.w(TAG, "Unable to migrate data from " + originalPs.name
10270                                + " to " + pkg.packageName + ": old uid "
10271                                + originalPs.sharedUser.name
10272                                + " differs from " + pkg.mSharedUserId);
10273                        continue;
10274                    }
10275                    // TODO: Add case when shared user id is added [b/28144775]
10276                } else {
10277                    if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
10278                            + pkg.packageName + " to old name " + originalPs.name);
10279                }
10280                return originalPs;
10281            }
10282        }
10283        return null;
10284    }
10285
10286    /**
10287     * Renames the package if it was installed under a different name.
10288     * <p>When we've already installed the package under an original name, update
10289     * the new package so we can continue to have the old name.
10290     */
10291    private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
10292            @NonNull String renamedPackageName) {
10293        if (pkg.mOriginalPackages == null
10294                || !pkg.mOriginalPackages.contains(renamedPackageName)
10295                || pkg.packageName.equals(renamedPackageName)) {
10296            return;
10297        }
10298        pkg.setPackageName(renamedPackageName);
10299    }
10300
10301    /**
10302     * Just scans the package without any side effects.
10303     * <p>Not entirely true at the moment. There is still one side effect -- this
10304     * method potentially modifies a live {@link PackageSetting} object representing
10305     * the package being scanned. This will be resolved in the future.
10306     *
10307     * @param request Information about the package to be scanned
10308     * @param isUnderFactoryTest Whether or not the device is under factory test
10309     * @param currentTime The current time, in millis
10310     * @return The results of the scan
10311     */
10312    @GuardedBy("mInstallLock")
10313    private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
10314            boolean isUnderFactoryTest, long currentTime)
10315                    throws PackageManagerException {
10316        final PackageParser.Package pkg = request.pkg;
10317        PackageSetting pkgSetting = request.pkgSetting;
10318        final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
10319        final PackageSetting originalPkgSetting = request.originalPkgSetting;
10320        final @ParseFlags int parseFlags = request.parseFlags;
10321        final @ScanFlags int scanFlags = request.scanFlags;
10322        final String realPkgName = request.realPkgName;
10323        final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
10324        final UserHandle user = request.user;
10325        final boolean isPlatformPackage = request.isPlatformPackage;
10326
10327        List<String> changedAbiCodePath = null;
10328
10329        if (DEBUG_PACKAGE_SCANNING) {
10330            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10331                Log.d(TAG, "Scanning package " + pkg.packageName);
10332        }
10333
10334        if (Build.IS_DEBUGGABLE &&
10335                pkg.isPrivileged() &&
10336                !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) {
10337            PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg);
10338        }
10339
10340        // Initialize package source and resource directories
10341        final File scanFile = new File(pkg.codePath);
10342        final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
10343        final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
10344
10345        // We keep references to the derived CPU Abis from settings in oder to reuse
10346        // them in the case where we're not upgrading or booting for the first time.
10347        String primaryCpuAbiFromSettings = null;
10348        String secondaryCpuAbiFromSettings = null;
10349        boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
10350
10351        if (!needToDeriveAbi) {
10352            if (pkgSetting != null) {
10353                primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
10354                secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
10355            } else {
10356                // Re-scanning a system package after uninstalling updates; need to derive ABI
10357                needToDeriveAbi = true;
10358            }
10359        }
10360
10361        if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
10362            PackageManagerService.reportSettingsProblem(Log.WARN,
10363                    "Package " + pkg.packageName + " shared user changed from "
10364                            + (pkgSetting.sharedUser != null
10365                            ? pkgSetting.sharedUser.name : "<nothing>")
10366                            + " to "
10367                            + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
10368                            + "; replacing with new");
10369            pkgSetting = null;
10370        }
10371
10372        String[] usesStaticLibraries = null;
10373        if (pkg.usesStaticLibraries != null) {
10374            usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
10375            pkg.usesStaticLibraries.toArray(usesStaticLibraries);
10376        }
10377        final boolean createNewPackage = (pkgSetting == null);
10378        if (createNewPackage) {
10379            final String parentPackageName = (pkg.parentPackage != null)
10380                    ? pkg.parentPackage.packageName : null;
10381            final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
10382            final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
10383            // REMOVE SharedUserSetting from method; update in a separate call
10384            pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
10385                    disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
10386                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
10387                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10388                    pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10389                    user, true /*allowInstall*/, instantApp, virtualPreload,
10390                    parentPackageName, pkg.getChildPackageNames(),
10391                    UserManagerService.getInstance(), usesStaticLibraries,
10392                    pkg.usesStaticLibrariesVersions);
10393        } else {
10394            // REMOVE SharedUserSetting from method; update in a separate call.
10395            //
10396            // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
10397            // secondaryCpuAbi are not known at this point so we always update them
10398            // to null here, only to reset them at a later point.
10399            Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
10400                    destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
10401                    pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
10402                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
10403                    pkg.getChildPackageNames(), UserManagerService.getInstance(),
10404                    usesStaticLibraries, pkg.usesStaticLibrariesVersions);
10405        }
10406        if (createNewPackage && originalPkgSetting != null) {
10407            // This is the initial transition from the original package, so,
10408            // fix up the new package's name now. We must do this after looking
10409            // up the package under its new name, so getPackageLP takes care of
10410            // fiddling things correctly.
10411            pkg.setPackageName(originalPkgSetting.name);
10412
10413            // File a report about this.
10414            String msg = "New package " + pkgSetting.realName
10415                    + " renamed to replace old package " + pkgSetting.name;
10416            reportSettingsProblem(Log.WARN, msg);
10417        }
10418
10419        if (disabledPkgSetting != null) {
10420            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10421        }
10422
10423        // Apps which share a sharedUserId must be placed in the same selinux domain. If this
10424        // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
10425        // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
10426        // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
10427        // least restrictive selinux domain.
10428        // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
10429        // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
10430        // ensures that all packages continue to run in the same selinux domain.
10431        final int targetSdkVersion =
10432            ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
10433            sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
10434        // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
10435        // They currently can be if the sharedUser apps are signed with the platform key.
10436        final boolean isPrivileged = (sharedUserSetting != null) ?
10437            sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
10438
10439        pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
10440                pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
10441
10442        pkg.mExtras = pkgSetting;
10443        pkg.applicationInfo.processName = fixProcessName(
10444                pkg.applicationInfo.packageName,
10445                pkg.applicationInfo.processName);
10446
10447        if (!isPlatformPackage) {
10448            // Get all of our default paths setup
10449            pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
10450        }
10451
10452        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
10453
10454        if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
10455            if (needToDeriveAbi) {
10456                Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
10457                final boolean extractNativeLibs = !pkg.isLibrary();
10458                derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
10459                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10460
10461                // Some system apps still use directory structure for native libraries
10462                // in which case we might end up not detecting abi solely based on apk
10463                // structure. Try to detect abi based on directory structure.
10464                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
10465                        pkg.applicationInfo.primaryCpuAbi == null) {
10466                    setBundledAppAbisAndRoots(pkg, pkgSetting);
10467                    setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10468                }
10469            } else {
10470                // This is not a first boot or an upgrade, don't bother deriving the
10471                // ABI during the scan. Instead, trust the value that was stored in the
10472                // package setting.
10473                pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
10474                pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
10475
10476                setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10477
10478                if (DEBUG_ABI_SELECTION) {
10479                    Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
10480                            pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
10481                            pkg.applicationInfo.secondaryCpuAbi);
10482                }
10483            }
10484        } else {
10485            if ((scanFlags & SCAN_MOVE) != 0) {
10486                // We haven't run dex-opt for this move (since we've moved the compiled output too)
10487                // but we already have this packages package info in the PackageSetting. We just
10488                // use that and derive the native library path based on the new codepath.
10489                pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
10490                pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
10491            }
10492
10493            // Set native library paths again. For moves, the path will be updated based on the
10494            // ABIs we've determined above. For non-moves, the path will be updated based on the
10495            // ABIs we determined during compilation, but the path will depend on the final
10496            // package path (after the rename away from the stage path).
10497            setNativeLibraryPaths(pkg, sAppLib32InstallDir);
10498        }
10499
10500        // This is a special case for the "system" package, where the ABI is
10501        // dictated by the zygote configuration (and init.rc). We should keep track
10502        // of this ABI so that we can deal with "normal" applications that run under
10503        // the same UID correctly.
10504        if (isPlatformPackage) {
10505            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
10506                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
10507        }
10508
10509        // If there's a mismatch between the abi-override in the package setting
10510        // and the abiOverride specified for the install. Warn about this because we
10511        // would've already compiled the app without taking the package setting into
10512        // account.
10513        if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
10514            if (cpuAbiOverride == null && pkg.packageName != null) {
10515                Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
10516                        " for package " + pkg.packageName);
10517            }
10518        }
10519
10520        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
10521        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
10522        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
10523
10524        // Copy the derived override back to the parsed package, so that we can
10525        // update the package settings accordingly.
10526        pkg.cpuAbiOverride = cpuAbiOverride;
10527
10528        if (DEBUG_ABI_SELECTION) {
10529            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
10530                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
10531                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
10532        }
10533
10534        // Push the derived path down into PackageSettings so we know what to
10535        // clean up at uninstall time.
10536        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
10537
10538        if (DEBUG_ABI_SELECTION) {
10539            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
10540                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
10541                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
10542        }
10543
10544        if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
10545            // We don't do this here during boot because we can do it all
10546            // at once after scanning all existing packages.
10547            //
10548            // We also do this *before* we perform dexopt on this package, so that
10549            // we can avoid redundant dexopts, and also to make sure we've got the
10550            // code and package path correct.
10551            changedAbiCodePath =
10552                    adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
10553        }
10554
10555        if (isUnderFactoryTest && pkg.requestedPermissions.contains(
10556                android.Manifest.permission.FACTORY_TEST)) {
10557            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
10558        }
10559
10560        if (isSystemApp(pkg)) {
10561            pkgSetting.isOrphaned = true;
10562        }
10563
10564        // Take care of first install / last update times.
10565        final long scanFileTime = getLastModifiedTime(pkg);
10566        if (currentTime != 0) {
10567            if (pkgSetting.firstInstallTime == 0) {
10568                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
10569            } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
10570                pkgSetting.lastUpdateTime = currentTime;
10571            }
10572        } else if (pkgSetting.firstInstallTime == 0) {
10573            // We need *something*.  Take time time stamp of the file.
10574            pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
10575        } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
10576            if (scanFileTime != pkgSetting.timeStamp) {
10577                // A package on the system image has changed; consider this
10578                // to be an update.
10579                pkgSetting.lastUpdateTime = scanFileTime;
10580            }
10581        }
10582        pkgSetting.setTimeStamp(scanFileTime);
10583
10584        pkgSetting.pkg = pkg;
10585        pkgSetting.pkgFlags = pkg.applicationInfo.flags;
10586        if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
10587            pkgSetting.versionCode = pkg.getLongVersionCode();
10588        }
10589        // Update volume if needed
10590        final String volumeUuid = pkg.applicationInfo.volumeUuid;
10591        if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
10592            Slog.i(PackageManagerService.TAG,
10593                    "Update" + (pkgSetting.isSystem() ? " system" : "")
10594                    + " package " + pkg.packageName
10595                    + " volume from " + pkgSetting.volumeUuid
10596                    + " to " + volumeUuid);
10597            pkgSetting.volumeUuid = volumeUuid;
10598        }
10599
10600        return new ScanResult(true, pkgSetting, changedAbiCodePath);
10601    }
10602
10603    /**
10604     * Returns {@code true} if the given file contains code. Otherwise {@code false}.
10605     */
10606    private static boolean apkHasCode(String fileName) {
10607        StrictJarFile jarFile = null;
10608        try {
10609            jarFile = new StrictJarFile(fileName,
10610                    false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
10611            return jarFile.findEntry("classes.dex") != null;
10612        } catch (IOException ignore) {
10613        } finally {
10614            try {
10615                if (jarFile != null) {
10616                    jarFile.close();
10617                }
10618            } catch (IOException ignore) {}
10619        }
10620        return false;
10621    }
10622
10623    /**
10624     * Enforces code policy for the package. This ensures that if an APK has
10625     * declared hasCode="true" in its manifest that the APK actually contains
10626     * code.
10627     *
10628     * @throws PackageManagerException If bytecode could not be found when it should exist
10629     */
10630    private static void assertCodePolicy(PackageParser.Package pkg)
10631            throws PackageManagerException {
10632        final boolean shouldHaveCode =
10633                (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
10634        if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
10635            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10636                    "Package " + pkg.baseCodePath + " code is missing");
10637        }
10638
10639        if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
10640            for (int i = 0; i < pkg.splitCodePaths.length; i++) {
10641                final boolean splitShouldHaveCode =
10642                        (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
10643                if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
10644                    throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10645                            "Package " + pkg.splitCodePaths[i] + " code is missing");
10646                }
10647            }
10648        }
10649    }
10650
10651    /**
10652     * Applies policy to the parsed package based upon the given policy flags.
10653     * Ensures the package is in a good state.
10654     * <p>
10655     * Implementation detail: This method must NOT have any side effect. It would
10656     * ideally be static, but, it requires locks to read system state.
10657     */
10658    private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10659            final @ScanFlags int scanFlags) {
10660        if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
10661            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
10662            if (pkg.applicationInfo.isDirectBootAware()) {
10663                // we're direct boot aware; set for all components
10664                for (PackageParser.Service s : pkg.services) {
10665                    s.info.encryptionAware = s.info.directBootAware = true;
10666                }
10667                for (PackageParser.Provider p : pkg.providers) {
10668                    p.info.encryptionAware = p.info.directBootAware = true;
10669                }
10670                for (PackageParser.Activity a : pkg.activities) {
10671                    a.info.encryptionAware = a.info.directBootAware = true;
10672                }
10673                for (PackageParser.Activity r : pkg.receivers) {
10674                    r.info.encryptionAware = r.info.directBootAware = true;
10675                }
10676            }
10677            if (compressedFileExists(pkg.codePath)) {
10678                pkg.isStub = true;
10679            }
10680        } else {
10681            // non system apps can't be flagged as core
10682            pkg.coreApp = false;
10683            // clear flags not applicable to regular apps
10684            pkg.applicationInfo.flags &=
10685                    ~ApplicationInfo.FLAG_PERSISTENT;
10686            pkg.applicationInfo.privateFlags &=
10687                    ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
10688            pkg.applicationInfo.privateFlags &=
10689                    ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
10690            // cap permission priorities
10691            if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
10692                for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
10693                    pkg.permissionGroups.get(i).info.priority = 0;
10694                }
10695            }
10696        }
10697        if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10698            // clear protected broadcasts
10699            pkg.protectedBroadcasts = null;
10700            // ignore export request for single user receivers
10701            if (pkg.receivers != null) {
10702                for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
10703                    final PackageParser.Activity receiver = pkg.receivers.get(i);
10704                    if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
10705                        receiver.info.exported = false;
10706                    }
10707                }
10708            }
10709            // ignore export request for single user services
10710            if (pkg.services != null) {
10711                for (int i = pkg.services.size() - 1; i >= 0; --i) {
10712                    final PackageParser.Service service = pkg.services.get(i);
10713                    if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
10714                        service.info.exported = false;
10715                    }
10716                }
10717            }
10718            // ignore export request for single user providers
10719            if (pkg.providers != null) {
10720                for (int i = pkg.providers.size() - 1; i >= 0; --i) {
10721                    final PackageParser.Provider provider = pkg.providers.get(i);
10722                    if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
10723                        provider.info.exported = false;
10724                    }
10725                }
10726            }
10727        }
10728
10729        if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
10730            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
10731        }
10732
10733        if ((scanFlags & SCAN_AS_OEM) != 0) {
10734            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
10735        }
10736
10737        if ((scanFlags & SCAN_AS_VENDOR) != 0) {
10738            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
10739        }
10740
10741        if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
10742            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
10743        }
10744
10745        if (!isSystemApp(pkg)) {
10746            // Only system apps can use these features.
10747            pkg.mOriginalPackages = null;
10748            pkg.mRealPackage = null;
10749            pkg.mAdoptPermissions = null;
10750        }
10751    }
10752
10753    private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
10754            throws PackageManagerException {
10755        if (object == null) {
10756            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
10757        }
10758        return object;
10759    }
10760
10761    /**
10762     * Asserts the parsed package is valid according to the given policy. If the
10763     * package is invalid, for whatever reason, throws {@link PackageManagerException}.
10764     * <p>
10765     * Implementation detail: This method must NOT have any side effects. It would
10766     * ideally be static, but, it requires locks to read system state.
10767     *
10768     * @throws PackageManagerException If the package fails any of the validation checks
10769     */
10770    private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
10771            final @ScanFlags int scanFlags)
10772                    throws PackageManagerException {
10773        if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
10774            assertCodePolicy(pkg);
10775        }
10776
10777        if (pkg.applicationInfo.getCodePath() == null ||
10778                pkg.applicationInfo.getResourcePath() == null) {
10779            // Bail out. The resource and code paths haven't been set.
10780            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
10781                    "Code and resource paths haven't been set correctly");
10782        }
10783
10784        // Make sure we're not adding any bogus keyset info
10785        final KeySetManagerService ksms = mSettings.mKeySetManagerService;
10786        ksms.assertScannedPackageValid(pkg);
10787
10788        synchronized (mPackages) {
10789            // The special "android" package can only be defined once
10790            if (pkg.packageName.equals("android")) {
10791                if (mAndroidApplication != null) {
10792                    Slog.w(TAG, "*************************************************");
10793                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
10794                    Slog.w(TAG, " codePath=" + pkg.codePath);
10795                    Slog.w(TAG, "*************************************************");
10796                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10797                            "Core android package being redefined.  Skipping.");
10798                }
10799            }
10800
10801            // A package name must be unique; don't allow duplicates
10802            if (mPackages.containsKey(pkg.packageName)) {
10803                throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
10804                        "Application package " + pkg.packageName
10805                        + " already installed.  Skipping duplicate.");
10806            }
10807
10808            if (pkg.applicationInfo.isStaticSharedLibrary()) {
10809                // Static libs have a synthetic package name containing the version
10810                // but we still want the base name to be unique.
10811                if (mPackages.containsKey(pkg.manifestPackageName)) {
10812                    throw new PackageManagerException(
10813                            "Duplicate static shared lib provider package");
10814                }
10815
10816                // Static shared libraries should have at least O target SDK
10817                if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
10818                    throw new PackageManagerException(
10819                            "Packages declaring static-shared libs must target O SDK or higher");
10820                }
10821
10822                // Package declaring static a shared lib cannot be instant apps
10823                if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
10824                    throw new PackageManagerException(
10825                            "Packages declaring static-shared libs cannot be instant apps");
10826                }
10827
10828                // Package declaring static a shared lib cannot be renamed since the package
10829                // name is synthetic and apps can't code around package manager internals.
10830                if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
10831                    throw new PackageManagerException(
10832                            "Packages declaring static-shared libs cannot be renamed");
10833                }
10834
10835                // Package declaring static a shared lib cannot declare child packages
10836                if (!ArrayUtils.isEmpty(pkg.childPackages)) {
10837                    throw new PackageManagerException(
10838                            "Packages declaring static-shared libs cannot have child packages");
10839                }
10840
10841                // Package declaring static a shared lib cannot declare dynamic libs
10842                if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
10843                    throw new PackageManagerException(
10844                            "Packages declaring static-shared libs cannot declare dynamic libs");
10845                }
10846
10847                // Package declaring static a shared lib cannot declare shared users
10848                if (pkg.mSharedUserId != null) {
10849                    throw new PackageManagerException(
10850                            "Packages declaring static-shared libs cannot declare shared users");
10851                }
10852
10853                // Static shared libs cannot declare activities
10854                if (!pkg.activities.isEmpty()) {
10855                    throw new PackageManagerException(
10856                            "Static shared libs cannot declare activities");
10857                }
10858
10859                // Static shared libs cannot declare services
10860                if (!pkg.services.isEmpty()) {
10861                    throw new PackageManagerException(
10862                            "Static shared libs cannot declare services");
10863                }
10864
10865                // Static shared libs cannot declare providers
10866                if (!pkg.providers.isEmpty()) {
10867                    throw new PackageManagerException(
10868                            "Static shared libs cannot declare content providers");
10869                }
10870
10871                // Static shared libs cannot declare receivers
10872                if (!pkg.receivers.isEmpty()) {
10873                    throw new PackageManagerException(
10874                            "Static shared libs cannot declare broadcast receivers");
10875                }
10876
10877                // Static shared libs cannot declare permission groups
10878                if (!pkg.permissionGroups.isEmpty()) {
10879                    throw new PackageManagerException(
10880                            "Static shared libs cannot declare permission groups");
10881                }
10882
10883                // Static shared libs cannot declare permissions
10884                if (!pkg.permissions.isEmpty()) {
10885                    throw new PackageManagerException(
10886                            "Static shared libs cannot declare permissions");
10887                }
10888
10889                // Static shared libs cannot declare protected broadcasts
10890                if (pkg.protectedBroadcasts != null) {
10891                    throw new PackageManagerException(
10892                            "Static shared libs cannot declare protected broadcasts");
10893                }
10894
10895                // Static shared libs cannot be overlay targets
10896                if (pkg.mOverlayTarget != null) {
10897                    throw new PackageManagerException(
10898                            "Static shared libs cannot be overlay targets");
10899                }
10900
10901                // The version codes must be ordered as lib versions
10902                long minVersionCode = Long.MIN_VALUE;
10903                long maxVersionCode = Long.MAX_VALUE;
10904
10905                LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(
10906                        pkg.staticSharedLibName);
10907                if (versionedLib != null) {
10908                    final int versionCount = versionedLib.size();
10909                    for (int i = 0; i < versionCount; i++) {
10910                        SharedLibraryInfo libInfo = versionedLib.valueAt(i).info;
10911                        final long libVersionCode = libInfo.getDeclaringPackage()
10912                                .getLongVersionCode();
10913                        if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
10914                            minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
10915                        } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
10916                            maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
10917                        } else {
10918                            minVersionCode = maxVersionCode = libVersionCode;
10919                            break;
10920                        }
10921                    }
10922                }
10923                if (pkg.getLongVersionCode() < minVersionCode
10924                        || pkg.getLongVersionCode() > maxVersionCode) {
10925                    throw new PackageManagerException("Static shared"
10926                            + " lib version codes must be ordered as lib versions");
10927                }
10928            }
10929
10930            // Only privileged apps and updated privileged apps can add child packages.
10931            if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
10932                if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
10933                    throw new PackageManagerException("Only privileged apps can add child "
10934                            + "packages. Ignoring package " + pkg.packageName);
10935                }
10936                final int childCount = pkg.childPackages.size();
10937                for (int i = 0; i < childCount; i++) {
10938                    PackageParser.Package childPkg = pkg.childPackages.get(i);
10939                    if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
10940                            childPkg.packageName)) {
10941                        throw new PackageManagerException("Can't override child of "
10942                                + "another disabled app. Ignoring package " + pkg.packageName);
10943                    }
10944                }
10945            }
10946
10947            // If we're only installing presumed-existing packages, require that the
10948            // scanned APK is both already known and at the path previously established
10949            // for it.  Previously unknown packages we pick up normally, but if we have an
10950            // a priori expectation about this package's install presence, enforce it.
10951            // With a singular exception for new system packages. When an OTA contains
10952            // a new system package, we allow the codepath to change from a system location
10953            // to the user-installed location. If we don't allow this change, any newer,
10954            // user-installed version of the application will be ignored.
10955            if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
10956                if (mExpectingBetter.containsKey(pkg.packageName)) {
10957                    logCriticalInfo(Log.WARN,
10958                            "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
10959                } else {
10960                    PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
10961                    if (known != null) {
10962                        if (DEBUG_PACKAGE_SCANNING) {
10963                            Log.d(TAG, "Examining " + pkg.codePath
10964                                    + " and requiring known paths " + known.codePathString
10965                                    + " & " + known.resourcePathString);
10966                        }
10967                        if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
10968                                || !pkg.applicationInfo.getResourcePath().equals(
10969                                        known.resourcePathString)) {
10970                            throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
10971                                    "Application package " + pkg.packageName
10972                                    + " found at " + pkg.applicationInfo.getCodePath()
10973                                    + " but expected at " + known.codePathString
10974                                    + "; ignoring.");
10975                        }
10976                    } else {
10977                        throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10978                                "Application package " + pkg.packageName
10979                                + " not found; ignoring.");
10980                    }
10981                }
10982            }
10983
10984            // Verify that this new package doesn't have any content providers
10985            // that conflict with existing packages.  Only do this if the
10986            // package isn't already installed, since we don't want to break
10987            // things that are installed.
10988            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
10989                final int N = pkg.providers.size();
10990                int i;
10991                for (i=0; i<N; i++) {
10992                    PackageParser.Provider p = pkg.providers.get(i);
10993                    if (p.info.authority != null) {
10994                        String names[] = p.info.authority.split(";");
10995                        for (int j = 0; j < names.length; j++) {
10996                            if (mProvidersByAuthority.containsKey(names[j])) {
10997                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
10998                                final String otherPackageName =
10999                                        ((other != null && other.getComponentName() != null) ?
11000                                                other.getComponentName().getPackageName() : "?");
11001                                throw new PackageManagerException(
11002                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
11003                                        "Can't install because provider name " + names[j]
11004                                                + " (in package " + pkg.applicationInfo.packageName
11005                                                + ") is already used by " + otherPackageName);
11006                            }
11007                        }
11008                    }
11009                }
11010            }
11011
11012            // Verify that packages sharing a user with a privileged app are marked as privileged.
11013            if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11014                SharedUserSetting sharedUserSetting = null;
11015                try {
11016                    sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11017                } catch (PackageManagerException ignore) {}
11018                if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11019                    // Exempt SharedUsers signed with the platform key.
11020                    PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11021                    if ((platformPkgSetting.signatures.mSigningDetails
11022                            != PackageParser.SigningDetails.UNKNOWN)
11023                            && (compareSignatures(
11024                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11025                                    pkg.mSigningDetails.signatures)
11026                                            != PackageManager.SIGNATURE_MATCH)) {
11027                        throw new PackageManagerException("Apps that share a user with a " +
11028                                "privileged app must themselves be marked as privileged. " +
11029                                pkg.packageName + " shares privileged user " +
11030                                pkg.mSharedUserId + ".");
11031                    }
11032                }
11033            }
11034
11035            // Apply policies specific for runtime resource overlays (RROs).
11036            if (pkg.mOverlayTarget != null) {
11037                // System overlays have some restrictions on their use of the 'static' state.
11038                if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11039                    // We are scanning a system overlay. This can be the first scan of the
11040                    // system/vendor/oem partition, or an update to the system overlay.
11041                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11042                        // This must be an update to a system overlay.
11043                        final PackageSetting previousPkg = assertNotNull(
11044                                mSettings.getPackageLPr(pkg.packageName),
11045                                "previous package state not present");
11046
11047                        // Static overlays cannot be updated.
11048                        if (previousPkg.pkg.mOverlayIsStatic) {
11049                            throw new PackageManagerException("Overlay " + pkg.packageName +
11050                                    " is static and cannot be upgraded.");
11051                        // Non-static overlays cannot be converted to static overlays.
11052                        } else if (pkg.mOverlayIsStatic) {
11053                            throw new PackageManagerException("Overlay " + pkg.packageName +
11054                                    " cannot be upgraded into a static overlay.");
11055                        }
11056                    }
11057                } else {
11058                    // The overlay is a non-system overlay. Non-system overlays cannot be static.
11059                    if (pkg.mOverlayIsStatic) {
11060                        throw new PackageManagerException("Overlay " + pkg.packageName +
11061                                " is static but not pre-installed.");
11062                    }
11063
11064                    // The only case where we allow installation of a non-system overlay is when
11065                    // its signature is signed with the platform certificate.
11066                    PackageSetting platformPkgSetting = mSettings.getPackageLPr("android");
11067                    if ((platformPkgSetting.signatures.mSigningDetails
11068                            != PackageParser.SigningDetails.UNKNOWN)
11069                            && (compareSignatures(
11070                                    platformPkgSetting.signatures.mSigningDetails.signatures,
11071                                    pkg.mSigningDetails.signatures)
11072                                            != PackageManager.SIGNATURE_MATCH)) {
11073                        throw new PackageManagerException("Overlay " + pkg.packageName +
11074                                " must be signed with the platform certificate.");
11075                    }
11076                }
11077            }
11078        }
11079    }
11080
11081    private boolean addSharedLibraryLPw(String path, String apk, String name, long version,
11082            int type, String declaringPackageName, long declaringVersionCode) {
11083        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11084        if (versionedLib == null) {
11085            versionedLib = new LongSparseArray<>();
11086            mSharedLibraries.put(name, versionedLib);
11087            if (type == SharedLibraryInfo.TYPE_STATIC) {
11088                mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
11089            }
11090        } else if (versionedLib.indexOfKey(version) >= 0) {
11091            return false;
11092        }
11093        SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name,
11094                version, type, declaringPackageName, declaringVersionCode);
11095        versionedLib.put(version, libEntry);
11096        return true;
11097    }
11098
11099    private boolean removeSharedLibraryLPw(String name, long version) {
11100        LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name);
11101        if (versionedLib == null) {
11102            return false;
11103        }
11104        final int libIdx = versionedLib.indexOfKey(version);
11105        if (libIdx < 0) {
11106            return false;
11107        }
11108        SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx);
11109        versionedLib.remove(version);
11110        if (versionedLib.size() <= 0) {
11111            mSharedLibraries.remove(name);
11112            if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) {
11113                mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage()
11114                        .getPackageName());
11115            }
11116        }
11117        return true;
11118    }
11119
11120    /**
11121     * Adds a scanned package to the system. When this method is finished, the package will
11122     * be available for query, resolution, etc...
11123     */
11124    private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting,
11125            UserHandle user, final @ScanFlags int scanFlags, boolean chatty) {
11126        final String pkgName = pkg.packageName;
11127        if (mCustomResolverComponentName != null &&
11128                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
11129            setUpCustomResolverActivity(pkg);
11130        }
11131
11132        if (pkg.packageName.equals("android")) {
11133            synchronized (mPackages) {
11134                if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
11135                    // Set up information for our fall-back user intent resolution activity.
11136                    mPlatformPackage = pkg;
11137                    pkg.mVersionCode = mSdkVersion;
11138                    pkg.mVersionCodeMajor = 0;
11139                    mAndroidApplication = pkg.applicationInfo;
11140                    if (!mResolverReplaced) {
11141                        mResolveActivity.applicationInfo = mAndroidApplication;
11142                        mResolveActivity.name = ResolverActivity.class.getName();
11143                        mResolveActivity.packageName = mAndroidApplication.packageName;
11144                        mResolveActivity.processName = "system:ui";
11145                        mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11146                        mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
11147                        mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
11148                        mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
11149                        mResolveActivity.exported = true;
11150                        mResolveActivity.enabled = true;
11151                        mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
11152                        mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
11153                                | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
11154                                | ActivityInfo.CONFIG_SCREEN_LAYOUT
11155                                | ActivityInfo.CONFIG_ORIENTATION
11156                                | ActivityInfo.CONFIG_KEYBOARD
11157                                | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
11158                        mResolveInfo.activityInfo = mResolveActivity;
11159                        mResolveInfo.priority = 0;
11160                        mResolveInfo.preferredOrder = 0;
11161                        mResolveInfo.match = 0;
11162                        mResolveComponentName = new ComponentName(
11163                                mAndroidApplication.packageName, mResolveActivity.name);
11164                    }
11165                }
11166            }
11167        }
11168
11169        ArrayList<PackageParser.Package> clientLibPkgs = null;
11170        // writer
11171        synchronized (mPackages) {
11172            boolean hasStaticSharedLibs = false;
11173
11174            // Any app can add new static shared libraries
11175            if (pkg.staticSharedLibName != null) {
11176                // Static shared libs don't allow renaming as they have synthetic package
11177                // names to allow install of multiple versions, so use name from manifest.
11178                if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName,
11179                        pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC,
11180                        pkg.manifestPackageName, pkg.getLongVersionCode())) {
11181                    hasStaticSharedLibs = true;
11182                } else {
11183                    Slog.w(TAG, "Package " + pkg.packageName + " library "
11184                                + pkg.staticSharedLibName + " already exists; skipping");
11185                }
11186                // Static shared libs cannot be updated once installed since they
11187                // use synthetic package name which includes the version code, so
11188                // not need to update other packages's shared lib dependencies.
11189            }
11190
11191            if (!hasStaticSharedLibs
11192                    && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
11193                // Only system apps can add new dynamic shared libraries.
11194                if (pkg.libraryNames != null) {
11195                    for (int i = 0; i < pkg.libraryNames.size(); i++) {
11196                        String name = pkg.libraryNames.get(i);
11197                        boolean allowed = false;
11198                        if (pkg.isUpdatedSystemApp()) {
11199                            // New library entries can only be added through the
11200                            // system image.  This is important to get rid of a lot
11201                            // of nasty edge cases: for example if we allowed a non-
11202                            // system update of the app to add a library, then uninstalling
11203                            // the update would make the library go away, and assumptions
11204                            // we made such as through app install filtering would now
11205                            // have allowed apps on the device which aren't compatible
11206                            // with it.  Better to just have the restriction here, be
11207                            // conservative, and create many fewer cases that can negatively
11208                            // impact the user experience.
11209                            final PackageSetting sysPs = mSettings
11210                                    .getDisabledSystemPkgLPr(pkg.packageName);
11211                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
11212                                for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) {
11213                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
11214                                        allowed = true;
11215                                        break;
11216                                    }
11217                                }
11218                            }
11219                        } else {
11220                            allowed = true;
11221                        }
11222                        if (allowed) {
11223                            if (!addSharedLibraryLPw(null, pkg.packageName, name,
11224                                    SharedLibraryInfo.VERSION_UNDEFINED,
11225                                    SharedLibraryInfo.TYPE_DYNAMIC,
11226                                    pkg.packageName, pkg.getLongVersionCode())) {
11227                                Slog.w(TAG, "Package " + pkg.packageName + " library "
11228                                        + name + " already exists; skipping");
11229                            }
11230                        } else {
11231                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
11232                                    + name + " that is not declared on system image; skipping");
11233                        }
11234                    }
11235
11236                    if ((scanFlags & SCAN_BOOTING) == 0) {
11237                        // If we are not booting, we need to update any applications
11238                        // that are clients of our shared library.  If we are booting,
11239                        // this will all be done once the scan is complete.
11240                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
11241                    }
11242                }
11243            }
11244        }
11245
11246        if ((scanFlags & SCAN_BOOTING) != 0) {
11247            // No apps can run during boot scan, so they don't need to be frozen
11248        } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
11249            // Caller asked to not kill app, so it's probably not frozen
11250        } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
11251            // Caller asked us to ignore frozen check for some reason; they
11252            // probably didn't know the package name
11253        } else {
11254            // We're doing major surgery on this package, so it better be frozen
11255            // right now to keep it from launching
11256            checkPackageFrozen(pkgName);
11257        }
11258
11259        // Also need to kill any apps that are dependent on the library.
11260        if (clientLibPkgs != null) {
11261            for (int i=0; i<clientLibPkgs.size(); i++) {
11262                PackageParser.Package clientPkg = clientLibPkgs.get(i);
11263                killApplication(clientPkg.applicationInfo.packageName,
11264                        clientPkg.applicationInfo.uid, "update lib");
11265            }
11266        }
11267
11268        // writer
11269        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
11270
11271        synchronized (mPackages) {
11272            // We don't expect installation to fail beyond this point
11273
11274            // Add the new setting to mSettings
11275            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
11276            // Add the new setting to mPackages
11277            mPackages.put(pkg.applicationInfo.packageName, pkg);
11278            // Make sure we don't accidentally delete its data.
11279            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
11280            while (iter.hasNext()) {
11281                PackageCleanItem item = iter.next();
11282                if (pkgName.equals(item.packageName)) {
11283                    iter.remove();
11284                }
11285            }
11286
11287            // Add the package's KeySets to the global KeySetManagerService
11288            KeySetManagerService ksms = mSettings.mKeySetManagerService;
11289            ksms.addScannedPackageLPw(pkg);
11290
11291            int N = pkg.providers.size();
11292            StringBuilder r = null;
11293            int i;
11294            for (i=0; i<N; i++) {
11295                PackageParser.Provider p = pkg.providers.get(i);
11296                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
11297                        p.info.processName);
11298                mProviders.addProvider(p);
11299                p.syncable = p.info.isSyncable;
11300                if (p.info.authority != null) {
11301                    String names[] = p.info.authority.split(";");
11302                    p.info.authority = null;
11303                    for (int j = 0; j < names.length; j++) {
11304                        if (j == 1 && p.syncable) {
11305                            // We only want the first authority for a provider to possibly be
11306                            // syncable, so if we already added this provider using a different
11307                            // authority clear the syncable flag. We copy the provider before
11308                            // changing it because the mProviders object contains a reference
11309                            // to a provider that we don't want to change.
11310                            // Only do this for the second authority since the resulting provider
11311                            // object can be the same for all future authorities for this provider.
11312                            p = new PackageParser.Provider(p);
11313                            p.syncable = false;
11314                        }
11315                        if (!mProvidersByAuthority.containsKey(names[j])) {
11316                            mProvidersByAuthority.put(names[j], p);
11317                            if (p.info.authority == null) {
11318                                p.info.authority = names[j];
11319                            } else {
11320                                p.info.authority = p.info.authority + ";" + names[j];
11321                            }
11322                            if (DEBUG_PACKAGE_SCANNING) {
11323                                if (chatty)
11324                                    Log.d(TAG, "Registered content provider: " + names[j]
11325                                            + ", className = " + p.info.name + ", isSyncable = "
11326                                            + p.info.isSyncable);
11327                            }
11328                        } else {
11329                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
11330                            Slog.w(TAG, "Skipping provider name " + names[j] +
11331                                    " (in package " + pkg.applicationInfo.packageName +
11332                                    "): name already used by "
11333                                    + ((other != null && other.getComponentName() != null)
11334                                            ? other.getComponentName().getPackageName() : "?"));
11335                        }
11336                    }
11337                }
11338                if (chatty) {
11339                    if (r == null) {
11340                        r = new StringBuilder(256);
11341                    } else {
11342                        r.append(' ');
11343                    }
11344                    r.append(p.info.name);
11345                }
11346            }
11347            if (r != null) {
11348                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
11349            }
11350
11351            N = pkg.services.size();
11352            r = null;
11353            for (i=0; i<N; i++) {
11354                PackageParser.Service s = pkg.services.get(i);
11355                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
11356                        s.info.processName);
11357                mServices.addService(s);
11358                if (chatty) {
11359                    if (r == null) {
11360                        r = new StringBuilder(256);
11361                    } else {
11362                        r.append(' ');
11363                    }
11364                    r.append(s.info.name);
11365                }
11366            }
11367            if (r != null) {
11368                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
11369            }
11370
11371            N = pkg.receivers.size();
11372            r = null;
11373            for (i=0; i<N; i++) {
11374                PackageParser.Activity a = pkg.receivers.get(i);
11375                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11376                        a.info.processName);
11377                mReceivers.addActivity(a, "receiver");
11378                if (chatty) {
11379                    if (r == null) {
11380                        r = new StringBuilder(256);
11381                    } else {
11382                        r.append(' ');
11383                    }
11384                    r.append(a.info.name);
11385                }
11386            }
11387            if (r != null) {
11388                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
11389            }
11390
11391            N = pkg.activities.size();
11392            r = null;
11393            for (i=0; i<N; i++) {
11394                PackageParser.Activity a = pkg.activities.get(i);
11395                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
11396                        a.info.processName);
11397                mActivities.addActivity(a, "activity");
11398                if (chatty) {
11399                    if (r == null) {
11400                        r = new StringBuilder(256);
11401                    } else {
11402                        r.append(' ');
11403                    }
11404                    r.append(a.info.name);
11405                }
11406            }
11407            if (r != null) {
11408                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
11409            }
11410
11411            // Don't allow ephemeral applications to define new permissions groups.
11412            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11413                Slog.w(TAG, "Permission groups from package " + pkg.packageName
11414                        + " ignored: instant apps cannot define new permission groups.");
11415            } else {
11416                mPermissionManager.addAllPermissionGroups(pkg, chatty);
11417            }
11418
11419            // Don't allow ephemeral applications to define new permissions.
11420            if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11421                Slog.w(TAG, "Permissions from package " + pkg.packageName
11422                        + " ignored: instant apps cannot define new permissions.");
11423            } else {
11424                mPermissionManager.addAllPermissions(pkg, chatty);
11425            }
11426
11427            N = pkg.instrumentation.size();
11428            r = null;
11429            for (i=0; i<N; i++) {
11430                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
11431                a.info.packageName = pkg.applicationInfo.packageName;
11432                a.info.sourceDir = pkg.applicationInfo.sourceDir;
11433                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
11434                a.info.splitNames = pkg.splitNames;
11435                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
11436                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
11437                a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
11438                a.info.dataDir = pkg.applicationInfo.dataDir;
11439                a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
11440                a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
11441                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
11442                a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
11443                mInstrumentation.put(a.getComponentName(), a);
11444                if (chatty) {
11445                    if (r == null) {
11446                        r = new StringBuilder(256);
11447                    } else {
11448                        r.append(' ');
11449                    }
11450                    r.append(a.info.name);
11451                }
11452            }
11453            if (r != null) {
11454                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
11455            }
11456
11457            if (pkg.protectedBroadcasts != null) {
11458                N = pkg.protectedBroadcasts.size();
11459                synchronized (mProtectedBroadcasts) {
11460                    for (i = 0; i < N; i++) {
11461                        mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
11462                    }
11463                }
11464            }
11465        }
11466
11467        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11468    }
11469
11470    /**
11471     * Derive the ABI of a non-system package located at {@code scanFile}. This information
11472     * is derived purely on the basis of the contents of {@code scanFile} and
11473     * {@code cpuAbiOverride}.
11474     *
11475     * If {@code extractLibs} is true, native libraries are extracted from the app if required.
11476     */
11477    private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
11478            boolean extractLibs)
11479                    throws PackageManagerException {
11480        // Give ourselves some initial paths; we'll come back for another
11481        // pass once we've determined ABI below.
11482        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11483
11484        // We would never need to extract libs for forward-locked and external packages,
11485        // since the container service will do it for us. We shouldn't attempt to
11486        // extract libs from system app when it was not updated.
11487        if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() ||
11488                (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) {
11489            extractLibs = false;
11490        }
11491
11492        final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
11493        final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
11494
11495        NativeLibraryHelper.Handle handle = null;
11496        try {
11497            handle = NativeLibraryHelper.Handle.create(pkg);
11498            // TODO(multiArch): This can be null for apps that didn't go through the
11499            // usual installation process. We can calculate it again, like we
11500            // do during install time.
11501            //
11502            // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
11503            // unnecessary.
11504            final File nativeLibraryRoot = new File(nativeLibraryRootStr);
11505
11506            // Null out the abis so that they can be recalculated.
11507            pkg.applicationInfo.primaryCpuAbi = null;
11508            pkg.applicationInfo.secondaryCpuAbi = null;
11509            if (isMultiArch(pkg.applicationInfo)) {
11510                // Warn if we've set an abiOverride for multi-lib packages..
11511                // By definition, we need to copy both 32 and 64 bit libraries for
11512                // such packages.
11513                if (pkg.cpuAbiOverride != null
11514                        && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
11515                    Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
11516                }
11517
11518                int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
11519                int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
11520                if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
11521                    if (extractLibs) {
11522                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11523                        abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11524                                nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
11525                                useIsaSpecificSubdirs);
11526                    } else {
11527                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11528                        abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
11529                    }
11530                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11531                }
11532
11533                // Shared library native code should be in the APK zip aligned
11534                if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
11535                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11536                            "Shared library native lib extraction not supported");
11537                }
11538
11539                maybeThrowExceptionForMultiArchCopy(
11540                        "Error unpackaging 32 bit native libs for multiarch app.", abi32);
11541
11542                if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
11543                    if (extractLibs) {
11544                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11545                        abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11546                                nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
11547                                useIsaSpecificSubdirs);
11548                    } else {
11549                        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11550                        abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
11551                    }
11552                    Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11553                }
11554
11555                maybeThrowExceptionForMultiArchCopy(
11556                        "Error unpackaging 64 bit native libs for multiarch app.", abi64);
11557
11558                if (abi64 >= 0) {
11559                    // Shared library native libs should be in the APK zip aligned
11560                    if (extractLibs && pkg.isLibrary()) {
11561                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11562                                "Shared library native lib extraction not supported");
11563                    }
11564                    pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
11565                }
11566
11567                if (abi32 >= 0) {
11568                    final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
11569                    if (abi64 >= 0) {
11570                        if (pkg.use32bitAbi) {
11571                            pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
11572                            pkg.applicationInfo.primaryCpuAbi = abi;
11573                        } else {
11574                            pkg.applicationInfo.secondaryCpuAbi = abi;
11575                        }
11576                    } else {
11577                        pkg.applicationInfo.primaryCpuAbi = abi;
11578                    }
11579                }
11580            } else {
11581                String[] abiList = (cpuAbiOverride != null) ?
11582                        new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
11583
11584                // Enable gross and lame hacks for apps that are built with old
11585                // SDK tools. We must scan their APKs for renderscript bitcode and
11586                // not launch them if it's present. Don't bother checking on devices
11587                // that don't have 64 bit support.
11588                boolean needsRenderScriptOverride = false;
11589                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
11590                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
11591                    abiList = Build.SUPPORTED_32_BIT_ABIS;
11592                    needsRenderScriptOverride = true;
11593                }
11594
11595                final int copyRet;
11596                if (extractLibs) {
11597                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
11598                    copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
11599                            nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
11600                } else {
11601                    Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
11602                    copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
11603                }
11604                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11605
11606                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
11607                    throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11608                            "Error unpackaging native libs for app, errorCode=" + copyRet);
11609                }
11610
11611                if (copyRet >= 0) {
11612                    // Shared libraries that have native libs must be multi-architecture
11613                    if (pkg.isLibrary()) {
11614                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
11615                                "Shared library with native libs must be multiarch");
11616                    }
11617                    pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
11618                } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
11619                    pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
11620                } else if (needsRenderScriptOverride) {
11621                    pkg.applicationInfo.primaryCpuAbi = abiList[0];
11622                }
11623            }
11624        } catch (IOException ioe) {
11625            Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
11626        } finally {
11627            IoUtils.closeQuietly(handle);
11628        }
11629
11630        // Now that we've calculated the ABIs and determined if it's an internal app,
11631        // we will go ahead and populate the nativeLibraryPath.
11632        setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11633    }
11634
11635    /**
11636     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
11637     * i.e, so that all packages can be run inside a single process if required.
11638     *
11639     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
11640     * this function will either try and make the ABI for all packages in {@code packagesForUser}
11641     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
11642     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
11643     * updating a package that belongs to a shared user.
11644     *
11645     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
11646     * adds unnecessary complexity.
11647     */
11648    private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
11649            Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
11650        List<String> changedAbiCodePath = null;
11651        String requiredInstructionSet = null;
11652        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
11653            requiredInstructionSet = VMRuntime.getInstructionSet(
11654                     scannedPackage.applicationInfo.primaryCpuAbi);
11655        }
11656
11657        PackageSetting requirer = null;
11658        for (PackageSetting ps : packagesForUser) {
11659            // If packagesForUser contains scannedPackage, we skip it. This will happen
11660            // when scannedPackage is an update of an existing package. Without this check,
11661            // we will never be able to change the ABI of any package belonging to a shared
11662            // user, even if it's compatible with other packages.
11663            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11664                if (ps.primaryCpuAbiString == null) {
11665                    continue;
11666                }
11667
11668                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
11669                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
11670                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
11671                    // this but there's not much we can do.
11672                    String errorMessage = "Instruction set mismatch, "
11673                            + ((requirer == null) ? "[caller]" : requirer)
11674                            + " requires " + requiredInstructionSet + " whereas " + ps
11675                            + " requires " + instructionSet;
11676                    Slog.w(TAG, errorMessage);
11677                }
11678
11679                if (requiredInstructionSet == null) {
11680                    requiredInstructionSet = instructionSet;
11681                    requirer = ps;
11682                }
11683            }
11684        }
11685
11686        if (requiredInstructionSet != null) {
11687            String adjustedAbi;
11688            if (requirer != null) {
11689                // requirer != null implies that either scannedPackage was null or that scannedPackage
11690                // did not require an ABI, in which case we have to adjust scannedPackage to match
11691                // the ABI of the set (which is the same as requirer's ABI)
11692                adjustedAbi = requirer.primaryCpuAbiString;
11693                if (scannedPackage != null) {
11694                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
11695                }
11696            } else {
11697                // requirer == null implies that we're updating all ABIs in the set to
11698                // match scannedPackage.
11699                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
11700            }
11701
11702            for (PackageSetting ps : packagesForUser) {
11703                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
11704                    if (ps.primaryCpuAbiString != null) {
11705                        continue;
11706                    }
11707
11708                    ps.primaryCpuAbiString = adjustedAbi;
11709                    if (ps.pkg != null && ps.pkg.applicationInfo != null &&
11710                            !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
11711                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
11712                        if (DEBUG_ABI_SELECTION) {
11713                            Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
11714                                    + " (requirer="
11715                                    + (requirer != null ? requirer.pkg : "null")
11716                                    + ", scannedPackage="
11717                                    + (scannedPackage != null ? scannedPackage : "null")
11718                                    + ")");
11719                        }
11720                        if (changedAbiCodePath == null) {
11721                            changedAbiCodePath = new ArrayList<>();
11722                        }
11723                        changedAbiCodePath.add(ps.codePathString);
11724                    }
11725                }
11726            }
11727        }
11728        return changedAbiCodePath;
11729    }
11730
11731    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
11732        synchronized (mPackages) {
11733            mResolverReplaced = true;
11734            // Set up information for custom user intent resolution activity.
11735            mResolveActivity.applicationInfo = pkg.applicationInfo;
11736            mResolveActivity.name = mCustomResolverComponentName.getClassName();
11737            mResolveActivity.packageName = pkg.applicationInfo.packageName;
11738            mResolveActivity.processName = pkg.applicationInfo.packageName;
11739            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
11740            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
11741                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11742            mResolveActivity.theme = 0;
11743            mResolveActivity.exported = true;
11744            mResolveActivity.enabled = true;
11745            mResolveInfo.activityInfo = mResolveActivity;
11746            mResolveInfo.priority = 0;
11747            mResolveInfo.preferredOrder = 0;
11748            mResolveInfo.match = 0;
11749            mResolveComponentName = mCustomResolverComponentName;
11750            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
11751                    mResolveComponentName);
11752        }
11753    }
11754
11755    private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
11756        if (installerActivity == null) {
11757            if (DEBUG_INSTANT) {
11758                Slog.d(TAG, "Clear ephemeral installer activity");
11759            }
11760            mInstantAppInstallerActivity = null;
11761            return;
11762        }
11763
11764        if (DEBUG_INSTANT) {
11765            Slog.d(TAG, "Set ephemeral installer activity: "
11766                    + installerActivity.getComponentName());
11767        }
11768        // Set up information for ephemeral installer activity
11769        mInstantAppInstallerActivity = installerActivity;
11770        mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
11771                | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
11772        mInstantAppInstallerActivity.exported = true;
11773        mInstantAppInstallerActivity.enabled = true;
11774        mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
11775        mInstantAppInstallerInfo.priority = 1;
11776        mInstantAppInstallerInfo.preferredOrder = 1;
11777        mInstantAppInstallerInfo.isDefault = true;
11778        mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
11779                | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
11780    }
11781
11782    private static String calculateBundledApkRoot(final String codePathString) {
11783        final File codePath = new File(codePathString);
11784        final File codeRoot;
11785        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
11786            codeRoot = Environment.getRootDirectory();
11787        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
11788            codeRoot = Environment.getOemDirectory();
11789        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
11790            codeRoot = Environment.getVendorDirectory();
11791        } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
11792            codeRoot = Environment.getOdmDirectory();
11793        } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
11794            codeRoot = Environment.getProductDirectory();
11795        } else {
11796            // Unrecognized code path; take its top real segment as the apk root:
11797            // e.g. /something/app/blah.apk => /something
11798            try {
11799                File f = codePath.getCanonicalFile();
11800                File parent = f.getParentFile();    // non-null because codePath is a file
11801                File tmp;
11802                while ((tmp = parent.getParentFile()) != null) {
11803                    f = parent;
11804                    parent = tmp;
11805                }
11806                codeRoot = f;
11807                Slog.w(TAG, "Unrecognized code path "
11808                        + codePath + " - using " + codeRoot);
11809            } catch (IOException e) {
11810                // Can't canonicalize the code path -- shenanigans?
11811                Slog.w(TAG, "Can't canonicalize code path " + codePath);
11812                return Environment.getRootDirectory().getPath();
11813            }
11814        }
11815        return codeRoot.getPath();
11816    }
11817
11818    /**
11819     * Derive and set the location of native libraries for the given package,
11820     * which varies depending on where and how the package was installed.
11821     */
11822    private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
11823        final ApplicationInfo info = pkg.applicationInfo;
11824        final String codePath = pkg.codePath;
11825        final File codeFile = new File(codePath);
11826        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
11827        final boolean asecApp = info.isForwardLocked() || info.isExternalAsec();
11828
11829        info.nativeLibraryRootDir = null;
11830        info.nativeLibraryRootRequiresIsa = false;
11831        info.nativeLibraryDir = null;
11832        info.secondaryNativeLibraryDir = null;
11833
11834        if (isApkFile(codeFile)) {
11835            // Monolithic install
11836            if (bundledApp) {
11837                // If "/system/lib64/apkname" exists, assume that is the per-package
11838                // native library directory to use; otherwise use "/system/lib/apkname".
11839                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
11840                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
11841                        getPrimaryInstructionSet(info));
11842
11843                // This is a bundled system app so choose the path based on the ABI.
11844                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
11845                // is just the default path.
11846                final String apkName = deriveCodePathName(codePath);
11847                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
11848                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
11849                        apkName).getAbsolutePath();
11850
11851                if (info.secondaryCpuAbi != null) {
11852                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
11853                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
11854                            secondaryLibDir, apkName).getAbsolutePath();
11855                }
11856            } else if (asecApp) {
11857                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
11858                        .getAbsolutePath();
11859            } else {
11860                final String apkName = deriveCodePathName(codePath);
11861                info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
11862                        .getAbsolutePath();
11863            }
11864
11865            info.nativeLibraryRootRequiresIsa = false;
11866            info.nativeLibraryDir = info.nativeLibraryRootDir;
11867        } else {
11868            // Cluster install
11869            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
11870            info.nativeLibraryRootRequiresIsa = true;
11871
11872            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
11873                    getPrimaryInstructionSet(info)).getAbsolutePath();
11874
11875            if (info.secondaryCpuAbi != null) {
11876                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
11877                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
11878            }
11879        }
11880    }
11881
11882    /**
11883     * Calculate the abis and roots for a bundled app. These can uniquely
11884     * be determined from the contents of the system partition, i.e whether
11885     * it contains 64 or 32 bit shared libraries etc. We do not validate any
11886     * of this information, and instead assume that the system was built
11887     * sensibly.
11888     */
11889    private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
11890                                           PackageSetting pkgSetting) {
11891        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
11892
11893        // If "/system/lib64/apkname" exists, assume that is the per-package
11894        // native library directory to use; otherwise use "/system/lib/apkname".
11895        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
11896        setBundledAppAbi(pkg, apkRoot, apkName);
11897        // pkgSetting might be null during rescan following uninstall of updates
11898        // to a bundled app, so accommodate that possibility.  The settings in
11899        // that case will be established later from the parsed package.
11900        //
11901        // If the settings aren't null, sync them up with what we've just derived.
11902        // note that apkRoot isn't stored in the package settings.
11903        if (pkgSetting != null) {
11904            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11905            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11906        }
11907    }
11908
11909    /**
11910     * Deduces the ABI of a bundled app and sets the relevant fields on the
11911     * parsed pkg object.
11912     *
11913     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
11914     *        under which system libraries are installed.
11915     * @param apkName the name of the installed package.
11916     */
11917    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
11918        final File codeFile = new File(pkg.codePath);
11919
11920        final boolean has64BitLibs;
11921        final boolean has32BitLibs;
11922        if (isApkFile(codeFile)) {
11923            // Monolithic install
11924            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
11925            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
11926        } else {
11927            // Cluster install
11928            final File rootDir = new File(codeFile, LIB_DIR_NAME);
11929            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
11930                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
11931                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
11932                has64BitLibs = (new File(rootDir, isa)).exists();
11933            } else {
11934                has64BitLibs = false;
11935            }
11936            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
11937                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
11938                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
11939                has32BitLibs = (new File(rootDir, isa)).exists();
11940            } else {
11941                has32BitLibs = false;
11942            }
11943        }
11944
11945        if (has64BitLibs && !has32BitLibs) {
11946            // The package has 64 bit libs, but not 32 bit libs. Its primary
11947            // ABI should be 64 bit. We can safely assume here that the bundled
11948            // native libraries correspond to the most preferred ABI in the list.
11949
11950            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11951            pkg.applicationInfo.secondaryCpuAbi = null;
11952        } else if (has32BitLibs && !has64BitLibs) {
11953            // The package has 32 bit libs but not 64 bit libs. Its primary
11954            // ABI should be 32 bit.
11955
11956            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11957            pkg.applicationInfo.secondaryCpuAbi = null;
11958        } else if (has32BitLibs && has64BitLibs) {
11959            // The application has both 64 and 32 bit bundled libraries. We check
11960            // here that the app declares multiArch support, and warn if it doesn't.
11961            //
11962            // We will be lenient here and record both ABIs. The primary will be the
11963            // ABI that's higher on the list, i.e, a device that's configured to prefer
11964            // 64 bit apps will see a 64 bit primary ABI,
11965
11966            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
11967                Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
11968            }
11969
11970            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
11971                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11972                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11973            } else {
11974                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
11975                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
11976            }
11977        } else {
11978            pkg.applicationInfo.primaryCpuAbi = null;
11979            pkg.applicationInfo.secondaryCpuAbi = null;
11980        }
11981    }
11982
11983    private void killApplication(String pkgName, int appId, String reason) {
11984        killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
11985    }
11986
11987    private void killApplication(String pkgName, int appId, int userId, String reason) {
11988        // Request the ActivityManager to kill the process(only for existing packages)
11989        // so that we do not end up in a confused state while the user is still using the older
11990        // version of the application while the new one gets installed.
11991        final long token = Binder.clearCallingIdentity();
11992        try {
11993            IActivityManager am = ActivityManager.getService();
11994            if (am != null) {
11995                try {
11996                    am.killApplication(pkgName, appId, userId, reason);
11997                } catch (RemoteException e) {
11998                }
11999            }
12000        } finally {
12001            Binder.restoreCallingIdentity(token);
12002        }
12003    }
12004
12005    private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12006        // Remove the parent package setting
12007        PackageSetting ps = (PackageSetting) pkg.mExtras;
12008        if (ps != null) {
12009            removePackageLI(ps, chatty);
12010        }
12011        // Remove the child package setting
12012        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12013        for (int i = 0; i < childCount; i++) {
12014            PackageParser.Package childPkg = pkg.childPackages.get(i);
12015            ps = (PackageSetting) childPkg.mExtras;
12016            if (ps != null) {
12017                removePackageLI(ps, chatty);
12018            }
12019        }
12020    }
12021
12022    void removePackageLI(PackageSetting ps, boolean chatty) {
12023        if (DEBUG_INSTALL) {
12024            if (chatty)
12025                Log.d(TAG, "Removing package " + ps.name);
12026        }
12027
12028        // writer
12029        synchronized (mPackages) {
12030            mPackages.remove(ps.name);
12031            final PackageParser.Package pkg = ps.pkg;
12032            if (pkg != null) {
12033                cleanPackageDataStructuresLILPw(pkg, chatty);
12034            }
12035        }
12036    }
12037
12038    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12039        if (DEBUG_INSTALL) {
12040            if (chatty)
12041                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12042        }
12043
12044        // writer
12045        synchronized (mPackages) {
12046            // Remove the parent package
12047            mPackages.remove(pkg.applicationInfo.packageName);
12048            cleanPackageDataStructuresLILPw(pkg, chatty);
12049
12050            // Remove the child packages
12051            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12052            for (int i = 0; i < childCount; i++) {
12053                PackageParser.Package childPkg = pkg.childPackages.get(i);
12054                mPackages.remove(childPkg.applicationInfo.packageName);
12055                cleanPackageDataStructuresLILPw(childPkg, chatty);
12056            }
12057        }
12058    }
12059
12060    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12061        int N = pkg.providers.size();
12062        StringBuilder r = null;
12063        int i;
12064        for (i=0; i<N; i++) {
12065            PackageParser.Provider p = pkg.providers.get(i);
12066            mProviders.removeProvider(p);
12067            if (p.info.authority == null) {
12068
12069                /* There was another ContentProvider with this authority when
12070                 * this app was installed so this authority is null,
12071                 * Ignore it as we don't have to unregister the provider.
12072                 */
12073                continue;
12074            }
12075            String names[] = p.info.authority.split(";");
12076            for (int j = 0; j < names.length; j++) {
12077                if (mProvidersByAuthority.get(names[j]) == p) {
12078                    mProvidersByAuthority.remove(names[j]);
12079                    if (DEBUG_REMOVE) {
12080                        if (chatty)
12081                            Log.d(TAG, "Unregistered content provider: " + names[j]
12082                                    + ", className = " + p.info.name + ", isSyncable = "
12083                                    + p.info.isSyncable);
12084                    }
12085                }
12086            }
12087            if (DEBUG_REMOVE && chatty) {
12088                if (r == null) {
12089                    r = new StringBuilder(256);
12090                } else {
12091                    r.append(' ');
12092                }
12093                r.append(p.info.name);
12094            }
12095        }
12096        if (r != null) {
12097            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
12098        }
12099
12100        N = pkg.services.size();
12101        r = null;
12102        for (i=0; i<N; i++) {
12103            PackageParser.Service s = pkg.services.get(i);
12104            mServices.removeService(s);
12105            if (chatty) {
12106                if (r == null) {
12107                    r = new StringBuilder(256);
12108                } else {
12109                    r.append(' ');
12110                }
12111                r.append(s.info.name);
12112            }
12113        }
12114        if (r != null) {
12115            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
12116        }
12117
12118        N = pkg.receivers.size();
12119        r = null;
12120        for (i=0; i<N; i++) {
12121            PackageParser.Activity a = pkg.receivers.get(i);
12122            mReceivers.removeActivity(a, "receiver");
12123            if (DEBUG_REMOVE && chatty) {
12124                if (r == null) {
12125                    r = new StringBuilder(256);
12126                } else {
12127                    r.append(' ');
12128                }
12129                r.append(a.info.name);
12130            }
12131        }
12132        if (r != null) {
12133            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
12134        }
12135
12136        N = pkg.activities.size();
12137        r = null;
12138        for (i=0; i<N; i++) {
12139            PackageParser.Activity a = pkg.activities.get(i);
12140            mActivities.removeActivity(a, "activity");
12141            if (DEBUG_REMOVE && chatty) {
12142                if (r == null) {
12143                    r = new StringBuilder(256);
12144                } else {
12145                    r.append(' ');
12146                }
12147                r.append(a.info.name);
12148            }
12149        }
12150        if (r != null) {
12151            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
12152        }
12153
12154        mPermissionManager.removeAllPermissions(pkg, chatty);
12155
12156        N = pkg.instrumentation.size();
12157        r = null;
12158        for (i=0; i<N; i++) {
12159            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12160            mInstrumentation.remove(a.getComponentName());
12161            if (DEBUG_REMOVE && chatty) {
12162                if (r == null) {
12163                    r = new StringBuilder(256);
12164                } else {
12165                    r.append(' ');
12166                }
12167                r.append(a.info.name);
12168            }
12169        }
12170        if (r != null) {
12171            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12172        }
12173
12174        r = null;
12175        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12176            // Only system apps can hold shared libraries.
12177            if (pkg.libraryNames != null) {
12178                for (i = 0; i < pkg.libraryNames.size(); i++) {
12179                    String name = pkg.libraryNames.get(i);
12180                    if (removeSharedLibraryLPw(name, 0)) {
12181                        if (DEBUG_REMOVE && chatty) {
12182                            if (r == null) {
12183                                r = new StringBuilder(256);
12184                            } else {
12185                                r.append(' ');
12186                            }
12187                            r.append(name);
12188                        }
12189                    }
12190                }
12191            }
12192        }
12193
12194        r = null;
12195
12196        // Any package can hold static shared libraries.
12197        if (pkg.staticSharedLibName != null) {
12198            if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12199                if (DEBUG_REMOVE && chatty) {
12200                    if (r == null) {
12201                        r = new StringBuilder(256);
12202                    } else {
12203                        r.append(' ');
12204                    }
12205                    r.append(pkg.staticSharedLibName);
12206                }
12207            }
12208        }
12209
12210        if (r != null) {
12211            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12212        }
12213    }
12214
12215
12216    final class ActivityIntentResolver
12217            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
12218        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12219                boolean defaultOnly, int userId) {
12220            if (!sUserManager.exists(userId)) return null;
12221            mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
12222            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12223        }
12224
12225        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12226                int userId) {
12227            if (!sUserManager.exists(userId)) return null;
12228            mFlags = flags;
12229            return super.queryIntent(intent, resolvedType,
12230                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12231                    userId);
12232        }
12233
12234        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12235                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
12236            if (!sUserManager.exists(userId)) return null;
12237            if (packageActivities == null) {
12238                return null;
12239            }
12240            mFlags = flags;
12241            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
12242            final int N = packageActivities.size();
12243            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
12244                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
12245
12246            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
12247            for (int i = 0; i < N; ++i) {
12248                intentFilters = packageActivities.get(i).intents;
12249                if (intentFilters != null && intentFilters.size() > 0) {
12250                    PackageParser.ActivityIntentInfo[] array =
12251                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
12252                    intentFilters.toArray(array);
12253                    listCut.add(array);
12254                }
12255            }
12256            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12257        }
12258
12259        /**
12260         * Finds a privileged activity that matches the specified activity names.
12261         */
12262        private PackageParser.Activity findMatchingActivity(
12263                List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
12264            for (PackageParser.Activity sysActivity : activityList) {
12265                if (sysActivity.info.name.equals(activityInfo.name)) {
12266                    return sysActivity;
12267                }
12268                if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
12269                    return sysActivity;
12270                }
12271                if (sysActivity.info.targetActivity != null) {
12272                    if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
12273                        return sysActivity;
12274                    }
12275                    if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
12276                        return sysActivity;
12277                    }
12278                }
12279            }
12280            return null;
12281        }
12282
12283        public class IterGenerator<E> {
12284            public Iterator<E> generate(ActivityIntentInfo info) {
12285                return null;
12286            }
12287        }
12288
12289        public class ActionIterGenerator extends IterGenerator<String> {
12290            @Override
12291            public Iterator<String> generate(ActivityIntentInfo info) {
12292                return info.actionsIterator();
12293            }
12294        }
12295
12296        public class CategoriesIterGenerator extends IterGenerator<String> {
12297            @Override
12298            public Iterator<String> generate(ActivityIntentInfo info) {
12299                return info.categoriesIterator();
12300            }
12301        }
12302
12303        public class SchemesIterGenerator extends IterGenerator<String> {
12304            @Override
12305            public Iterator<String> generate(ActivityIntentInfo info) {
12306                return info.schemesIterator();
12307            }
12308        }
12309
12310        public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> {
12311            @Override
12312            public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) {
12313                return info.authoritiesIterator();
12314            }
12315        }
12316
12317        /**
12318         * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE
12319         * MODIFIED. Do not pass in a list that should not be changed.
12320         */
12321        private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList,
12322                IterGenerator<T> generator, Iterator<T> searchIterator) {
12323            // loop through the set of actions; every one must be found in the intent filter
12324            while (searchIterator.hasNext()) {
12325                // we must have at least one filter in the list to consider a match
12326                if (intentList.size() == 0) {
12327                    break;
12328                }
12329
12330                final T searchAction = searchIterator.next();
12331
12332                // loop through the set of intent filters
12333                final Iterator<ActivityIntentInfo> intentIter = intentList.iterator();
12334                while (intentIter.hasNext()) {
12335                    final ActivityIntentInfo intentInfo = intentIter.next();
12336                    boolean selectionFound = false;
12337
12338                    // loop through the intent filter's selection criteria; at least one
12339                    // of them must match the searched criteria
12340                    final Iterator<T> intentSelectionIter = generator.generate(intentInfo);
12341                    while (intentSelectionIter != null && intentSelectionIter.hasNext()) {
12342                        final T intentSelection = intentSelectionIter.next();
12343                        if (intentSelection != null && intentSelection.equals(searchAction)) {
12344                            selectionFound = true;
12345                            break;
12346                        }
12347                    }
12348
12349                    // the selection criteria wasn't found in this filter's set; this filter
12350                    // is not a potential match
12351                    if (!selectionFound) {
12352                        intentIter.remove();
12353                    }
12354                }
12355            }
12356        }
12357
12358        private boolean isProtectedAction(ActivityIntentInfo filter) {
12359            final Iterator<String> actionsIter = filter.actionsIterator();
12360            while (actionsIter != null && actionsIter.hasNext()) {
12361                final String filterAction = actionsIter.next();
12362                if (PROTECTED_ACTIONS.contains(filterAction)) {
12363                    return true;
12364                }
12365            }
12366            return false;
12367        }
12368
12369        /**
12370         * Adjusts the priority of the given intent filter according to policy.
12371         * <p>
12372         * <ul>
12373         * <li>The priority for non privileged applications is capped to '0'</li>
12374         * <li>The priority for protected actions on privileged applications is capped to '0'</li>
12375         * <li>The priority for unbundled updates to privileged applications is capped to the
12376         *      priority defined on the system partition</li>
12377         * </ul>
12378         * <p>
12379         * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is
12380         * allowed to obtain any priority on any action.
12381         */
12382        private void adjustPriority(
12383                List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) {
12384            // nothing to do; priority is fine as-is
12385            if (intent.getPriority() <= 0) {
12386                return;
12387            }
12388
12389            final ActivityInfo activityInfo = intent.activity.info;
12390            final ApplicationInfo applicationInfo = activityInfo.applicationInfo;
12391
12392            final boolean privilegedApp =
12393                    ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0);
12394            if (!privilegedApp) {
12395                // non-privileged applications can never define a priority >0
12396                if (DEBUG_FILTERS) {
12397                    Slog.i(TAG, "Non-privileged app; cap priority to 0;"
12398                            + " package: " + applicationInfo.packageName
12399                            + " activity: " + intent.activity.className
12400                            + " origPrio: " + intent.getPriority());
12401                }
12402                intent.setPriority(0);
12403                return;
12404            }
12405
12406            if (systemActivities == null) {
12407                // the system package is not disabled; we're parsing the system partition
12408                if (isProtectedAction(intent)) {
12409                    if (mDeferProtectedFilters) {
12410                        // We can't deal with these just yet. No component should ever obtain a
12411                        // >0 priority for a protected actions, with ONE exception -- the setup
12412                        // wizard. The setup wizard, however, cannot be known until we're able to
12413                        // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do
12414                        // until all intent filters have been processed. Chicken, meet egg.
12415                        // Let the filter temporarily have a high priority and rectify the
12416                        // priorities after all system packages have been scanned.
12417                        mProtectedFilters.add(intent);
12418                        if (DEBUG_FILTERS) {
12419                            Slog.i(TAG, "Protected action; save for later;"
12420                                    + " package: " + applicationInfo.packageName
12421                                    + " activity: " + intent.activity.className
12422                                    + " origPrio: " + intent.getPriority());
12423                        }
12424                        return;
12425                    } else {
12426                        if (DEBUG_FILTERS && mSetupWizardPackage == null) {
12427                            Slog.i(TAG, "No setup wizard;"
12428                                + " All protected intents capped to priority 0");
12429                        }
12430                        if (intent.activity.info.packageName.equals(mSetupWizardPackage)) {
12431                            if (DEBUG_FILTERS) {
12432                                Slog.i(TAG, "Found setup wizard;"
12433                                    + " allow priority " + intent.getPriority() + ";"
12434                                    + " package: " + intent.activity.info.packageName
12435                                    + " activity: " + intent.activity.className
12436                                    + " priority: " + intent.getPriority());
12437                            }
12438                            // setup wizard gets whatever it wants
12439                            return;
12440                        }
12441                        if (DEBUG_FILTERS) {
12442                            Slog.i(TAG, "Protected action; cap priority to 0;"
12443                                    + " package: " + intent.activity.info.packageName
12444                                    + " activity: " + intent.activity.className
12445                                    + " origPrio: " + intent.getPriority());
12446                        }
12447                        intent.setPriority(0);
12448                        return;
12449                    }
12450                }
12451                // privileged apps on the system image get whatever priority they request
12452                return;
12453            }
12454
12455            // privileged app unbundled update ... try to find the same activity
12456            final PackageParser.Activity foundActivity =
12457                    findMatchingActivity(systemActivities, activityInfo);
12458            if (foundActivity == null) {
12459                // this is a new activity; it cannot obtain >0 priority
12460                if (DEBUG_FILTERS) {
12461                    Slog.i(TAG, "New activity; cap priority to 0;"
12462                            + " package: " + applicationInfo.packageName
12463                            + " activity: " + intent.activity.className
12464                            + " origPrio: " + intent.getPriority());
12465                }
12466                intent.setPriority(0);
12467                return;
12468            }
12469
12470            // found activity, now check for filter equivalence
12471
12472            // a shallow copy is enough; we modify the list, not its contents
12473            final List<ActivityIntentInfo> intentListCopy =
12474                    new ArrayList<>(foundActivity.intents);
12475            final List<ActivityIntentInfo> foundFilters = findFilters(intent);
12476
12477            // find matching action subsets
12478            final Iterator<String> actionsIterator = intent.actionsIterator();
12479            if (actionsIterator != null) {
12480                getIntentListSubset(
12481                        intentListCopy, new ActionIterGenerator(), actionsIterator);
12482                if (intentListCopy.size() == 0) {
12483                    // no more intents to match; we're not equivalent
12484                    if (DEBUG_FILTERS) {
12485                        Slog.i(TAG, "Mismatched action; cap priority to 0;"
12486                                + " package: " + applicationInfo.packageName
12487                                + " activity: " + intent.activity.className
12488                                + " origPrio: " + intent.getPriority());
12489                    }
12490                    intent.setPriority(0);
12491                    return;
12492                }
12493            }
12494
12495            // find matching category subsets
12496            final Iterator<String> categoriesIterator = intent.categoriesIterator();
12497            if (categoriesIterator != null) {
12498                getIntentListSubset(intentListCopy, new CategoriesIterGenerator(),
12499                        categoriesIterator);
12500                if (intentListCopy.size() == 0) {
12501                    // no more intents to match; we're not equivalent
12502                    if (DEBUG_FILTERS) {
12503                        Slog.i(TAG, "Mismatched category; cap priority to 0;"
12504                                + " package: " + applicationInfo.packageName
12505                                + " activity: " + intent.activity.className
12506                                + " origPrio: " + intent.getPriority());
12507                    }
12508                    intent.setPriority(0);
12509                    return;
12510                }
12511            }
12512
12513            // find matching schemes subsets
12514            final Iterator<String> schemesIterator = intent.schemesIterator();
12515            if (schemesIterator != null) {
12516                getIntentListSubset(intentListCopy, new SchemesIterGenerator(),
12517                        schemesIterator);
12518                if (intentListCopy.size() == 0) {
12519                    // no more intents to match; we're not equivalent
12520                    if (DEBUG_FILTERS) {
12521                        Slog.i(TAG, "Mismatched scheme; cap priority to 0;"
12522                                + " package: " + applicationInfo.packageName
12523                                + " activity: " + intent.activity.className
12524                                + " origPrio: " + intent.getPriority());
12525                    }
12526                    intent.setPriority(0);
12527                    return;
12528                }
12529            }
12530
12531            // find matching authorities subsets
12532            final Iterator<IntentFilter.AuthorityEntry>
12533                    authoritiesIterator = intent.authoritiesIterator();
12534            if (authoritiesIterator != null) {
12535                getIntentListSubset(intentListCopy,
12536                        new AuthoritiesIterGenerator(),
12537                        authoritiesIterator);
12538                if (intentListCopy.size() == 0) {
12539                    // no more intents to match; we're not equivalent
12540                    if (DEBUG_FILTERS) {
12541                        Slog.i(TAG, "Mismatched authority; cap priority to 0;"
12542                                + " package: " + applicationInfo.packageName
12543                                + " activity: " + intent.activity.className
12544                                + " origPrio: " + intent.getPriority());
12545                    }
12546                    intent.setPriority(0);
12547                    return;
12548                }
12549            }
12550
12551            // we found matching filter(s); app gets the max priority of all intents
12552            int cappedPriority = 0;
12553            for (int i = intentListCopy.size() - 1; i >= 0; --i) {
12554                cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority());
12555            }
12556            if (intent.getPriority() > cappedPriority) {
12557                if (DEBUG_FILTERS) {
12558                    Slog.i(TAG, "Found matching filter(s);"
12559                            + " cap priority to " + cappedPriority + ";"
12560                            + " package: " + applicationInfo.packageName
12561                            + " activity: " + intent.activity.className
12562                            + " origPrio: " + intent.getPriority());
12563                }
12564                intent.setPriority(cappedPriority);
12565                return;
12566            }
12567            // all this for nothing; the requested priority was <= what was on the system
12568        }
12569
12570        public final void addActivity(PackageParser.Activity a, String type) {
12571            mActivities.put(a.getComponentName(), a);
12572            if (DEBUG_SHOW_INFO)
12573                Log.v(
12574                TAG, "  " + type + " " +
12575                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
12576            if (DEBUG_SHOW_INFO)
12577                Log.v(TAG, "    Class=" + a.info.name);
12578            final int NI = a.intents.size();
12579            for (int j=0; j<NI; j++) {
12580                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12581                if ("activity".equals(type)) {
12582                    final PackageSetting ps =
12583                            mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName);
12584                    final List<PackageParser.Activity> systemActivities =
12585                            ps != null && ps.pkg != null ? ps.pkg.activities : null;
12586                    adjustPriority(systemActivities, intent);
12587                }
12588                if (DEBUG_SHOW_INFO) {
12589                    Log.v(TAG, "    IntentFilter:");
12590                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12591                }
12592                if (!intent.debugCheck()) {
12593                    Log.w(TAG, "==> For Activity " + a.info.name);
12594                }
12595                addFilter(intent);
12596            }
12597        }
12598
12599        public final void removeActivity(PackageParser.Activity a, String type) {
12600            mActivities.remove(a.getComponentName());
12601            if (DEBUG_SHOW_INFO) {
12602                Log.v(TAG, "  " + type + " "
12603                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
12604                                : a.info.name) + ":");
12605                Log.v(TAG, "    Class=" + a.info.name);
12606            }
12607            final int NI = a.intents.size();
12608            for (int j=0; j<NI; j++) {
12609                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
12610                if (DEBUG_SHOW_INFO) {
12611                    Log.v(TAG, "    IntentFilter:");
12612                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12613                }
12614                removeFilter(intent);
12615            }
12616        }
12617
12618        @Override
12619        protected boolean allowFilterResult(
12620                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
12621            ActivityInfo filterAi = filter.activity.info;
12622            for (int i=dest.size()-1; i>=0; i--) {
12623                ActivityInfo destAi = dest.get(i).activityInfo;
12624                if (destAi.name == filterAi.name
12625                        && destAi.packageName == filterAi.packageName) {
12626                    return false;
12627                }
12628            }
12629            return true;
12630        }
12631
12632        @Override
12633        protected ActivityIntentInfo[] newArray(int size) {
12634            return new ActivityIntentInfo[size];
12635        }
12636
12637        @Override
12638        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
12639            if (!sUserManager.exists(userId)) return true;
12640            PackageParser.Package p = filter.activity.owner;
12641            if (p != null) {
12642                PackageSetting ps = (PackageSetting)p.mExtras;
12643                if (ps != null) {
12644                    // System apps are never considered stopped for purposes of
12645                    // filtering, because there may be no way for the user to
12646                    // actually re-launch them.
12647                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
12648                            && ps.getStopped(userId);
12649                }
12650            }
12651            return false;
12652        }
12653
12654        @Override
12655        protected boolean isPackageForFilter(String packageName,
12656                PackageParser.ActivityIntentInfo info) {
12657            return packageName.equals(info.activity.owner.packageName);
12658        }
12659
12660        @Override
12661        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
12662                int match, int userId) {
12663            if (!sUserManager.exists(userId)) return null;
12664            if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) {
12665                return null;
12666            }
12667            final PackageParser.Activity activity = info.activity;
12668            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
12669            if (ps == null) {
12670                return null;
12671            }
12672            final PackageUserState userState = ps.readUserState(userId);
12673            ActivityInfo ai =
12674                    PackageParser.generateActivityInfo(activity, mFlags, userState, userId);
12675            if (ai == null) {
12676                return null;
12677            }
12678            final boolean matchExplicitlyVisibleOnly =
12679                    (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
12680            final boolean matchVisibleToInstantApp =
12681                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12682            final boolean componentVisible =
12683                    matchVisibleToInstantApp
12684                    && info.isVisibleToInstantApp()
12685                    && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp());
12686            final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12687            // throw out filters that aren't visible to ephemeral apps
12688            if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) {
12689                return null;
12690            }
12691            // throw out instant app filters if we're not explicitly requesting them
12692            if (!matchInstantApp && userState.instantApp) {
12693                return null;
12694            }
12695            // throw out instant app filters if updates are available; will trigger
12696            // instant app resolution
12697            if (userState.instantApp && ps.isUpdateAvailable()) {
12698                return null;
12699            }
12700            final ResolveInfo res = new ResolveInfo();
12701            res.activityInfo = ai;
12702            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12703                res.filter = info;
12704            }
12705            if (info != null) {
12706                res.handleAllWebDataURI = info.handleAllWebDataURI();
12707            }
12708            res.priority = info.getPriority();
12709            res.preferredOrder = activity.owner.mPreferredOrder;
12710            //System.out.println("Result: " + res.activityInfo.className +
12711            //                   " = " + res.priority);
12712            res.match = match;
12713            res.isDefault = info.hasDefault;
12714            res.labelRes = info.labelRes;
12715            res.nonLocalizedLabel = info.nonLocalizedLabel;
12716            if (userNeedsBadging(userId)) {
12717                res.noResourceId = true;
12718            } else {
12719                res.icon = info.icon;
12720            }
12721            res.iconResourceId = info.icon;
12722            res.system = res.activityInfo.applicationInfo.isSystemApp();
12723            res.isInstantAppAvailable = userState.instantApp;
12724            return res;
12725        }
12726
12727        @Override
12728        protected void sortResults(List<ResolveInfo> results) {
12729            Collections.sort(results, mResolvePrioritySorter);
12730        }
12731
12732        @Override
12733        protected void dumpFilter(PrintWriter out, String prefix,
12734                PackageParser.ActivityIntentInfo filter) {
12735            out.print(prefix); out.print(
12736                    Integer.toHexString(System.identityHashCode(filter.activity)));
12737                    out.print(' ');
12738                    filter.activity.printComponentShortName(out);
12739                    out.print(" filter ");
12740                    out.println(Integer.toHexString(System.identityHashCode(filter)));
12741        }
12742
12743        @Override
12744        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
12745            return filter.activity;
12746        }
12747
12748        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12749            PackageParser.Activity activity = (PackageParser.Activity)label;
12750            out.print(prefix); out.print(
12751                    Integer.toHexString(System.identityHashCode(activity)));
12752                    out.print(' ');
12753                    activity.printComponentShortName(out);
12754            if (count > 1) {
12755                out.print(" ("); out.print(count); out.print(" filters)");
12756            }
12757            out.println();
12758        }
12759
12760        // Keys are String (activity class name), values are Activity.
12761        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
12762                = new ArrayMap<ComponentName, PackageParser.Activity>();
12763        private int mFlags;
12764    }
12765
12766    private final class ServiceIntentResolver
12767            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
12768        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
12769                boolean defaultOnly, int userId) {
12770            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
12771            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
12772        }
12773
12774        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
12775                int userId) {
12776            if (!sUserManager.exists(userId)) return null;
12777            mFlags = flags;
12778            return super.queryIntent(intent, resolvedType,
12779                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
12780                    userId);
12781        }
12782
12783        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
12784                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
12785            if (!sUserManager.exists(userId)) return null;
12786            if (packageServices == null) {
12787                return null;
12788            }
12789            mFlags = flags;
12790            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
12791            final int N = packageServices.size();
12792            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
12793                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
12794
12795            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
12796            for (int i = 0; i < N; ++i) {
12797                intentFilters = packageServices.get(i).intents;
12798                if (intentFilters != null && intentFilters.size() > 0) {
12799                    PackageParser.ServiceIntentInfo[] array =
12800                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
12801                    intentFilters.toArray(array);
12802                    listCut.add(array);
12803                }
12804            }
12805            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
12806        }
12807
12808        public final void addService(PackageParser.Service s) {
12809            mServices.put(s.getComponentName(), s);
12810            if (DEBUG_SHOW_INFO) {
12811                Log.v(TAG, "  "
12812                        + (s.info.nonLocalizedLabel != null
12813                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12814                Log.v(TAG, "    Class=" + s.info.name);
12815            }
12816            final int NI = s.intents.size();
12817            int j;
12818            for (j=0; j<NI; j++) {
12819                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12820                if (DEBUG_SHOW_INFO) {
12821                    Log.v(TAG, "    IntentFilter:");
12822                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12823                }
12824                if (!intent.debugCheck()) {
12825                    Log.w(TAG, "==> For Service " + s.info.name);
12826                }
12827                addFilter(intent);
12828            }
12829        }
12830
12831        public final void removeService(PackageParser.Service s) {
12832            mServices.remove(s.getComponentName());
12833            if (DEBUG_SHOW_INFO) {
12834                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
12835                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
12836                Log.v(TAG, "    Class=" + s.info.name);
12837            }
12838            final int NI = s.intents.size();
12839            int j;
12840            for (j=0; j<NI; j++) {
12841                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
12842                if (DEBUG_SHOW_INFO) {
12843                    Log.v(TAG, "    IntentFilter:");
12844                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
12845                }
12846                removeFilter(intent);
12847            }
12848        }
12849
12850        @Override
12851        protected boolean allowFilterResult(
12852                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
12853            ServiceInfo filterSi = filter.service.info;
12854            for (int i=dest.size()-1; i>=0; i--) {
12855                ServiceInfo destAi = dest.get(i).serviceInfo;
12856                if (destAi.name == filterSi.name
12857                        && destAi.packageName == filterSi.packageName) {
12858                    return false;
12859                }
12860            }
12861            return true;
12862        }
12863
12864        @Override
12865        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
12866            return new PackageParser.ServiceIntentInfo[size];
12867        }
12868
12869        @Override
12870        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
12871            if (!sUserManager.exists(userId)) return true;
12872            PackageParser.Package p = filter.service.owner;
12873            if (p != null) {
12874                PackageSetting ps = (PackageSetting)p.mExtras;
12875                if (ps != null) {
12876                    // System apps are never considered stopped for purposes of
12877                    // filtering, because there may be no way for the user to
12878                    // actually re-launch them.
12879                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
12880                            && ps.getStopped(userId);
12881                }
12882            }
12883            return false;
12884        }
12885
12886        @Override
12887        protected boolean isPackageForFilter(String packageName,
12888                PackageParser.ServiceIntentInfo info) {
12889            return packageName.equals(info.service.owner.packageName);
12890        }
12891
12892        @Override
12893        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
12894                int match, int userId) {
12895            if (!sUserManager.exists(userId)) return null;
12896            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
12897            if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) {
12898                return null;
12899            }
12900            final PackageParser.Service service = info.service;
12901            PackageSetting ps = (PackageSetting) service.owner.mExtras;
12902            if (ps == null) {
12903                return null;
12904            }
12905            final PackageUserState userState = ps.readUserState(userId);
12906            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
12907                    userState, userId);
12908            if (si == null) {
12909                return null;
12910            }
12911            final boolean matchVisibleToInstantApp =
12912                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
12913            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
12914            // throw out filters that aren't visible to ephemeral apps
12915            if (matchVisibleToInstantApp
12916                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
12917                return null;
12918            }
12919            // throw out ephemeral filters if we're not explicitly requesting them
12920            if (!isInstantApp && userState.instantApp) {
12921                return null;
12922            }
12923            // throw out instant app filters if updates are available; will trigger
12924            // instant app resolution
12925            if (userState.instantApp && ps.isUpdateAvailable()) {
12926                return null;
12927            }
12928            final ResolveInfo res = new ResolveInfo();
12929            res.serviceInfo = si;
12930            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
12931                res.filter = filter;
12932            }
12933            res.priority = info.getPriority();
12934            res.preferredOrder = service.owner.mPreferredOrder;
12935            res.match = match;
12936            res.isDefault = info.hasDefault;
12937            res.labelRes = info.labelRes;
12938            res.nonLocalizedLabel = info.nonLocalizedLabel;
12939            res.icon = info.icon;
12940            res.system = res.serviceInfo.applicationInfo.isSystemApp();
12941            return res;
12942        }
12943
12944        @Override
12945        protected void sortResults(List<ResolveInfo> results) {
12946            Collections.sort(results, mResolvePrioritySorter);
12947        }
12948
12949        @Override
12950        protected void dumpFilter(PrintWriter out, String prefix,
12951                PackageParser.ServiceIntentInfo filter) {
12952            out.print(prefix); out.print(
12953                    Integer.toHexString(System.identityHashCode(filter.service)));
12954                    out.print(' ');
12955                    filter.service.printComponentShortName(out);
12956                    out.print(" filter ");
12957                    out.print(Integer.toHexString(System.identityHashCode(filter)));
12958                    if (filter.service.info.permission != null) {
12959                        out.print(" permission "); out.println(filter.service.info.permission);
12960                    } else {
12961                        out.println();
12962                    }
12963        }
12964
12965        @Override
12966        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
12967            return filter.service;
12968        }
12969
12970        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
12971            PackageParser.Service service = (PackageParser.Service)label;
12972            out.print(prefix); out.print(
12973                    Integer.toHexString(System.identityHashCode(service)));
12974                    out.print(' ');
12975                    service.printComponentShortName(out);
12976            if (count > 1) {
12977                out.print(" ("); out.print(count); out.print(" filters)");
12978            }
12979            out.println();
12980        }
12981
12982//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
12983//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
12984//            final List<ResolveInfo> retList = Lists.newArrayList();
12985//            while (i.hasNext()) {
12986//                final ResolveInfo resolveInfo = (ResolveInfo) i;
12987//                if (isEnabledLP(resolveInfo.serviceInfo)) {
12988//                    retList.add(resolveInfo);
12989//                }
12990//            }
12991//            return retList;
12992//        }
12993
12994        // Keys are String (activity class name), values are Activity.
12995        private final ArrayMap<ComponentName, PackageParser.Service> mServices
12996                = new ArrayMap<ComponentName, PackageParser.Service>();
12997        private int mFlags;
12998    }
12999
13000    private final class ProviderIntentResolver
13001            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
13002        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
13003                boolean defaultOnly, int userId) {
13004            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
13005            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
13006        }
13007
13008        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
13009                int userId) {
13010            if (!sUserManager.exists(userId))
13011                return null;
13012            mFlags = flags;
13013            return super.queryIntent(intent, resolvedType,
13014                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
13015                    userId);
13016        }
13017
13018        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
13019                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
13020            if (!sUserManager.exists(userId))
13021                return null;
13022            if (packageProviders == null) {
13023                return null;
13024            }
13025            mFlags = flags;
13026            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
13027            final int N = packageProviders.size();
13028            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
13029                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
13030
13031            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
13032            for (int i = 0; i < N; ++i) {
13033                intentFilters = packageProviders.get(i).intents;
13034                if (intentFilters != null && intentFilters.size() > 0) {
13035                    PackageParser.ProviderIntentInfo[] array =
13036                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
13037                    intentFilters.toArray(array);
13038                    listCut.add(array);
13039                }
13040            }
13041            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
13042        }
13043
13044        public final void addProvider(PackageParser.Provider p) {
13045            if (mProviders.containsKey(p.getComponentName())) {
13046                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
13047                return;
13048            }
13049
13050            mProviders.put(p.getComponentName(), p);
13051            if (DEBUG_SHOW_INFO) {
13052                Log.v(TAG, "  "
13053                        + (p.info.nonLocalizedLabel != null
13054                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
13055                Log.v(TAG, "    Class=" + p.info.name);
13056            }
13057            final int NI = p.intents.size();
13058            int j;
13059            for (j = 0; j < NI; j++) {
13060                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13061                if (DEBUG_SHOW_INFO) {
13062                    Log.v(TAG, "    IntentFilter:");
13063                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13064                }
13065                if (!intent.debugCheck()) {
13066                    Log.w(TAG, "==> For Provider " + p.info.name);
13067                }
13068                addFilter(intent);
13069            }
13070        }
13071
13072        public final void removeProvider(PackageParser.Provider p) {
13073            mProviders.remove(p.getComponentName());
13074            if (DEBUG_SHOW_INFO) {
13075                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
13076                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
13077                Log.v(TAG, "    Class=" + p.info.name);
13078            }
13079            final int NI = p.intents.size();
13080            int j;
13081            for (j = 0; j < NI; j++) {
13082                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
13083                if (DEBUG_SHOW_INFO) {
13084                    Log.v(TAG, "    IntentFilter:");
13085                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
13086                }
13087                removeFilter(intent);
13088            }
13089        }
13090
13091        @Override
13092        protected boolean allowFilterResult(
13093                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
13094            ProviderInfo filterPi = filter.provider.info;
13095            for (int i = dest.size() - 1; i >= 0; i--) {
13096                ProviderInfo destPi = dest.get(i).providerInfo;
13097                if (destPi.name == filterPi.name
13098                        && destPi.packageName == filterPi.packageName) {
13099                    return false;
13100                }
13101            }
13102            return true;
13103        }
13104
13105        @Override
13106        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
13107            return new PackageParser.ProviderIntentInfo[size];
13108        }
13109
13110        @Override
13111        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
13112            if (!sUserManager.exists(userId))
13113                return true;
13114            PackageParser.Package p = filter.provider.owner;
13115            if (p != null) {
13116                PackageSetting ps = (PackageSetting) p.mExtras;
13117                if (ps != null) {
13118                    // System apps are never considered stopped for purposes of
13119                    // filtering, because there may be no way for the user to
13120                    // actually re-launch them.
13121                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
13122                            && ps.getStopped(userId);
13123                }
13124            }
13125            return false;
13126        }
13127
13128        @Override
13129        protected boolean isPackageForFilter(String packageName,
13130                PackageParser.ProviderIntentInfo info) {
13131            return packageName.equals(info.provider.owner.packageName);
13132        }
13133
13134        @Override
13135        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
13136                int match, int userId) {
13137            if (!sUserManager.exists(userId))
13138                return null;
13139            final PackageParser.ProviderIntentInfo info = filter;
13140            if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) {
13141                return null;
13142            }
13143            final PackageParser.Provider provider = info.provider;
13144            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
13145            if (ps == null) {
13146                return null;
13147            }
13148            final PackageUserState userState = ps.readUserState(userId);
13149            final boolean matchVisibleToInstantApp =
13150                    (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
13151            final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0;
13152            // throw out filters that aren't visible to instant applications
13153            if (matchVisibleToInstantApp
13154                    && !(info.isVisibleToInstantApp() || userState.instantApp)) {
13155                return null;
13156            }
13157            // throw out instant application filters if we're not explicitly requesting them
13158            if (!isInstantApp && userState.instantApp) {
13159                return null;
13160            }
13161            // throw out instant application filters if updates are available; will trigger
13162            // instant application resolution
13163            if (userState.instantApp && ps.isUpdateAvailable()) {
13164                return null;
13165            }
13166            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
13167                    userState, userId);
13168            if (pi == null) {
13169                return null;
13170            }
13171            final ResolveInfo res = new ResolveInfo();
13172            res.providerInfo = pi;
13173            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
13174                res.filter = filter;
13175            }
13176            res.priority = info.getPriority();
13177            res.preferredOrder = provider.owner.mPreferredOrder;
13178            res.match = match;
13179            res.isDefault = info.hasDefault;
13180            res.labelRes = info.labelRes;
13181            res.nonLocalizedLabel = info.nonLocalizedLabel;
13182            res.icon = info.icon;
13183            res.system = res.providerInfo.applicationInfo.isSystemApp();
13184            return res;
13185        }
13186
13187        @Override
13188        protected void sortResults(List<ResolveInfo> results) {
13189            Collections.sort(results, mResolvePrioritySorter);
13190        }
13191
13192        @Override
13193        protected void dumpFilter(PrintWriter out, String prefix,
13194                PackageParser.ProviderIntentInfo filter) {
13195            out.print(prefix);
13196            out.print(
13197                    Integer.toHexString(System.identityHashCode(filter.provider)));
13198            out.print(' ');
13199            filter.provider.printComponentShortName(out);
13200            out.print(" filter ");
13201            out.println(Integer.toHexString(System.identityHashCode(filter)));
13202        }
13203
13204        @Override
13205        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
13206            return filter.provider;
13207        }
13208
13209        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
13210            PackageParser.Provider provider = (PackageParser.Provider)label;
13211            out.print(prefix); out.print(
13212                    Integer.toHexString(System.identityHashCode(provider)));
13213                    out.print(' ');
13214                    provider.printComponentShortName(out);
13215            if (count > 1) {
13216                out.print(" ("); out.print(count); out.print(" filters)");
13217            }
13218            out.println();
13219        }
13220
13221        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
13222                = new ArrayMap<ComponentName, PackageParser.Provider>();
13223        private int mFlags;
13224    }
13225
13226    static final class InstantAppIntentResolver
13227            extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter,
13228            AuxiliaryResolveInfo.AuxiliaryFilter> {
13229        /**
13230         * The result that has the highest defined order. Ordering applies on a
13231         * per-package basis. Mapping is from package name to Pair of order and
13232         * EphemeralResolveInfo.
13233         * <p>
13234         * NOTE: This is implemented as a field variable for convenience and efficiency.
13235         * By having a field variable, we're able to track filter ordering as soon as
13236         * a non-zero order is defined. Otherwise, multiple loops across the result set
13237         * would be needed to apply ordering. If the intent resolver becomes re-entrant,
13238         * this needs to be contained entirely within {@link #filterResults}.
13239         */
13240        final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>();
13241
13242        @Override
13243        protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) {
13244            return new AuxiliaryResolveInfo.AuxiliaryFilter[size];
13245        }
13246
13247        @Override
13248        protected boolean isPackageForFilter(String packageName,
13249                AuxiliaryResolveInfo.AuxiliaryFilter responseObj) {
13250            return true;
13251        }
13252
13253        @Override
13254        protected AuxiliaryResolveInfo.AuxiliaryFilter newResult(
13255                AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) {
13256            if (!sUserManager.exists(userId)) {
13257                return null;
13258            }
13259            final String packageName = responseObj.resolveInfo.getPackageName();
13260            final Integer order = responseObj.getOrder();
13261            final Pair<Integer, InstantAppResolveInfo> lastOrderResult =
13262                    mOrderResult.get(packageName);
13263            // ordering is enabled and this item's order isn't high enough
13264            if (lastOrderResult != null && lastOrderResult.first >= order) {
13265                return null;
13266            }
13267            final InstantAppResolveInfo res = responseObj.resolveInfo;
13268            if (order > 0) {
13269                // non-zero order, enable ordering
13270                mOrderResult.put(packageName, new Pair<>(order, res));
13271            }
13272            return responseObj;
13273        }
13274
13275        @Override
13276        protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) {
13277            // only do work if ordering is enabled [most of the time it won't be]
13278            if (mOrderResult.size() == 0) {
13279                return;
13280            }
13281            int resultSize = results.size();
13282            for (int i = 0; i < resultSize; i++) {
13283                final InstantAppResolveInfo info = results.get(i).resolveInfo;
13284                final String packageName = info.getPackageName();
13285                final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName);
13286                if (savedInfo == null) {
13287                    // package doesn't having ordering
13288                    continue;
13289                }
13290                if (savedInfo.second == info) {
13291                    // circled back to the highest ordered item; remove from order list
13292                    mOrderResult.remove(packageName);
13293                    if (mOrderResult.size() == 0) {
13294                        // no more ordered items
13295                        break;
13296                    }
13297                    continue;
13298                }
13299                // item has a worse order, remove it from the result list
13300                results.remove(i);
13301                resultSize--;
13302                i--;
13303            }
13304        }
13305    }
13306
13307    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
13308            new Comparator<ResolveInfo>() {
13309        public int compare(ResolveInfo r1, ResolveInfo r2) {
13310            int v1 = r1.priority;
13311            int v2 = r2.priority;
13312            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
13313            if (v1 != v2) {
13314                return (v1 > v2) ? -1 : 1;
13315            }
13316            v1 = r1.preferredOrder;
13317            v2 = r2.preferredOrder;
13318            if (v1 != v2) {
13319                return (v1 > v2) ? -1 : 1;
13320            }
13321            if (r1.isDefault != r2.isDefault) {
13322                return r1.isDefault ? -1 : 1;
13323            }
13324            v1 = r1.match;
13325            v2 = r2.match;
13326            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
13327            if (v1 != v2) {
13328                return (v1 > v2) ? -1 : 1;
13329            }
13330            if (r1.system != r2.system) {
13331                return r1.system ? -1 : 1;
13332            }
13333            if (r1.activityInfo != null) {
13334                return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName);
13335            }
13336            if (r1.serviceInfo != null) {
13337                return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName);
13338            }
13339            if (r1.providerInfo != null) {
13340                return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName);
13341            }
13342            return 0;
13343        }
13344    };
13345
13346    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
13347            new Comparator<ProviderInfo>() {
13348        public int compare(ProviderInfo p1, ProviderInfo p2) {
13349            final int v1 = p1.initOrder;
13350            final int v2 = p2.initOrder;
13351            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13352        }
13353    };
13354
13355    @Override
13356    public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
13357            final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
13358            final int[] userIds, int[] instantUserIds) {
13359        mHandler.post(new Runnable() {
13360            @Override
13361            public void run() {
13362                try {
13363                    final IActivityManager am = ActivityManager.getService();
13364                    if (am == null) return;
13365                    final int[] resolvedUserIds;
13366                    if (userIds == null) {
13367                        resolvedUserIds = am.getRunningUserIds();
13368                    } else {
13369                        resolvedUserIds = userIds;
13370                    }
13371                    doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13372                            resolvedUserIds, false);
13373                    if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
13374                        doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
13375                                instantUserIds, true);
13376                    }
13377                } catch (RemoteException ex) {
13378                }
13379            }
13380        });
13381    }
13382
13383    @Override
13384    public void notifyPackageAdded(String packageName) {
13385        final PackageListObserver[] observers;
13386        synchronized (mPackages) {
13387            if (mPackageListObservers.size() == 0) {
13388                return;
13389            }
13390            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13391        }
13392        for (int i = observers.length - 1; i >= 0; --i) {
13393            observers[i].onPackageAdded(packageName);
13394        }
13395    }
13396
13397    @Override
13398    public void notifyPackageRemoved(String packageName) {
13399        final PackageListObserver[] observers;
13400        synchronized (mPackages) {
13401            if (mPackageListObservers.size() == 0) {
13402                return;
13403            }
13404            observers = (PackageListObserver[]) mPackageListObservers.toArray();
13405        }
13406        for (int i = observers.length - 1; i >= 0; --i) {
13407            observers[i].onPackageRemoved(packageName);
13408        }
13409    }
13410
13411    /**
13412     * Sends a broadcast for the given action.
13413     * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13414     * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13415     * the system and applications allowed to see instant applications to receive package
13416     * lifecycle events for instant applications.
13417     */
13418    private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13419            int flags, String targetPkg, IIntentReceiver finishedReceiver,
13420            int[] userIds, boolean isInstantApp)
13421                    throws RemoteException {
13422        for (int id : userIds) {
13423            final Intent intent = new Intent(action,
13424                    pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13425            final String[] requiredPermissions =
13426                    isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13427            if (extras != null) {
13428                intent.putExtras(extras);
13429            }
13430            if (targetPkg != null) {
13431                intent.setPackage(targetPkg);
13432            }
13433            // Modify the UID when posting to other users
13434            int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13435            if (uid > 0 && UserHandle.getUserId(uid) != id) {
13436                uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13437                intent.putExtra(Intent.EXTRA_UID, uid);
13438            }
13439            intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13440            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13441            if (DEBUG_BROADCASTS) {
13442                RuntimeException here = new RuntimeException("here");
13443                here.fillInStackTrace();
13444                Slog.d(TAG, "Sending to user " + id + ": "
13445                        + intent.toShortString(false, true, false, false)
13446                        + " " + intent.getExtras(), here);
13447            }
13448            am.broadcastIntent(null, intent, null, finishedReceiver,
13449                    0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13450                    null, finishedReceiver != null, false, id);
13451        }
13452    }
13453
13454    /**
13455     * Check if the external storage media is available. This is true if there
13456     * is a mounted external storage medium or if the external storage is
13457     * emulated.
13458     */
13459    private boolean isExternalMediaAvailable() {
13460        return mMediaMounted || Environment.isExternalStorageEmulated();
13461    }
13462
13463    @Override
13464    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
13465        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
13466            return null;
13467        }
13468        if (!isExternalMediaAvailable()) {
13469                // If the external storage is no longer mounted at this point,
13470                // the caller may not have been able to delete all of this
13471                // packages files and can not delete any more.  Bail.
13472            return null;
13473        }
13474        synchronized (mPackages) {
13475            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
13476            if (lastPackage != null) {
13477                pkgs.remove(lastPackage);
13478            }
13479            if (pkgs.size() > 0) {
13480                return pkgs.get(0);
13481            }
13482        }
13483        return null;
13484    }
13485
13486    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
13487        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
13488                userId, andCode ? 1 : 0, packageName);
13489        if (mSystemReady) {
13490            msg.sendToTarget();
13491        } else {
13492            if (mPostSystemReadyMessages == null) {
13493                mPostSystemReadyMessages = new ArrayList<>();
13494            }
13495            mPostSystemReadyMessages.add(msg);
13496        }
13497    }
13498
13499    void startCleaningPackages() {
13500        // reader
13501        if (!isExternalMediaAvailable()) {
13502            return;
13503        }
13504        synchronized (mPackages) {
13505            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
13506                return;
13507            }
13508        }
13509        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
13510        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
13511        IActivityManager am = ActivityManager.getService();
13512        if (am != null) {
13513            int dcsUid = -1;
13514            synchronized (mPackages) {
13515                if (!mDefaultContainerWhitelisted) {
13516                    mDefaultContainerWhitelisted = true;
13517                    PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE);
13518                    dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId);
13519                }
13520            }
13521            try {
13522                if (dcsUid > 0) {
13523                    am.backgroundWhitelistUid(dcsUid);
13524                }
13525                am.startService(null, intent, null, false, mContext.getOpPackageName(),
13526                        UserHandle.USER_SYSTEM);
13527            } catch (RemoteException e) {
13528            }
13529        }
13530    }
13531
13532    /**
13533     * Ensure that the install reason matches what we know about the package installer (e.g. whether
13534     * it is acting on behalf on an enterprise or the user).
13535     *
13536     * Note that the ordering of the conditionals in this method is important. The checks we perform
13537     * are as follows, in this order:
13538     *
13539     * 1) If the install is being performed by a system app, we can trust the app to have set the
13540     *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13541     *    what it is.
13542     * 2) If the install is being performed by a device or profile owner app, the install reason
13543     *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13544     *    set the install reason correctly. If the app targets an older SDK version where install
13545     *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13546     *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13547     * 3) In all other cases, the install is being performed by a regular app that is neither part
13548     *    of the system nor a device or profile owner. We have no reason to believe that this app is
13549     *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13550     *    set to enterprise policy and if so, change it to unknown instead.
13551     */
13552    private int fixUpInstallReason(String installerPackageName, int installerUid,
13553            int installReason) {
13554        if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13555                == PERMISSION_GRANTED) {
13556            // If the install is being performed by a system app, we trust that app to have set the
13557            // install reason correctly.
13558            return installReason;
13559        }
13560
13561        final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
13562            ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
13563        if (dpm != null) {
13564            ComponentName owner = null;
13565            try {
13566                owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */);
13567                if (owner == null) {
13568                    owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid));
13569                }
13570            } catch (RemoteException e) {
13571            }
13572            if (owner != null && owner.getPackageName().equals(installerPackageName)) {
13573                // If the install is being performed by a device or profile owner, the install
13574                // reason should be enterprise policy.
13575                return PackageManager.INSTALL_REASON_POLICY;
13576            }
13577        }
13578
13579        if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13580            // If the install is being performed by a regular app (i.e. neither system app nor
13581            // device or profile owner), we have no reason to believe that the app is acting on
13582            // behalf of an enterprise. If the app set the install reason to enterprise policy,
13583            // change it to unknown instead.
13584            return PackageManager.INSTALL_REASON_UNKNOWN;
13585        }
13586
13587        // If the install is being performed by a regular app and the install reason was set to any
13588        // value but enterprise policy, leave the install reason unchanged.
13589        return installReason;
13590    }
13591
13592    void installStage(String packageName, File stagedDir,
13593            IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams,
13594            String installerPackageName, int installerUid, UserHandle user,
13595            PackageParser.SigningDetails signingDetails) {
13596        if (DEBUG_INSTANT) {
13597            if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
13598                Slog.d(TAG, "Ephemeral install of " + packageName);
13599            }
13600        }
13601        final VerificationInfo verificationInfo = new VerificationInfo(
13602                sessionParams.originatingUri, sessionParams.referrerUri,
13603                sessionParams.originatingUid, installerUid);
13604
13605        final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir);
13606
13607        final Message msg = mHandler.obtainMessage(INIT_COPY);
13608        final int installReason = fixUpInstallReason(installerPackageName, installerUid,
13609                sessionParams.installReason);
13610        final InstallParams params = new InstallParams(origin, null, observer,
13611                sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid,
13612                verificationInfo, user, sessionParams.abiOverride,
13613                sessionParams.grantedRuntimePermissions, signingDetails, installReason);
13614        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13615        msg.obj = params;
13616
13617        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13618                System.identityHashCode(msg.obj));
13619        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13620                System.identityHashCode(msg.obj));
13621
13622        mHandler.sendMessage(msg);
13623    }
13624
13625    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13626            int userId) {
13627        final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13628        final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13629        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13630        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13631        sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13632                false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13633
13634        // Send a session commit broadcast
13635        final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13636        info.installReason = pkgSetting.getInstallReason(userId);
13637        info.appPackageName = packageName;
13638        sendSessionCommitBroadcast(info, userId);
13639    }
13640
13641    @Override
13642    public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13643            boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13644        if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13645            return;
13646        }
13647        Bundle extras = new Bundle(1);
13648        // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13649        final int uid = UserHandle.getUid(
13650                (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13651        extras.putInt(Intent.EXTRA_UID, uid);
13652
13653        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13654                packageName, extras, 0, null, null, userIds, instantUserIds);
13655        if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13656            mHandler.post(() -> {
13657                        for (int userId : userIds) {
13658                            sendBootCompletedBroadcastToSystemApp(
13659                                    packageName, includeStopped, userId);
13660                        }
13661                    }
13662            );
13663        }
13664    }
13665
13666    /**
13667     * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13668     * automatically without needing an explicit launch.
13669     * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13670     */
13671    private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13672            int userId) {
13673        // If user is not running, the app didn't miss any broadcast
13674        if (!mUserManagerInternal.isUserRunning(userId)) {
13675            return;
13676        }
13677        final IActivityManager am = ActivityManager.getService();
13678        try {
13679            // Deliver LOCKED_BOOT_COMPLETED first
13680            Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13681                    .setPackage(packageName);
13682            if (includeStopped) {
13683                lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13684            }
13685            final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13686            am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13687                    android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13688
13689            // Deliver BOOT_COMPLETED only if user is unlocked
13690            if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13691                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13692                if (includeStopped) {
13693                    bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13694                }
13695                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13696                        android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13697            }
13698        } catch (RemoteException e) {
13699            throw e.rethrowFromSystemServer();
13700        }
13701    }
13702
13703    @Override
13704    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13705            int userId) {
13706        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13707        PackageSetting pkgSetting;
13708        final int callingUid = Binder.getCallingUid();
13709        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13710                true /* requireFullPermission */, true /* checkShell */,
13711                "setApplicationHiddenSetting for user " + userId);
13712
13713        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13714            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13715            return false;
13716        }
13717
13718        long callingId = Binder.clearCallingIdentity();
13719        try {
13720            boolean sendAdded = false;
13721            boolean sendRemoved = false;
13722            // writer
13723            synchronized (mPackages) {
13724                pkgSetting = mSettings.mPackages.get(packageName);
13725                if (pkgSetting == null) {
13726                    return false;
13727                }
13728                if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13729                    return false;
13730                }
13731                // Do not allow "android" is being disabled
13732                if ("android".equals(packageName)) {
13733                    Slog.w(TAG, "Cannot hide package: android");
13734                    return false;
13735                }
13736                // Cannot hide static shared libs as they are considered
13737                // a part of the using app (emulating static linking). Also
13738                // static libs are installed always on internal storage.
13739                PackageParser.Package pkg = mPackages.get(packageName);
13740                if (pkg != null && pkg.staticSharedLibName != null) {
13741                    Slog.w(TAG, "Cannot hide package: " + packageName
13742                            + " providing static shared library: "
13743                            + pkg.staticSharedLibName);
13744                    return false;
13745                }
13746                // Only allow protected packages to hide themselves.
13747                if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13748                        && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13749                    Slog.w(TAG, "Not hiding protected package: " + packageName);
13750                    return false;
13751                }
13752
13753                if (pkgSetting.getHidden(userId) != hidden) {
13754                    pkgSetting.setHidden(hidden, userId);
13755                    mSettings.writePackageRestrictionsLPr(userId);
13756                    if (hidden) {
13757                        sendRemoved = true;
13758                    } else {
13759                        sendAdded = true;
13760                    }
13761                }
13762            }
13763            if (sendAdded) {
13764                sendPackageAddedForUser(packageName, pkgSetting, userId);
13765                return true;
13766            }
13767            if (sendRemoved) {
13768                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13769                        "hiding pkg");
13770                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13771                return true;
13772            }
13773        } finally {
13774            Binder.restoreCallingIdentity(callingId);
13775        }
13776        return false;
13777    }
13778
13779    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13780            int userId) {
13781        final PackageRemovedInfo info = new PackageRemovedInfo(this);
13782        info.removedPackage = packageName;
13783        info.installerPackageName = pkgSetting.installerPackageName;
13784        info.removedUsers = new int[] {userId};
13785        info.broadcastUsers = new int[] {userId};
13786        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13787        info.sendPackageRemovedBroadcasts(true /*killApp*/);
13788    }
13789
13790    private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) {
13791        if (pkgList.length > 0) {
13792            Bundle extras = new Bundle(1);
13793            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13794
13795            sendPackageBroadcast(
13796                    suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13797                            : Intent.ACTION_PACKAGES_UNSUSPENDED,
13798                    null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13799                    new int[] {userId}, null);
13800        }
13801    }
13802
13803    /**
13804     * Returns true if application is not found or there was an error. Otherwise it returns
13805     * the hidden state of the package for the given user.
13806     */
13807    @Override
13808    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13809        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13810        final int callingUid = Binder.getCallingUid();
13811        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13812                true /* requireFullPermission */, false /* checkShell */,
13813                "getApplicationHidden for user " + userId);
13814        PackageSetting ps;
13815        long callingId = Binder.clearCallingIdentity();
13816        try {
13817            // writer
13818            synchronized (mPackages) {
13819                ps = mSettings.mPackages.get(packageName);
13820                if (ps == null) {
13821                    return true;
13822                }
13823                if (filterAppAccessLPr(ps, callingUid, userId)) {
13824                    return true;
13825                }
13826                return ps.getHidden(userId);
13827            }
13828        } finally {
13829            Binder.restoreCallingIdentity(callingId);
13830        }
13831    }
13832
13833    /**
13834     * @hide
13835     */
13836    @Override
13837    public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13838            int installReason) {
13839        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
13840                null);
13841        PackageSetting pkgSetting;
13842        final int callingUid = Binder.getCallingUid();
13843        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13844                true /* requireFullPermission */, true /* checkShell */,
13845                "installExistingPackage for user " + userId);
13846        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13847            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13848        }
13849
13850        long callingId = Binder.clearCallingIdentity();
13851        try {
13852            boolean installed = false;
13853            final boolean instantApp =
13854                    (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13855            final boolean fullApp =
13856                    (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13857
13858            // writer
13859            synchronized (mPackages) {
13860                pkgSetting = mSettings.mPackages.get(packageName);
13861                if (pkgSetting == null) {
13862                    return PackageManager.INSTALL_FAILED_INVALID_URI;
13863                }
13864                if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13865                    // only allow the existing package to be used if it's installed as a full
13866                    // application for at least one user
13867                    boolean installAllowed = false;
13868                    for (int checkUserId : sUserManager.getUserIds()) {
13869                        installAllowed = !pkgSetting.getInstantApp(checkUserId);
13870                        if (installAllowed) {
13871                            break;
13872                        }
13873                    }
13874                    if (!installAllowed) {
13875                        return PackageManager.INSTALL_FAILED_INVALID_URI;
13876                    }
13877                }
13878                if (!pkgSetting.getInstalled(userId)) {
13879                    pkgSetting.setInstalled(true, userId);
13880                    pkgSetting.setHidden(false, userId);
13881                    pkgSetting.setInstallReason(installReason, userId);
13882                    mSettings.writePackageRestrictionsLPr(userId);
13883                    mSettings.writeKernelMappingLPr(pkgSetting);
13884                    installed = true;
13885                } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13886                    // upgrade app from instant to full; we don't allow app downgrade
13887                    installed = true;
13888                }
13889                setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13890            }
13891
13892            if (installed) {
13893                if (pkgSetting.pkg != null) {
13894                    synchronized (mInstallLock) {
13895                        // We don't need to freeze for a brand new install
13896                        prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13897                    }
13898                }
13899                sendPackageAddedForUser(packageName, pkgSetting, userId);
13900                synchronized (mPackages) {
13901                    updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13902                }
13903            }
13904        } finally {
13905            Binder.restoreCallingIdentity(callingId);
13906        }
13907
13908        return PackageManager.INSTALL_SUCCEEDED;
13909    }
13910
13911    void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13912            boolean instantApp, boolean fullApp) {
13913        // no state specified; do nothing
13914        if (!instantApp && !fullApp) {
13915            return;
13916        }
13917        if (userId != UserHandle.USER_ALL) {
13918            if (instantApp && !pkgSetting.getInstantApp(userId)) {
13919                pkgSetting.setInstantApp(true /*instantApp*/, userId);
13920            } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13921                pkgSetting.setInstantApp(false /*instantApp*/, userId);
13922            }
13923        } else {
13924            for (int currentUserId : sUserManager.getUserIds()) {
13925                if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13926                    pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13927                } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13928                    pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13929                }
13930            }
13931        }
13932    }
13933
13934    boolean isUserRestricted(int userId, String restrictionKey) {
13935        Bundle restrictions = sUserManager.getUserRestrictions(userId);
13936        if (restrictions.getBoolean(restrictionKey, false)) {
13937            Log.w(TAG, "User is restricted: " + restrictionKey);
13938            return true;
13939        }
13940        return false;
13941    }
13942
13943    @Override
13944    public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13945            PersistableBundle appExtras, PersistableBundle launcherExtras, String callingPackage,
13946            int userId) {
13947        try {
13948            mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, null);
13949        } catch (SecurityException e) {
13950            mContext.enforceCallingOrSelfPermission(Manifest.permission.MANAGE_USERS,
13951                    "Callers need to have either " + Manifest.permission.SUSPEND_APPS + " or "
13952                            + Manifest.permission.MANAGE_USERS);
13953        }
13954        final int callingUid = Binder.getCallingUid();
13955        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13956                true /* requireFullPermission */, true /* checkShell */,
13957                "setPackagesSuspended for user " + userId);
13958        if (callingUid != Process.ROOT_UID &&
13959                !UserHandle.isSameApp(getPackageUid(callingPackage, 0, userId), callingUid)) {
13960            throw new IllegalArgumentException("callingPackage " + callingPackage + " does not"
13961                    + " belong to calling app id " + UserHandle.getAppId(callingUid));
13962        }
13963
13964        if (ArrayUtils.isEmpty(packageNames)) {
13965            return packageNames;
13966        }
13967
13968        // List of package names for whom the suspended state has changed.
13969        final List<String> changedPackages = new ArrayList<>(packageNames.length);
13970        // List of package names for whom the suspended state is not set as requested in this
13971        // method.
13972        final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13973        final long callingId = Binder.clearCallingIdentity();
13974        try {
13975            synchronized (mPackages) {
13976                for (int i = 0; i < packageNames.length; i++) {
13977                    final String packageName = packageNames[i];
13978                    if (packageName == callingPackage) {
13979                        Slog.w(TAG, "Calling package: " + callingPackage + "trying to "
13980                                + (suspended ? "" : "un") + "suspend itself. Ignoring");
13981                        unactionedPackages.add(packageName);
13982                        continue;
13983                    }
13984                    final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13985                    if (pkgSetting == null
13986                            || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13987                        Slog.w(TAG, "Could not find package setting for package \"" + packageName
13988                                + "\". Skipping suspending/un-suspending.");
13989                        unactionedPackages.add(packageName);
13990                        continue;
13991                    }
13992                    if (pkgSetting.getSuspended(userId) != suspended) {
13993                        if (!canSuspendPackageForUserLocked(packageName, userId)) {
13994                            unactionedPackages.add(packageName);
13995                            continue;
13996                        }
13997                        pkgSetting.setSuspended(suspended, callingPackage, appExtras,
13998                                launcherExtras, userId);
13999                        changedPackages.add(packageName);
14000                    }
14001                }
14002            }
14003        } finally {
14004            Binder.restoreCallingIdentity(callingId);
14005        }
14006        // TODO (b/75036698): Also send each package a broadcast when suspended state changed
14007        if (!changedPackages.isEmpty()) {
14008            sendPackagesSuspendedForUser(changedPackages.toArray(
14009                    new String[changedPackages.size()]), userId, suspended);
14010            synchronized (mPackages) {
14011                scheduleWritePackageRestrictionsLocked(userId);
14012            }
14013        }
14014
14015        return unactionedPackages.toArray(new String[unactionedPackages.size()]);
14016    }
14017
14018    @Override
14019    public PersistableBundle getPackageSuspendedAppExtras(String packageName, int userId) {
14020        final int callingUid = Binder.getCallingUid();
14021        if (getPackageUid(packageName, 0, userId) != callingUid) {
14022            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14023        }
14024        synchronized (mPackages) {
14025            final PackageSetting ps = mSettings.mPackages.get(packageName);
14026            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14027                throw new IllegalArgumentException("Unknown target package: " + packageName);
14028            }
14029            final PackageUserState packageUserState = ps.readUserState(userId);
14030            return packageUserState.suspended ? packageUserState.suspendedAppExtras : null;
14031        }
14032    }
14033
14034    @Override
14035    public void setSuspendedPackageAppExtras(String packageName, PersistableBundle appExtras,
14036            int userId) {
14037        final int callingUid = Binder.getCallingUid();
14038        mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14039        synchronized (mPackages) {
14040            final PackageSetting ps = mSettings.mPackages.get(packageName);
14041            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14042                throw new IllegalArgumentException("Unknown target package: " + packageName);
14043            }
14044            final PackageUserState packageUserState = ps.readUserState(userId);
14045            if (packageUserState.suspended) {
14046                // TODO (b/75036698): Also send this package a broadcast with the new app extras
14047                packageUserState.suspendedAppExtras = appExtras;
14048            }
14049        }
14050    }
14051
14052    @Override
14053    public boolean isPackageSuspendedForUser(String packageName, int userId) {
14054        final int callingUid = Binder.getCallingUid();
14055        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
14056                true /* requireFullPermission */, false /* checkShell */,
14057                "isPackageSuspendedForUser for user " + userId);
14058        if (getPackageUid(packageName, 0, userId) != callingUid) {
14059            mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, null);
14060        }
14061        synchronized (mPackages) {
14062            final PackageSetting ps = mSettings.mPackages.get(packageName);
14063            if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
14064                throw new IllegalArgumentException("Unknown target package: " + packageName);
14065            }
14066            return ps.getSuspended(userId);
14067        }
14068    }
14069
14070    void onSuspendingPackageRemoved(String packageName, int userId) {
14071        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
14072                : new int[] {userId};
14073        synchronized (mPackages) {
14074            for (PackageSetting ps : mSettings.mPackages.values()) {
14075                for (int user : userIds) {
14076                    final PackageUserState pus = ps.readUserState(user);
14077                    if (pus.suspended && packageName.equals(pus.suspendingPackage)) {
14078                        ps.setSuspended(false, null, null, null, user);
14079                    }
14080                }
14081            }
14082        }
14083    }
14084
14085    @GuardedBy("mPackages")
14086    private boolean canSuspendPackageForUserLocked(String packageName, int userId) {
14087        if (isPackageDeviceAdmin(packageName, userId)) {
14088            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14089                    + "\": has an active device admin");
14090            return false;
14091        }
14092
14093        String activeLauncherPackageName = getActiveLauncherPackageName(userId);
14094        if (packageName.equals(activeLauncherPackageName)) {
14095            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14096                    + "\": contains the active launcher");
14097            return false;
14098        }
14099
14100        if (packageName.equals(mRequiredInstallerPackage)) {
14101            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14102                    + "\": required for package installation");
14103            return false;
14104        }
14105
14106        if (packageName.equals(mRequiredUninstallerPackage)) {
14107            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14108                    + "\": required for package uninstallation");
14109            return false;
14110        }
14111
14112        if (packageName.equals(mRequiredVerifierPackage)) {
14113            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14114                    + "\": required for package verification");
14115            return false;
14116        }
14117
14118        if (packageName.equals(getDefaultDialerPackageName(userId))) {
14119            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14120                    + "\": is the default dialer");
14121            return false;
14122        }
14123
14124        if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
14125            Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName
14126                    + "\": protected package");
14127            return false;
14128        }
14129
14130        // Cannot suspend static shared libs as they are considered
14131        // a part of the using app (emulating static linking). Also
14132        // static libs are installed always on internal storage.
14133        PackageParser.Package pkg = mPackages.get(packageName);
14134        if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
14135            Slog.w(TAG, "Cannot suspend package: " + packageName
14136                    + " providing static shared library: "
14137                    + pkg.staticSharedLibName);
14138            return false;
14139        }
14140
14141        if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
14142            Slog.w(TAG, "Cannot suspend package: " + packageName);
14143            return false;
14144        }
14145
14146        return true;
14147    }
14148
14149    private String getActiveLauncherPackageName(int userId) {
14150        Intent intent = new Intent(Intent.ACTION_MAIN);
14151        intent.addCategory(Intent.CATEGORY_HOME);
14152        ResolveInfo resolveInfo = resolveIntent(
14153                intent,
14154                intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14155                PackageManager.MATCH_DEFAULT_ONLY,
14156                userId);
14157
14158        return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14159    }
14160
14161    private String getDefaultDialerPackageName(int userId) {
14162        synchronized (mPackages) {
14163            return mSettings.getDefaultDialerPackageNameLPw(userId);
14164        }
14165    }
14166
14167    @Override
14168    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14169        mContext.enforceCallingOrSelfPermission(
14170                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14171                "Only package verification agents can verify applications");
14172
14173        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14174        final PackageVerificationResponse response = new PackageVerificationResponse(
14175                verificationCode, Binder.getCallingUid());
14176        msg.arg1 = id;
14177        msg.obj = response;
14178        mHandler.sendMessage(msg);
14179    }
14180
14181    @Override
14182    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14183            long millisecondsToDelay) {
14184        mContext.enforceCallingOrSelfPermission(
14185                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14186                "Only package verification agents can extend verification timeouts");
14187
14188        final PackageVerificationState state = mPendingVerification.get(id);
14189        final PackageVerificationResponse response = new PackageVerificationResponse(
14190                verificationCodeAtTimeout, Binder.getCallingUid());
14191
14192        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14193            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14194        }
14195        if (millisecondsToDelay < 0) {
14196            millisecondsToDelay = 0;
14197        }
14198        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14199                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14200            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14201        }
14202
14203        if ((state != null) && !state.timeoutExtended()) {
14204            state.extendTimeout();
14205
14206            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14207            msg.arg1 = id;
14208            msg.obj = response;
14209            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14210        }
14211    }
14212
14213    private void broadcastPackageVerified(int verificationId, Uri packageUri,
14214            int verificationCode, UserHandle user) {
14215        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14216        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14217        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14218        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14219        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14220
14221        mContext.sendBroadcastAsUser(intent, user,
14222                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14223    }
14224
14225    private ComponentName matchComponentForVerifier(String packageName,
14226            List<ResolveInfo> receivers) {
14227        ActivityInfo targetReceiver = null;
14228
14229        final int NR = receivers.size();
14230        for (int i = 0; i < NR; i++) {
14231            final ResolveInfo info = receivers.get(i);
14232            if (info.activityInfo == null) {
14233                continue;
14234            }
14235
14236            if (packageName.equals(info.activityInfo.packageName)) {
14237                targetReceiver = info.activityInfo;
14238                break;
14239            }
14240        }
14241
14242        if (targetReceiver == null) {
14243            return null;
14244        }
14245
14246        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14247    }
14248
14249    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14250            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14251        if (pkgInfo.verifiers.length == 0) {
14252            return null;
14253        }
14254
14255        final int N = pkgInfo.verifiers.length;
14256        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
14257        for (int i = 0; i < N; i++) {
14258            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14259
14260            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14261                    receivers);
14262            if (comp == null) {
14263                continue;
14264            }
14265
14266            final int verifierUid = getUidForVerifier(verifierInfo);
14267            if (verifierUid == -1) {
14268                continue;
14269            }
14270
14271            if (DEBUG_VERIFY) {
14272                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14273                        + " with the correct signature");
14274            }
14275            sufficientVerifiers.add(comp);
14276            verificationState.addSufficientVerifier(verifierUid);
14277        }
14278
14279        return sufficientVerifiers;
14280    }
14281
14282    private int getUidForVerifier(VerifierInfo verifierInfo) {
14283        synchronized (mPackages) {
14284            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14285            if (pkg == null) {
14286                return -1;
14287            } else if (pkg.mSigningDetails.signatures.length != 1) {
14288                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14289                        + " has more than one signature; ignoring");
14290                return -1;
14291            }
14292
14293            /*
14294             * If the public key of the package's signature does not match
14295             * our expected public key, then this is a different package and
14296             * we should skip.
14297             */
14298
14299            final byte[] expectedPublicKey;
14300            try {
14301                final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14302                final PublicKey publicKey = verifierSig.getPublicKey();
14303                expectedPublicKey = publicKey.getEncoded();
14304            } catch (CertificateException e) {
14305                return -1;
14306            }
14307
14308            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14309
14310            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14311                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14312                        + " does not have the expected public key; ignoring");
14313                return -1;
14314            }
14315
14316            return pkg.applicationInfo.uid;
14317        }
14318    }
14319
14320    @Override
14321    public void finishPackageInstall(int token, boolean didLaunch) {
14322        enforceSystemOrRoot("Only the system is allowed to finish installs");
14323
14324        if (DEBUG_INSTALL) {
14325            Slog.v(TAG, "BM finishing package install for " + token);
14326        }
14327        Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14328
14329        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14330        mHandler.sendMessage(msg);
14331    }
14332
14333    /**
14334     * Get the verification agent timeout.  Used for both the APK verifier and the
14335     * intent filter verifier.
14336     *
14337     * @return verification timeout in milliseconds
14338     */
14339    private long getVerificationTimeout() {
14340        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14341                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14342                DEFAULT_VERIFICATION_TIMEOUT);
14343    }
14344
14345    /**
14346     * Get the default verification agent response code.
14347     *
14348     * @return default verification response code
14349     */
14350    private int getDefaultVerificationResponse(UserHandle user) {
14351        if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14352            return PackageManager.VERIFICATION_REJECT;
14353        }
14354        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14355                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14356                DEFAULT_VERIFICATION_RESPONSE);
14357    }
14358
14359    /**
14360     * Check whether or not package verification has been enabled.
14361     *
14362     * @return true if verification should be performed
14363     */
14364    private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14365        if (!DEFAULT_VERIFY_ENABLE) {
14366            return false;
14367        }
14368
14369        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14370
14371        // Check if installing from ADB
14372        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14373            // Do not run verification in a test harness environment
14374            if (ActivityManager.isRunningInTestHarness()) {
14375                return false;
14376            }
14377            if (ensureVerifyAppsEnabled) {
14378                return true;
14379            }
14380            // Check if the developer does not want package verification for ADB installs
14381            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14382                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14383                return false;
14384            }
14385        } else {
14386            // only when not installed from ADB, skip verification for instant apps when
14387            // the installer and verifier are the same.
14388            if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14389                if (mInstantAppInstallerActivity != null
14390                        && mInstantAppInstallerActivity.packageName.equals(
14391                                mRequiredVerifierPackage)) {
14392                    try {
14393                        mContext.getSystemService(AppOpsManager.class)
14394                                .checkPackage(installerUid, mRequiredVerifierPackage);
14395                        if (DEBUG_VERIFY) {
14396                            Slog.i(TAG, "disable verification for instant app");
14397                        }
14398                        return false;
14399                    } catch (SecurityException ignore) { }
14400                }
14401            }
14402        }
14403
14404        if (ensureVerifyAppsEnabled) {
14405            return true;
14406        }
14407
14408        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14409                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14410    }
14411
14412    @Override
14413    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14414            throws RemoteException {
14415        mContext.enforceCallingOrSelfPermission(
14416                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14417                "Only intentfilter verification agents can verify applications");
14418
14419        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14420        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14421                Binder.getCallingUid(), verificationCode, failedDomains);
14422        msg.arg1 = id;
14423        msg.obj = response;
14424        mHandler.sendMessage(msg);
14425    }
14426
14427    @Override
14428    public int getIntentVerificationStatus(String packageName, int userId) {
14429        final int callingUid = Binder.getCallingUid();
14430        if (UserHandle.getUserId(callingUid) != userId) {
14431            mContext.enforceCallingOrSelfPermission(
14432                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14433                    "getIntentVerificationStatus" + userId);
14434        }
14435        if (getInstantAppPackageName(callingUid) != null) {
14436            return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14437        }
14438        synchronized (mPackages) {
14439            final PackageSetting ps = mSettings.mPackages.get(packageName);
14440            if (ps == null
14441                    || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14442                return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14443            }
14444            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14445        }
14446    }
14447
14448    @Override
14449    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14450        mContext.enforceCallingOrSelfPermission(
14451                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14452
14453        boolean result = false;
14454        synchronized (mPackages) {
14455            final PackageSetting ps = mSettings.mPackages.get(packageName);
14456            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14457                return false;
14458            }
14459            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14460        }
14461        if (result) {
14462            scheduleWritePackageRestrictionsLocked(userId);
14463        }
14464        return result;
14465    }
14466
14467    @Override
14468    public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14469            String packageName) {
14470        final int callingUid = Binder.getCallingUid();
14471        if (getInstantAppPackageName(callingUid) != null) {
14472            return ParceledListSlice.emptyList();
14473        }
14474        synchronized (mPackages) {
14475            final PackageSetting ps = mSettings.mPackages.get(packageName);
14476            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14477                return ParceledListSlice.emptyList();
14478            }
14479            return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14480        }
14481    }
14482
14483    @Override
14484    public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14485        if (TextUtils.isEmpty(packageName)) {
14486            return ParceledListSlice.emptyList();
14487        }
14488        final int callingUid = Binder.getCallingUid();
14489        final int callingUserId = UserHandle.getUserId(callingUid);
14490        synchronized (mPackages) {
14491            PackageParser.Package pkg = mPackages.get(packageName);
14492            if (pkg == null || pkg.activities == null) {
14493                return ParceledListSlice.emptyList();
14494            }
14495            if (pkg.mExtras == null) {
14496                return ParceledListSlice.emptyList();
14497            }
14498            final PackageSetting ps = (PackageSetting) pkg.mExtras;
14499            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14500                return ParceledListSlice.emptyList();
14501            }
14502            final int count = pkg.activities.size();
14503            ArrayList<IntentFilter> result = new ArrayList<>();
14504            for (int n=0; n<count; n++) {
14505                PackageParser.Activity activity = pkg.activities.get(n);
14506                if (activity.intents != null && activity.intents.size() > 0) {
14507                    result.addAll(activity.intents);
14508                }
14509            }
14510            return new ParceledListSlice<>(result);
14511        }
14512    }
14513
14514    @Override
14515    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14516        mContext.enforceCallingOrSelfPermission(
14517                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14518        if (UserHandle.getCallingUserId() != userId) {
14519            mContext.enforceCallingOrSelfPermission(
14520                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14521        }
14522
14523        synchronized (mPackages) {
14524            boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId);
14525            if (packageName != null) {
14526                mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(
14527                        packageName, userId);
14528            }
14529            return result;
14530        }
14531    }
14532
14533    @Override
14534    public String getDefaultBrowserPackageName(int userId) {
14535        if (UserHandle.getCallingUserId() != userId) {
14536            mContext.enforceCallingOrSelfPermission(
14537                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14538        }
14539        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14540            return null;
14541        }
14542        synchronized (mPackages) {
14543            return mSettings.getDefaultBrowserPackageNameLPw(userId);
14544        }
14545    }
14546
14547    /**
14548     * Get the "allow unknown sources" setting.
14549     *
14550     * @return the current "allow unknown sources" setting
14551     */
14552    private int getUnknownSourcesSettings() {
14553        return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14554                android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14555                -1);
14556    }
14557
14558    @Override
14559    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14560        final int callingUid = Binder.getCallingUid();
14561        if (getInstantAppPackageName(callingUid) != null) {
14562            return;
14563        }
14564        // writer
14565        synchronized (mPackages) {
14566            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14567            if (targetPackageSetting == null
14568                    || filterAppAccessLPr(
14569                            targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14570                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14571            }
14572
14573            PackageSetting installerPackageSetting;
14574            if (installerPackageName != null) {
14575                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14576                if (installerPackageSetting == null) {
14577                    throw new IllegalArgumentException("Unknown installer package: "
14578                            + installerPackageName);
14579                }
14580            } else {
14581                installerPackageSetting = null;
14582            }
14583
14584            Signature[] callerSignature;
14585            Object obj = mSettings.getUserIdLPr(callingUid);
14586            if (obj != null) {
14587                if (obj instanceof SharedUserSetting) {
14588                    callerSignature =
14589                            ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14590                } else if (obj instanceof PackageSetting) {
14591                    callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14592                } else {
14593                    throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14594                }
14595            } else {
14596                throw new SecurityException("Unknown calling UID: " + callingUid);
14597            }
14598
14599            // Verify: can't set installerPackageName to a package that is
14600            // not signed with the same cert as the caller.
14601            if (installerPackageSetting != null) {
14602                if (compareSignatures(callerSignature,
14603                        installerPackageSetting.signatures.mSigningDetails.signatures)
14604                        != PackageManager.SIGNATURE_MATCH) {
14605                    throw new SecurityException(
14606                            "Caller does not have same cert as new installer package "
14607                            + installerPackageName);
14608                }
14609            }
14610
14611            // Verify: if target already has an installer package, it must
14612            // be signed with the same cert as the caller.
14613            if (targetPackageSetting.installerPackageName != null) {
14614                PackageSetting setting = mSettings.mPackages.get(
14615                        targetPackageSetting.installerPackageName);
14616                // If the currently set package isn't valid, then it's always
14617                // okay to change it.
14618                if (setting != null) {
14619                    if (compareSignatures(callerSignature,
14620                            setting.signatures.mSigningDetails.signatures)
14621                            != PackageManager.SIGNATURE_MATCH) {
14622                        throw new SecurityException(
14623                                "Caller does not have same cert as old installer package "
14624                                + targetPackageSetting.installerPackageName);
14625                    }
14626                }
14627            }
14628
14629            // Okay!
14630            targetPackageSetting.installerPackageName = installerPackageName;
14631            if (installerPackageName != null) {
14632                mSettings.mInstallerPackages.add(installerPackageName);
14633            }
14634            scheduleWriteSettingsLocked();
14635        }
14636    }
14637
14638    @Override
14639    public void setApplicationCategoryHint(String packageName, int categoryHint,
14640            String callerPackageName) {
14641        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14642            throw new SecurityException("Instant applications don't have access to this method");
14643        }
14644        mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14645                callerPackageName);
14646        synchronized (mPackages) {
14647            PackageSetting ps = mSettings.mPackages.get(packageName);
14648            if (ps == null) {
14649                throw new IllegalArgumentException("Unknown target package " + packageName);
14650            }
14651            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14652                throw new IllegalArgumentException("Unknown target package " + packageName);
14653            }
14654            if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14655                throw new IllegalArgumentException("Calling package " + callerPackageName
14656                        + " is not installer for " + packageName);
14657            }
14658
14659            if (ps.categoryHint != categoryHint) {
14660                ps.categoryHint = categoryHint;
14661                scheduleWriteSettingsLocked();
14662            }
14663        }
14664    }
14665
14666    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14667        // Queue up an async operation since the package installation may take a little while.
14668        mHandler.post(new Runnable() {
14669            public void run() {
14670                mHandler.removeCallbacks(this);
14671                 // Result object to be returned
14672                PackageInstalledInfo res = new PackageInstalledInfo();
14673                res.setReturnCode(currentStatus);
14674                res.uid = -1;
14675                res.pkg = null;
14676                res.removedInfo = null;
14677                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
14678                    args.doPreInstall(res.returnCode);
14679                    synchronized (mInstallLock) {
14680                        installPackageTracedLI(args, res);
14681                    }
14682                    args.doPostInstall(res.returnCode, res.uid);
14683                }
14684
14685                // A restore should be performed at this point if (a) the install
14686                // succeeded, (b) the operation is not an update, and (c) the new
14687                // package has not opted out of backup participation.
14688                final boolean update = res.removedInfo != null
14689                        && res.removedInfo.removedPackage != null;
14690                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14691                boolean doRestore = !update
14692                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14693
14694                // Set up the post-install work request bookkeeping.  This will be used
14695                // and cleaned up by the post-install event handling regardless of whether
14696                // there's a restore pass performed.  Token values are >= 1.
14697                int token;
14698                if (mNextInstallToken < 0) mNextInstallToken = 1;
14699                token = mNextInstallToken++;
14700
14701                PostInstallData data = new PostInstallData(args, res);
14702                mRunningInstalls.put(token, data);
14703                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14704
14705                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14706                    // Pass responsibility to the Backup Manager.  It will perform a
14707                    // restore if appropriate, then pass responsibility back to the
14708                    // Package Manager to run the post-install observer callbacks
14709                    // and broadcasts.
14710                    IBackupManager bm = IBackupManager.Stub.asInterface(
14711                            ServiceManager.getService(Context.BACKUP_SERVICE));
14712                    if (bm != null) {
14713                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
14714                                + " to BM for possible restore");
14715                        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14716                        try {
14717                            // TODO: http://b/22388012
14718                            if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) {
14719                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
14720                            } else {
14721                                doRestore = false;
14722                            }
14723                        } catch (RemoteException e) {
14724                            // can't happen; the backup manager is local
14725                        } catch (Exception e) {
14726                            Slog.e(TAG, "Exception trying to enqueue restore", e);
14727                            doRestore = false;
14728                        }
14729                    } else {
14730                        Slog.e(TAG, "Backup Manager not found!");
14731                        doRestore = false;
14732                    }
14733                }
14734
14735                if (!doRestore) {
14736                    // No restore possible, or the Backup Manager was mysteriously not
14737                    // available -- just fire the post-install work request directly.
14738                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14739
14740                    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14741
14742                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14743                    mHandler.sendMessage(msg);
14744                }
14745            }
14746        });
14747    }
14748
14749    /**
14750     * Callback from PackageSettings whenever an app is first transitioned out of the
14751     * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14752     * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14753     * here whether the app is the target of an ongoing install, and only send the
14754     * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14755     * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14756     * handling.
14757     */
14758    void notifyFirstLaunch(final String packageName, final String installerPackage,
14759            final int userId) {
14760        // Serialize this with the rest of the install-process message chain.  In the
14761        // restore-at-install case, this Runnable will necessarily run before the
14762        // POST_INSTALL message is processed, so the contents of mRunningInstalls
14763        // are coherent.  In the non-restore case, the app has already completed install
14764        // and been launched through some other means, so it is not in a problematic
14765        // state for observers to see the FIRST_LAUNCH signal.
14766        mHandler.post(new Runnable() {
14767            @Override
14768            public void run() {
14769                for (int i = 0; i < mRunningInstalls.size(); i++) {
14770                    final PostInstallData data = mRunningInstalls.valueAt(i);
14771                    if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14772                        continue;
14773                    }
14774                    if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14775                        // right package; but is it for the right user?
14776                        for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14777                            if (userId == data.res.newUsers[uIndex]) {
14778                                if (DEBUG_BACKUP) {
14779                                    Slog.i(TAG, "Package " + packageName
14780                                            + " being restored so deferring FIRST_LAUNCH");
14781                                }
14782                                return;
14783                            }
14784                        }
14785                    }
14786                }
14787                // didn't find it, so not being restored
14788                if (DEBUG_BACKUP) {
14789                    Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14790                }
14791                final boolean isInstantApp = isInstantApp(packageName, userId);
14792                final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14793                final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14794                sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14795            }
14796        });
14797    }
14798
14799    private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14800            int[] userIds, int[] instantUserIds) {
14801        sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14802                installerPkg, null, userIds, instantUserIds);
14803    }
14804
14805    private abstract class HandlerParams {
14806        private static final int MAX_RETRIES = 4;
14807
14808        /**
14809         * Number of times startCopy() has been attempted and had a non-fatal
14810         * error.
14811         */
14812        private int mRetries = 0;
14813
14814        /** User handle for the user requesting the information or installation. */
14815        private final UserHandle mUser;
14816        String traceMethod;
14817        int traceCookie;
14818
14819        HandlerParams(UserHandle user) {
14820            mUser = user;
14821        }
14822
14823        UserHandle getUser() {
14824            return mUser;
14825        }
14826
14827        HandlerParams setTraceMethod(String traceMethod) {
14828            this.traceMethod = traceMethod;
14829            return this;
14830        }
14831
14832        HandlerParams setTraceCookie(int traceCookie) {
14833            this.traceCookie = traceCookie;
14834            return this;
14835        }
14836
14837        final boolean startCopy() {
14838            boolean res;
14839            try {
14840                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14841
14842                if (++mRetries > MAX_RETRIES) {
14843                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
14844                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
14845                    handleServiceError();
14846                    return false;
14847                } else {
14848                    handleStartCopy();
14849                    res = true;
14850                }
14851            } catch (RemoteException e) {
14852                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
14853                mHandler.sendEmptyMessage(MCS_RECONNECT);
14854                res = false;
14855            }
14856            handleReturnCode();
14857            return res;
14858        }
14859
14860        final void serviceError() {
14861            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
14862            handleServiceError();
14863            handleReturnCode();
14864        }
14865
14866        abstract void handleStartCopy() throws RemoteException;
14867        abstract void handleServiceError();
14868        abstract void handleReturnCode();
14869    }
14870
14871    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
14872        for (File path : paths) {
14873            try {
14874                mcs.clearDirectory(path.getAbsolutePath());
14875            } catch (RemoteException e) {
14876            }
14877        }
14878    }
14879
14880    static class OriginInfo {
14881        /**
14882         * Location where install is coming from, before it has been
14883         * copied/renamed into place. This could be a single monolithic APK
14884         * file, or a cluster directory. This location may be untrusted.
14885         */
14886        final File file;
14887
14888        /**
14889         * Flag indicating that {@link #file} or {@link #cid} has already been
14890         * staged, meaning downstream users don't need to defensively copy the
14891         * contents.
14892         */
14893        final boolean staged;
14894
14895        /**
14896         * Flag indicating that {@link #file} or {@link #cid} is an already
14897         * installed app that is being moved.
14898         */
14899        final boolean existing;
14900
14901        final String resolvedPath;
14902        final File resolvedFile;
14903
14904        static OriginInfo fromNothing() {
14905            return new OriginInfo(null, false, false);
14906        }
14907
14908        static OriginInfo fromUntrustedFile(File file) {
14909            return new OriginInfo(file, false, false);
14910        }
14911
14912        static OriginInfo fromExistingFile(File file) {
14913            return new OriginInfo(file, false, true);
14914        }
14915
14916        static OriginInfo fromStagedFile(File file) {
14917            return new OriginInfo(file, true, false);
14918        }
14919
14920        private OriginInfo(File file, boolean staged, boolean existing) {
14921            this.file = file;
14922            this.staged = staged;
14923            this.existing = existing;
14924
14925            if (file != null) {
14926                resolvedPath = file.getAbsolutePath();
14927                resolvedFile = file;
14928            } else {
14929                resolvedPath = null;
14930                resolvedFile = null;
14931            }
14932        }
14933    }
14934
14935    static class MoveInfo {
14936        final int moveId;
14937        final String fromUuid;
14938        final String toUuid;
14939        final String packageName;
14940        final String dataAppName;
14941        final int appId;
14942        final String seinfo;
14943        final int targetSdkVersion;
14944
14945        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14946                String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14947            this.moveId = moveId;
14948            this.fromUuid = fromUuid;
14949            this.toUuid = toUuid;
14950            this.packageName = packageName;
14951            this.dataAppName = dataAppName;
14952            this.appId = appId;
14953            this.seinfo = seinfo;
14954            this.targetSdkVersion = targetSdkVersion;
14955        }
14956    }
14957
14958    static class VerificationInfo {
14959        /** A constant used to indicate that a uid value is not present. */
14960        public static final int NO_UID = -1;
14961
14962        /** URI referencing where the package was downloaded from. */
14963        final Uri originatingUri;
14964
14965        /** HTTP referrer URI associated with the originatingURI. */
14966        final Uri referrer;
14967
14968        /** UID of the application that the install request originated from. */
14969        final int originatingUid;
14970
14971        /** UID of application requesting the install */
14972        final int installerUid;
14973
14974        VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14975            this.originatingUri = originatingUri;
14976            this.referrer = referrer;
14977            this.originatingUid = originatingUid;
14978            this.installerUid = installerUid;
14979        }
14980    }
14981
14982    class InstallParams extends HandlerParams {
14983        final OriginInfo origin;
14984        final MoveInfo move;
14985        final IPackageInstallObserver2 observer;
14986        int installFlags;
14987        final String installerPackageName;
14988        final String volumeUuid;
14989        private InstallArgs mArgs;
14990        private int mRet;
14991        final String packageAbiOverride;
14992        final String[] grantedRuntimePermissions;
14993        final VerificationInfo verificationInfo;
14994        final PackageParser.SigningDetails signingDetails;
14995        final int installReason;
14996
14997        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
14998                int installFlags, String installerPackageName, String volumeUuid,
14999                VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15000                String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) {
15001            super(user);
15002            this.origin = origin;
15003            this.move = move;
15004            this.observer = observer;
15005            this.installFlags = installFlags;
15006            this.installerPackageName = installerPackageName;
15007            this.volumeUuid = volumeUuid;
15008            this.verificationInfo = verificationInfo;
15009            this.packageAbiOverride = packageAbiOverride;
15010            this.grantedRuntimePermissions = grantedPermissions;
15011            this.signingDetails = signingDetails;
15012            this.installReason = installReason;
15013        }
15014
15015        @Override
15016        public String toString() {
15017            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15018                    + " file=" + origin.file + "}";
15019        }
15020
15021        private int installLocationPolicy(PackageInfoLite pkgLite) {
15022            String packageName = pkgLite.packageName;
15023            int installLocation = pkgLite.installLocation;
15024            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15025            // reader
15026            synchronized (mPackages) {
15027                // Currently installed package which the new package is attempting to replace or
15028                // null if no such package is installed.
15029                PackageParser.Package installedPkg = mPackages.get(packageName);
15030                // Package which currently owns the data which the new package will own if installed.
15031                // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15032                // will be null whereas dataOwnerPkg will contain information about the package
15033                // which was uninstalled while keeping its data.
15034                PackageParser.Package dataOwnerPkg = installedPkg;
15035                if (dataOwnerPkg  == null) {
15036                    PackageSetting ps = mSettings.mPackages.get(packageName);
15037                    if (ps != null) {
15038                        dataOwnerPkg = ps.pkg;
15039                    }
15040                }
15041
15042                if (dataOwnerPkg != null) {
15043                    // If installed, the package will get access to data left on the device by its
15044                    // predecessor. As a security measure, this is permited only if this is not a
15045                    // version downgrade or if the predecessor package is marked as debuggable and
15046                    // a downgrade is explicitly requested.
15047                    //
15048                    // On debuggable platform builds, downgrades are permitted even for
15049                    // non-debuggable packages to make testing easier. Debuggable platform builds do
15050                    // not offer security guarantees and thus it's OK to disable some security
15051                    // mechanisms to make debugging/testing easier on those builds. However, even on
15052                    // debuggable builds downgrades of packages are permitted only if requested via
15053                    // installFlags. This is because we aim to keep the behavior of debuggable
15054                    // platform builds as close as possible to the behavior of non-debuggable
15055                    // platform builds.
15056                    final boolean downgradeRequested =
15057                            (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0;
15058                    final boolean packageDebuggable =
15059                                (dataOwnerPkg.applicationInfo.flags
15060                                        & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
15061                    final boolean downgradePermitted =
15062                            (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable));
15063                    if (!downgradePermitted) {
15064                        try {
15065                            checkDowngrade(dataOwnerPkg, pkgLite);
15066                        } catch (PackageManagerException e) {
15067                            Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15068                            return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15069                        }
15070                    }
15071                }
15072
15073                if (installedPkg != null) {
15074                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15075                        // Check for updated system application.
15076                        if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15077                            if (onSd) {
15078                                Slog.w(TAG, "Cannot install update to system app on sdcard");
15079                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
15080                            }
15081                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15082                        } else {
15083                            if (onSd) {
15084                                // Install flag overrides everything.
15085                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15086                            }
15087                            // If current upgrade specifies particular preference
15088                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15089                                // Application explicitly specified internal.
15090                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15091                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15092                                // App explictly prefers external. Let policy decide
15093                            } else {
15094                                // Prefer previous location
15095                                if (isExternal(installedPkg)) {
15096                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15097                                }
15098                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15099                            }
15100                        }
15101                    } else {
15102                        // Invalid install. Return error code
15103                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15104                    }
15105                }
15106            }
15107            // All the special cases have been taken care of.
15108            // Return result based on recommended install location.
15109            if (onSd) {
15110                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15111            }
15112            return pkgLite.recommendedInstallLocation;
15113        }
15114
15115        /*
15116         * Invoke remote method to get package information and install
15117         * location values. Override install location based on default
15118         * policy if needed and then create install arguments based
15119         * on the install location.
15120         */
15121        public void handleStartCopy() throws RemoteException {
15122            int ret = PackageManager.INSTALL_SUCCEEDED;
15123
15124            // If we're already staged, we've firmly committed to an install location
15125            if (origin.staged) {
15126                if (origin.file != null) {
15127                    installFlags |= PackageManager.INSTALL_INTERNAL;
15128                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15129                } else {
15130                    throw new IllegalStateException("Invalid stage location");
15131                }
15132            }
15133
15134            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15135            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15136            final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15137            PackageInfoLite pkgLite = null;
15138
15139            if (onInt && onSd) {
15140                // Check if both bits are set.
15141                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
15142                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15143            } else if (onSd && ephemeral) {
15144                Slog.w(TAG,  "Conflicting flags specified for installing ephemeral on external");
15145                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15146            } else {
15147                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
15148                        packageAbiOverride);
15149
15150                if (DEBUG_INSTANT && ephemeral) {
15151                    Slog.v(TAG, "pkgLite for install: " + pkgLite);
15152                }
15153
15154                /*
15155                 * If we have too little free space, try to free cache
15156                 * before giving up.
15157                 */
15158                if (!origin.staged && pkgLite.recommendedInstallLocation
15159                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15160                    // TODO: focus freeing disk space on the target device
15161                    final StorageManager storage = StorageManager.from(mContext);
15162                    final long lowThreshold = storage.getStorageLowBytes(
15163                            Environment.getDataDirectory());
15164
15165                    final long sizeBytes = mContainerService.calculateInstalledSize(
15166                            origin.resolvedPath, packageAbiOverride);
15167
15168                    try {
15169                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15170                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
15171                                installFlags, packageAbiOverride);
15172                    } catch (InstallerException e) {
15173                        Slog.w(TAG, "Failed to free cache", e);
15174                    }
15175
15176                    /*
15177                     * The cache free must have deleted the file we
15178                     * downloaded to install.
15179                     *
15180                     * TODO: fix the "freeCache" call to not delete
15181                     *       the file we care about.
15182                     */
15183                    if (pkgLite.recommendedInstallLocation
15184                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15185                        pkgLite.recommendedInstallLocation
15186                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15187                    }
15188                }
15189            }
15190
15191            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15192                int loc = pkgLite.recommendedInstallLocation;
15193                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15194                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15195                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15196                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15197                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15198                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15199                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15200                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15201                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15202                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15203                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15204                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15205                } else {
15206                    // Override with defaults if needed.
15207                    loc = installLocationPolicy(pkgLite);
15208                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15209                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15210                    } else if (!onSd && !onInt) {
15211                        // Override install location with flags
15212                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15213                            // Set the flag to install on external media.
15214                            installFlags |= PackageManager.INSTALL_EXTERNAL;
15215                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
15216                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15217                            if (DEBUG_INSTANT) {
15218                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15219                            }
15220                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
15221                            installFlags &= ~(PackageManager.INSTALL_EXTERNAL
15222                                    |PackageManager.INSTALL_INTERNAL);
15223                        } else {
15224                            // Make sure the flag for installing on external
15225                            // media is unset
15226                            installFlags |= PackageManager.INSTALL_INTERNAL;
15227                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
15228                        }
15229                    }
15230                }
15231            }
15232
15233            final InstallArgs args = createInstallArgs(this);
15234            mArgs = args;
15235
15236            if (ret == PackageManager.INSTALL_SUCCEEDED) {
15237                // TODO: http://b/22976637
15238                // Apps installed for "all" users use the device owner to verify the app
15239                UserHandle verifierUser = getUser();
15240                if (verifierUser == UserHandle.ALL) {
15241                    verifierUser = UserHandle.SYSTEM;
15242                }
15243
15244                /*
15245                 * Determine if we have any installed package verifiers. If we
15246                 * do, then we'll defer to them to verify the packages.
15247                 */
15248                final int requiredUid = mRequiredVerifierPackage == null ? -1
15249                        : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15250                                verifierUser.getIdentifier());
15251                final int installerUid =
15252                        verificationInfo == null ? -1 : verificationInfo.installerUid;
15253                if (!origin.existing && requiredUid != -1
15254                        && isVerificationEnabled(
15255                                verifierUser.getIdentifier(), installFlags, installerUid)) {
15256                    final Intent verification = new Intent(
15257                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15258                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15259                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15260                            PACKAGE_MIME_TYPE);
15261                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15262
15263                    // Query all live verifiers based on current user state
15264                    final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15265                            PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15266                            false /*allowDynamicSplits*/);
15267
15268                    if (DEBUG_VERIFY) {
15269                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15270                                + verification.toString() + " with " + pkgLite.verifiers.length
15271                                + " optional verifiers");
15272                    }
15273
15274                    final int verificationId = mPendingVerificationToken++;
15275
15276                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15277
15278                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15279                            installerPackageName);
15280
15281                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15282                            installFlags);
15283
15284                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15285                            pkgLite.packageName);
15286
15287                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15288                            pkgLite.versionCode);
15289
15290                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15291                            pkgLite.getLongVersionCode());
15292
15293                    if (verificationInfo != null) {
15294                        if (verificationInfo.originatingUri != null) {
15295                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15296                                    verificationInfo.originatingUri);
15297                        }
15298                        if (verificationInfo.referrer != null) {
15299                            verification.putExtra(Intent.EXTRA_REFERRER,
15300                                    verificationInfo.referrer);
15301                        }
15302                        if (verificationInfo.originatingUid >= 0) {
15303                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15304                                    verificationInfo.originatingUid);
15305                        }
15306                        if (verificationInfo.installerUid >= 0) {
15307                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15308                                    verificationInfo.installerUid);
15309                        }
15310                    }
15311
15312                    final PackageVerificationState verificationState = new PackageVerificationState(
15313                            requiredUid, args);
15314
15315                    mPendingVerification.append(verificationId, verificationState);
15316
15317                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15318                            receivers, verificationState);
15319
15320                    DeviceIdleController.LocalService idleController = getDeviceIdleController();
15321                    final long idleDuration = getVerificationTimeout();
15322
15323                    /*
15324                     * If any sufficient verifiers were listed in the package
15325                     * manifest, attempt to ask them.
15326                     */
15327                    if (sufficientVerifiers != null) {
15328                        final int N = sufficientVerifiers.size();
15329                        if (N == 0) {
15330                            Slog.i(TAG, "Additional verifiers required, but none installed.");
15331                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15332                        } else {
15333                            for (int i = 0; i < N; i++) {
15334                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
15335                                idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15336                                        verifierComponent.getPackageName(), idleDuration,
15337                                        verifierUser.getIdentifier(), false, "package verifier");
15338
15339                                final Intent sufficientIntent = new Intent(verification);
15340                                sufficientIntent.setComponent(verifierComponent);
15341                                mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15342                            }
15343                        }
15344                    }
15345
15346                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15347                            mRequiredVerifierPackage, receivers);
15348                    if (ret == PackageManager.INSTALL_SUCCEEDED
15349                            && mRequiredVerifierPackage != null) {
15350                        Trace.asyncTraceBegin(
15351                                TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15352                        /*
15353                         * Send the intent to the required verification agent,
15354                         * but only start the verification timeout after the
15355                         * target BroadcastReceivers have run.
15356                         */
15357                        verification.setComponent(requiredVerifierComponent);
15358                        idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15359                                mRequiredVerifierPackage, idleDuration,
15360                                verifierUser.getIdentifier(), false, "package verifier");
15361                        mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15362                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15363                                new BroadcastReceiver() {
15364                                    @Override
15365                                    public void onReceive(Context context, Intent intent) {
15366                                        final Message msg = mHandler
15367                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
15368                                        msg.arg1 = verificationId;
15369                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15370                                    }
15371                                }, null, 0, null, null);
15372
15373                        /*
15374                         * We don't want the copy to proceed until verification
15375                         * succeeds, so null out this field.
15376                         */
15377                        mArgs = null;
15378                    }
15379                } else {
15380                    /*
15381                     * No package verification is enabled, so immediately start
15382                     * the remote call to initiate copy using temporary file.
15383                     */
15384                    ret = args.copyApk(mContainerService, true);
15385                }
15386            }
15387
15388            mRet = ret;
15389        }
15390
15391        @Override
15392        void handleReturnCode() {
15393            // If mArgs is null, then MCS couldn't be reached. When it
15394            // reconnects, it will try again to install. At that point, this
15395            // will succeed.
15396            if (mArgs != null) {
15397                processPendingInstall(mArgs, mRet);
15398            }
15399        }
15400
15401        @Override
15402        void handleServiceError() {
15403            mArgs = createInstallArgs(this);
15404            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15405        }
15406    }
15407
15408    private InstallArgs createInstallArgs(InstallParams params) {
15409        if (params.move != null) {
15410            return new MoveInstallArgs(params);
15411        } else {
15412            return new FileInstallArgs(params);
15413        }
15414    }
15415
15416    /**
15417     * Create args that describe an existing installed package. Typically used
15418     * when cleaning up old installs, or used as a move source.
15419     */
15420    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
15421            String resourcePath, String[] instructionSets) {
15422        return new FileInstallArgs(codePath, resourcePath, instructionSets);
15423    }
15424
15425    static abstract class InstallArgs {
15426        /** @see InstallParams#origin */
15427        final OriginInfo origin;
15428        /** @see InstallParams#move */
15429        final MoveInfo move;
15430
15431        final IPackageInstallObserver2 observer;
15432        // Always refers to PackageManager flags only
15433        final int installFlags;
15434        final String installerPackageName;
15435        final String volumeUuid;
15436        final UserHandle user;
15437        final String abiOverride;
15438        final String[] installGrantPermissions;
15439        /** If non-null, drop an async trace when the install completes */
15440        final String traceMethod;
15441        final int traceCookie;
15442        final PackageParser.SigningDetails signingDetails;
15443        final int installReason;
15444
15445        // The list of instruction sets supported by this app. This is currently
15446        // only used during the rmdex() phase to clean up resources. We can get rid of this
15447        // if we move dex files under the common app path.
15448        /* nullable */ String[] instructionSets;
15449
15450        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15451                int installFlags, String installerPackageName, String volumeUuid,
15452                UserHandle user, String[] instructionSets,
15453                String abiOverride, String[] installGrantPermissions,
15454                String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails,
15455                int installReason) {
15456            this.origin = origin;
15457            this.move = move;
15458            this.installFlags = installFlags;
15459            this.observer = observer;
15460            this.installerPackageName = installerPackageName;
15461            this.volumeUuid = volumeUuid;
15462            this.user = user;
15463            this.instructionSets = instructionSets;
15464            this.abiOverride = abiOverride;
15465            this.installGrantPermissions = installGrantPermissions;
15466            this.traceMethod = traceMethod;
15467            this.traceCookie = traceCookie;
15468            this.signingDetails = signingDetails;
15469            this.installReason = installReason;
15470        }
15471
15472        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
15473        abstract int doPreInstall(int status);
15474
15475        /**
15476         * Rename package into final resting place. All paths on the given
15477         * scanned package should be updated to reflect the rename.
15478         */
15479        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
15480        abstract int doPostInstall(int status, int uid);
15481
15482        /** @see PackageSettingBase#codePathString */
15483        abstract String getCodePath();
15484        /** @see PackageSettingBase#resourcePathString */
15485        abstract String getResourcePath();
15486
15487        // Need installer lock especially for dex file removal.
15488        abstract void cleanUpResourcesLI();
15489        abstract boolean doPostDeleteLI(boolean delete);
15490
15491        /**
15492         * Called before the source arguments are copied. This is used mostly
15493         * for MoveParams when it needs to read the source file to put it in the
15494         * destination.
15495         */
15496        int doPreCopy() {
15497            return PackageManager.INSTALL_SUCCEEDED;
15498        }
15499
15500        /**
15501         * Called after the source arguments are copied. This is used mostly for
15502         * MoveParams when it needs to read the source file to put it in the
15503         * destination.
15504         */
15505        int doPostCopy(int uid) {
15506            return PackageManager.INSTALL_SUCCEEDED;
15507        }
15508
15509        protected boolean isFwdLocked() {
15510            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
15511        }
15512
15513        protected boolean isExternalAsec() {
15514            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
15515        }
15516
15517        protected boolean isEphemeral() {
15518            return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15519        }
15520
15521        UserHandle getUser() {
15522            return user;
15523        }
15524    }
15525
15526    void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15527        if (!allCodePaths.isEmpty()) {
15528            if (instructionSets == null) {
15529                throw new IllegalStateException("instructionSet == null");
15530            }
15531            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15532            for (String codePath : allCodePaths) {
15533                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15534                    try {
15535                        mInstaller.rmdex(codePath, dexCodeInstructionSet);
15536                    } catch (InstallerException ignored) {
15537                    }
15538                }
15539            }
15540        }
15541    }
15542
15543    /**
15544     * Logic to handle installation of non-ASEC applications, including copying
15545     * and renaming logic.
15546     */
15547    class FileInstallArgs extends InstallArgs {
15548        private File codeFile;
15549        private File resourceFile;
15550
15551        // Example topology:
15552        // /data/app/com.example/base.apk
15553        // /data/app/com.example/split_foo.apk
15554        // /data/app/com.example/lib/arm/libfoo.so
15555        // /data/app/com.example/lib/arm64/libfoo.so
15556        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15557
15558        /** New install */
15559        FileInstallArgs(InstallParams params) {
15560            super(params.origin, params.move, params.observer, params.installFlags,
15561                    params.installerPackageName, params.volumeUuid,
15562                    params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15563                    params.grantedRuntimePermissions,
15564                    params.traceMethod, params.traceCookie, params.signingDetails,
15565                    params.installReason);
15566            if (isFwdLocked()) {
15567                throw new IllegalArgumentException("Forward locking only supported in ASEC");
15568            }
15569        }
15570
15571        /** Existing install */
15572        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15573            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15574                    null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15575                    PackageManager.INSTALL_REASON_UNKNOWN);
15576            this.codeFile = (codePath != null) ? new File(codePath) : null;
15577            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15578        }
15579
15580        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15581            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15582            try {
15583                return doCopyApk(imcs, temp);
15584            } finally {
15585                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15586            }
15587        }
15588
15589        private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
15590            if (origin.staged) {
15591                if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15592                codeFile = origin.file;
15593                resourceFile = origin.file;
15594                return PackageManager.INSTALL_SUCCEEDED;
15595            }
15596
15597            try {
15598                final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15599                final File tempDir =
15600                        mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15601                codeFile = tempDir;
15602                resourceFile = tempDir;
15603            } catch (IOException e) {
15604                Slog.w(TAG, "Failed to create copy file: " + e);
15605                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15606            }
15607
15608            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
15609                @Override
15610                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
15611                    if (!FileUtils.isValidExtFilename(name)) {
15612                        throw new IllegalArgumentException("Invalid filename: " + name);
15613                    }
15614                    try {
15615                        final File file = new File(codeFile, name);
15616                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
15617                                O_RDWR | O_CREAT, 0644);
15618                        Os.chmod(file.getAbsolutePath(), 0644);
15619                        return new ParcelFileDescriptor(fd);
15620                    } catch (ErrnoException e) {
15621                        throw new RemoteException("Failed to open: " + e.getMessage());
15622                    }
15623                }
15624            };
15625
15626            int ret = PackageManager.INSTALL_SUCCEEDED;
15627            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
15628            if (ret != PackageManager.INSTALL_SUCCEEDED) {
15629                Slog.e(TAG, "Failed to copy package");
15630                return ret;
15631            }
15632
15633            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15634            NativeLibraryHelper.Handle handle = null;
15635            try {
15636                handle = NativeLibraryHelper.Handle.create(codeFile);
15637                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15638                        abiOverride);
15639            } catch (IOException e) {
15640                Slog.e(TAG, "Copying native libraries failed", e);
15641                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15642            } finally {
15643                IoUtils.closeQuietly(handle);
15644            }
15645
15646            return ret;
15647        }
15648
15649        int doPreInstall(int status) {
15650            if (status != PackageManager.INSTALL_SUCCEEDED) {
15651                cleanUp();
15652            }
15653            return status;
15654        }
15655
15656        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15657            if (status != PackageManager.INSTALL_SUCCEEDED) {
15658                cleanUp();
15659                return false;
15660            }
15661
15662            final File targetDir = codeFile.getParentFile();
15663            final File beforeCodeFile = codeFile;
15664            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15665
15666            if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15667            try {
15668                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15669            } catch (ErrnoException e) {
15670                Slog.w(TAG, "Failed to rename", e);
15671                return false;
15672            }
15673
15674            if (!SELinux.restoreconRecursive(afterCodeFile)) {
15675                Slog.w(TAG, "Failed to restorecon");
15676                return false;
15677            }
15678
15679            // Reflect the rename internally
15680            codeFile = afterCodeFile;
15681            resourceFile = afterCodeFile;
15682
15683            // Reflect the rename in scanned details
15684            try {
15685                pkg.setCodePath(afterCodeFile.getCanonicalPath());
15686            } catch (IOException e) {
15687                Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15688                return false;
15689            }
15690            pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15691                    afterCodeFile, pkg.baseCodePath));
15692            pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15693                    afterCodeFile, pkg.splitCodePaths));
15694
15695            // Reflect the rename in app info
15696            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15697            pkg.setApplicationInfoCodePath(pkg.codePath);
15698            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15699            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15700            pkg.setApplicationInfoResourcePath(pkg.codePath);
15701            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15702            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15703
15704            return true;
15705        }
15706
15707        int doPostInstall(int status, int uid) {
15708            if (status != PackageManager.INSTALL_SUCCEEDED) {
15709                cleanUp();
15710            }
15711            return status;
15712        }
15713
15714        @Override
15715        String getCodePath() {
15716            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15717        }
15718
15719        @Override
15720        String getResourcePath() {
15721            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15722        }
15723
15724        private boolean cleanUp() {
15725            if (codeFile == null || !codeFile.exists()) {
15726                return false;
15727            }
15728
15729            removeCodePathLI(codeFile);
15730
15731            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15732                resourceFile.delete();
15733            }
15734
15735            return true;
15736        }
15737
15738        void cleanUpResourcesLI() {
15739            // Try enumerating all code paths before deleting
15740            List<String> allCodePaths = Collections.EMPTY_LIST;
15741            if (codeFile != null && codeFile.exists()) {
15742                try {
15743                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15744                    allCodePaths = pkg.getAllCodePaths();
15745                } catch (PackageParserException e) {
15746                    // Ignored; we tried our best
15747                }
15748            }
15749
15750            cleanUp();
15751            removeDexFiles(allCodePaths, instructionSets);
15752        }
15753
15754        boolean doPostDeleteLI(boolean delete) {
15755            // XXX err, shouldn't we respect the delete flag?
15756            cleanUpResourcesLI();
15757            return true;
15758        }
15759    }
15760
15761    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15762            PackageManagerException {
15763        if (copyRet < 0) {
15764            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15765                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15766                throw new PackageManagerException(copyRet, message);
15767            }
15768        }
15769    }
15770
15771    /**
15772     * Extract the StorageManagerService "container ID" from the full code path of an
15773     * .apk.
15774     */
15775    static String cidFromCodePath(String fullCodePath) {
15776        int eidx = fullCodePath.lastIndexOf("/");
15777        String subStr1 = fullCodePath.substring(0, eidx);
15778        int sidx = subStr1.lastIndexOf("/");
15779        return subStr1.substring(sidx+1, eidx);
15780    }
15781
15782    /**
15783     * Logic to handle movement of existing installed applications.
15784     */
15785    class MoveInstallArgs extends InstallArgs {
15786        private File codeFile;
15787        private File resourceFile;
15788
15789        /** New install */
15790        MoveInstallArgs(InstallParams params) {
15791            super(params.origin, params.move, params.observer, params.installFlags,
15792                    params.installerPackageName, params.volumeUuid,
15793                    params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15794                    params.grantedRuntimePermissions,
15795                    params.traceMethod, params.traceCookie, params.signingDetails,
15796                    params.installReason);
15797        }
15798
15799        int copyApk(IMediaContainerService imcs, boolean temp) {
15800            if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15801                    + move.fromUuid + " to " + move.toUuid);
15802            synchronized (mInstaller) {
15803                try {
15804                    mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15805                            move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15806                } catch (InstallerException e) {
15807                    Slog.w(TAG, "Failed to move app", e);
15808                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15809                }
15810            }
15811
15812            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15813            resourceFile = codeFile;
15814            if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15815
15816            return PackageManager.INSTALL_SUCCEEDED;
15817        }
15818
15819        int doPreInstall(int status) {
15820            if (status != PackageManager.INSTALL_SUCCEEDED) {
15821                cleanUp(move.toUuid);
15822            }
15823            return status;
15824        }
15825
15826        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
15827            if (status != PackageManager.INSTALL_SUCCEEDED) {
15828                cleanUp(move.toUuid);
15829                return false;
15830            }
15831
15832            // Reflect the move in app info
15833            pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15834            pkg.setApplicationInfoCodePath(pkg.codePath);
15835            pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15836            pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15837            pkg.setApplicationInfoResourcePath(pkg.codePath);
15838            pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15839            pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15840
15841            return true;
15842        }
15843
15844        int doPostInstall(int status, int uid) {
15845            if (status == PackageManager.INSTALL_SUCCEEDED) {
15846                cleanUp(move.fromUuid);
15847            } else {
15848                cleanUp(move.toUuid);
15849            }
15850            return status;
15851        }
15852
15853        @Override
15854        String getCodePath() {
15855            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15856        }
15857
15858        @Override
15859        String getResourcePath() {
15860            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15861        }
15862
15863        private boolean cleanUp(String volumeUuid) {
15864            final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15865                    move.dataAppName);
15866            Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15867            final int[] userIds = sUserManager.getUserIds();
15868            synchronized (mInstallLock) {
15869                // Clean up both app data and code
15870                // All package moves are frozen until finished
15871                for (int userId : userIds) {
15872                    try {
15873                        mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15874                                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15875                    } catch (InstallerException e) {
15876                        Slog.w(TAG, String.valueOf(e));
15877                    }
15878                }
15879                removeCodePathLI(codeFile);
15880            }
15881            return true;
15882        }
15883
15884        void cleanUpResourcesLI() {
15885            throw new UnsupportedOperationException();
15886        }
15887
15888        boolean doPostDeleteLI(boolean delete) {
15889            throw new UnsupportedOperationException();
15890        }
15891    }
15892
15893    static String getAsecPackageName(String packageCid) {
15894        int idx = packageCid.lastIndexOf("-");
15895        if (idx == -1) {
15896            return packageCid;
15897        }
15898        return packageCid.substring(0, idx);
15899    }
15900
15901    // Utility method used to create code paths based on package name and available index.
15902    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
15903        String idxStr = "";
15904        int idx = 1;
15905        // Fall back to default value of idx=1 if prefix is not
15906        // part of oldCodePath
15907        if (oldCodePath != null) {
15908            String subStr = oldCodePath;
15909            // Drop the suffix right away
15910            if (suffix != null && subStr.endsWith(suffix)) {
15911                subStr = subStr.substring(0, subStr.length() - suffix.length());
15912            }
15913            // If oldCodePath already contains prefix find out the
15914            // ending index to either increment or decrement.
15915            int sidx = subStr.lastIndexOf(prefix);
15916            if (sidx != -1) {
15917                subStr = subStr.substring(sidx + prefix.length());
15918                if (subStr != null) {
15919                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
15920                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
15921                    }
15922                    try {
15923                        idx = Integer.parseInt(subStr);
15924                        if (idx <= 1) {
15925                            idx++;
15926                        } else {
15927                            idx--;
15928                        }
15929                    } catch(NumberFormatException e) {
15930                    }
15931                }
15932            }
15933        }
15934        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
15935        return prefix + idxStr;
15936    }
15937
15938    private File getNextCodePath(File targetDir, String packageName) {
15939        File result;
15940        SecureRandom random = new SecureRandom();
15941        byte[] bytes = new byte[16];
15942        do {
15943            random.nextBytes(bytes);
15944            String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
15945            result = new File(targetDir, packageName + "-" + suffix);
15946        } while (result.exists());
15947        return result;
15948    }
15949
15950    // Utility method that returns the relative package path with respect
15951    // to the installation directory. Like say for /data/data/com.test-1.apk
15952    // string com.test-1 is returned.
15953    static String deriveCodePathName(String codePath) {
15954        if (codePath == null) {
15955            return null;
15956        }
15957        final File codeFile = new File(codePath);
15958        final String name = codeFile.getName();
15959        if (codeFile.isDirectory()) {
15960            return name;
15961        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
15962            final int lastDot = name.lastIndexOf('.');
15963            return name.substring(0, lastDot);
15964        } else {
15965            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
15966            return null;
15967        }
15968    }
15969
15970    static class PackageInstalledInfo {
15971        String name;
15972        int uid;
15973        // The set of users that originally had this package installed.
15974        int[] origUsers;
15975        // The set of users that now have this package installed.
15976        int[] newUsers;
15977        PackageParser.Package pkg;
15978        int returnCode;
15979        String returnMsg;
15980        String installerPackageName;
15981        PackageRemovedInfo removedInfo;
15982        ArrayMap<String, PackageInstalledInfo> addedChildPackages;
15983
15984        public void setError(int code, String msg) {
15985            setReturnCode(code);
15986            setReturnMessage(msg);
15987            Slog.w(TAG, msg);
15988        }
15989
15990        public void setError(String msg, PackageParserException e) {
15991            setReturnCode(e.error);
15992            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
15993            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
15994            for (int i = 0; i < childCount; i++) {
15995                addedChildPackages.valueAt(i).setError(msg, e);
15996            }
15997            Slog.w(TAG, msg, e);
15998        }
15999
16000        public void setError(String msg, PackageManagerException e) {
16001            returnCode = e.error;
16002            setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16003            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16004            for (int i = 0; i < childCount; i++) {
16005                addedChildPackages.valueAt(i).setError(msg, e);
16006            }
16007            Slog.w(TAG, msg, e);
16008        }
16009
16010        public void setReturnCode(int returnCode) {
16011            this.returnCode = returnCode;
16012            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16013            for (int i = 0; i < childCount; i++) {
16014                addedChildPackages.valueAt(i).returnCode = returnCode;
16015            }
16016        }
16017
16018        private void setReturnMessage(String returnMsg) {
16019            this.returnMsg = returnMsg;
16020            final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16021            for (int i = 0; i < childCount; i++) {
16022                addedChildPackages.valueAt(i).returnMsg = returnMsg;
16023            }
16024        }
16025
16026        // In some error cases we want to convey more info back to the observer
16027        String origPackage;
16028        String origPermission;
16029    }
16030
16031    /*
16032     * Install a non-existing package.
16033     */
16034    private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16035            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16036            String volumeUuid, PackageInstalledInfo res, int installReason) {
16037        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage");
16038
16039        // Remember this for later, in case we need to rollback this install
16040        String pkgName = pkg.packageName;
16041
16042        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
16043
16044        synchronized(mPackages) {
16045            final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName);
16046            if (renamedPackage != null) {
16047                // A package with the same name is already installed, though
16048                // it has been renamed to an older name.  The package we
16049                // are trying to install should be installed as an update to
16050                // the existing one, but that has not been requested, so bail.
16051                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16052                        + " without first uninstalling package running as "
16053                        + renamedPackage);
16054                return;
16055            }
16056            if (mPackages.containsKey(pkgName)) {
16057                // Don't allow installation over an existing package with the same name.
16058                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
16059                        + " without first uninstalling.");
16060                return;
16061            }
16062        }
16063
16064        try {
16065            PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags,
16066                    System.currentTimeMillis(), user);
16067
16068            updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason);
16069
16070            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16071                prepareAppDataAfterInstallLIF(newPackage);
16072
16073            } else {
16074                // Remove package from internal structures, but keep around any
16075                // data that might have already existed
16076                deletePackageLIF(pkgName, UserHandle.ALL, false, null,
16077                        PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null);
16078            }
16079        } catch (PackageManagerException e) {
16080            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16081        }
16082
16083        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16084    }
16085
16086    private static void updateDigest(MessageDigest digest, File file) throws IOException {
16087        try (DigestInputStream digestStream =
16088                new DigestInputStream(new FileInputStream(file), digest)) {
16089            while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16090        }
16091    }
16092
16093    private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags,
16094            final @ScanFlags int scanFlags, UserHandle user, String installerPackageName,
16095            PackageInstalledInfo res, int installReason) {
16096        final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16097
16098        final PackageParser.Package oldPackage;
16099        final PackageSetting ps;
16100        final String pkgName = pkg.packageName;
16101        final int[] allUsers;
16102        final int[] installedUsers;
16103
16104        synchronized(mPackages) {
16105            oldPackage = mPackages.get(pkgName);
16106            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
16107
16108            // don't allow upgrade to target a release SDK from a pre-release SDK
16109            final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion
16110                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16111            final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion
16112                    == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT;
16113            if (oldTargetsPreRelease
16114                    && !newTargetsPreRelease
16115                    && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) {
16116                Slog.w(TAG, "Can't install package targeting released sdk");
16117                res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE);
16118                return;
16119            }
16120
16121            ps = mSettings.mPackages.get(pkgName);
16122
16123            // verify signatures are valid
16124            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
16125            if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
16126                if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
16127                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16128                            "New package not signed by keys specified by upgrade-keysets: "
16129                                    + pkgName);
16130                    return;
16131                }
16132            } else {
16133
16134                // default to original signature matching
16135                if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
16136                        PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) {
16137                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16138                            "New package has a different signature: " + pkgName);
16139                    return;
16140                }
16141            }
16142
16143            // don't allow a system upgrade unless the upgrade hash matches
16144            if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
16145                byte[] digestBytes = null;
16146                try {
16147                    final MessageDigest digest = MessageDigest.getInstance("SHA-512");
16148                    updateDigest(digest, new File(pkg.baseCodePath));
16149                    if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
16150                        for (String path : pkg.splitCodePaths) {
16151                            updateDigest(digest, new File(path));
16152                        }
16153                    }
16154                    digestBytes = digest.digest();
16155                } catch (NoSuchAlgorithmException | IOException e) {
16156                    res.setError(INSTALL_FAILED_INVALID_APK,
16157                            "Could not compute hash: " + pkgName);
16158                    return;
16159                }
16160                if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
16161                    res.setError(INSTALL_FAILED_INVALID_APK,
16162                            "New package fails restrict-update check: " + pkgName);
16163                    return;
16164                }
16165                // retain upgrade restriction
16166                pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
16167            }
16168
16169            // Check for shared user id changes
16170            String invalidPackageName =
16171                    getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
16172            if (invalidPackageName != null) {
16173                res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
16174                        "Package " + invalidPackageName + " tried to change user "
16175                                + oldPackage.mSharedUserId);
16176                return;
16177            }
16178
16179            // check if the new package supports all of the abis which the old package supports
16180            boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null;
16181            boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null;
16182            if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) {
16183                res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16184                        "Update to package " + pkgName + " doesn't support multi arch");
16185                return;
16186            }
16187
16188            // In case of rollback, remember per-user/profile install state
16189            allUsers = sUserManager.getUserIds();
16190            installedUsers = ps.queryInstalledUsers(allUsers, true);
16191
16192            // don't allow an upgrade from full to ephemeral
16193            if (isInstantApp) {
16194                if (user == null || user.getIdentifier() == UserHandle.USER_ALL) {
16195                    for (int currentUser : allUsers) {
16196                        if (!ps.getInstantApp(currentUser)) {
16197                            // can't downgrade from full to instant
16198                            Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16199                                    + " for user: " + currentUser);
16200                            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16201                            return;
16202                        }
16203                    }
16204                } else if (!ps.getInstantApp(user.getIdentifier())) {
16205                    // can't downgrade from full to instant
16206                    Slog.w(TAG, "Can't replace full app with instant app: " + pkgName
16207                            + " for user: " + user.getIdentifier());
16208                    res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16209                    return;
16210                }
16211            }
16212        }
16213
16214        // Update what is removed
16215        res.removedInfo = new PackageRemovedInfo(this);
16216        res.removedInfo.uid = oldPackage.applicationInfo.uid;
16217        res.removedInfo.removedPackage = oldPackage.packageName;
16218        res.removedInfo.installerPackageName = ps.installerPackageName;
16219        res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
16220        res.removedInfo.isUpdate = true;
16221        res.removedInfo.origUsers = installedUsers;
16222        res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
16223        for (int i = 0; i < installedUsers.length; i++) {
16224            final int userId = installedUsers[i];
16225            res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
16226        }
16227
16228        final int childCount = (oldPackage.childPackages != null)
16229                ? oldPackage.childPackages.size() : 0;
16230        for (int i = 0; i < childCount; i++) {
16231            boolean childPackageUpdated = false;
16232            PackageParser.Package childPkg = oldPackage.childPackages.get(i);
16233            final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16234            if (res.addedChildPackages != null) {
16235                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
16236                if (childRes != null) {
16237                    childRes.removedInfo.uid = childPkg.applicationInfo.uid;
16238                    childRes.removedInfo.removedPackage = childPkg.packageName;
16239                    if (childPs != null) {
16240                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16241                    }
16242                    childRes.removedInfo.isUpdate = true;
16243                    childRes.removedInfo.installReasons = res.removedInfo.installReasons;
16244                    childPackageUpdated = true;
16245                }
16246            }
16247            if (!childPackageUpdated) {
16248                PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
16249                childRemovedRes.removedPackage = childPkg.packageName;
16250                if (childPs != null) {
16251                    childRemovedRes.installerPackageName = childPs.installerPackageName;
16252                }
16253                childRemovedRes.isUpdate = false;
16254                childRemovedRes.dataRemoved = true;
16255                synchronized (mPackages) {
16256                    if (childPs != null) {
16257                        childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true);
16258                    }
16259                }
16260                if (res.removedInfo.removedChildPackages == null) {
16261                    res.removedInfo.removedChildPackages = new ArrayMap<>();
16262                }
16263                res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes);
16264            }
16265        }
16266
16267        boolean sysPkg = (isSystemApp(oldPackage));
16268        if (sysPkg) {
16269            // Set the system/privileged/oem/vendor/product flags as needed
16270            final boolean privileged =
16271                    (oldPackage.applicationInfo.privateFlags
16272                            & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
16273            final boolean oem =
16274                    (oldPackage.applicationInfo.privateFlags
16275                            & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
16276            final boolean vendor =
16277                    (oldPackage.applicationInfo.privateFlags
16278                            & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
16279            final boolean product =
16280                    (oldPackage.applicationInfo.privateFlags
16281                            & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
16282            final @ParseFlags int systemParseFlags = parseFlags;
16283            final @ScanFlags int systemScanFlags = scanFlags
16284                    | SCAN_AS_SYSTEM
16285                    | (privileged ? SCAN_AS_PRIVILEGED : 0)
16286                    | (oem ? SCAN_AS_OEM : 0)
16287                    | (vendor ? SCAN_AS_VENDOR : 0)
16288                    | (product ? SCAN_AS_PRODUCT : 0);
16289
16290            replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags,
16291                    user, allUsers, installerPackageName, res, installReason);
16292        } else {
16293            replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags,
16294                    user, allUsers, installerPackageName, res, installReason);
16295        }
16296    }
16297
16298    @Override
16299    public List<String> getPreviousCodePaths(String packageName) {
16300        final int callingUid = Binder.getCallingUid();
16301        final List<String> result = new ArrayList<>();
16302        if (getInstantAppPackageName(callingUid) != null) {
16303            return result;
16304        }
16305        final PackageSetting ps = mSettings.mPackages.get(packageName);
16306        if (ps != null
16307                && ps.oldCodePaths != null
16308                && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
16309            result.addAll(ps.oldCodePaths);
16310        }
16311        return result;
16312    }
16313
16314    private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage,
16315            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16316            final @ScanFlags int scanFlags, UserHandle user, int[] allUsers,
16317            String installerPackageName, PackageInstalledInfo res, int installReason) {
16318        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
16319                + deletedPackage);
16320
16321        String pkgName = deletedPackage.packageName;
16322        boolean deletedPkg = true;
16323        boolean addedPkg = false;
16324        boolean updatedSettings = false;
16325        final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0;
16326        final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16327                | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16328
16329        final long origUpdateTime = (pkg.mExtras != null)
16330                ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0;
16331
16332        // First delete the existing package while retaining the data directory
16333        if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16334                res.removedInfo, true, pkg)) {
16335            // If the existing package wasn't successfully deleted
16336            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
16337            deletedPkg = false;
16338        } else {
16339            // Successfully deleted the old package; proceed with replace.
16340
16341            // If deleted package lived in a container, give users a chance to
16342            // relinquish resources before killing.
16343            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
16344                if (DEBUG_INSTALL) {
16345                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
16346                }
16347                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
16348                final ArrayList<String> pkgList = new ArrayList<String>(1);
16349                pkgList.add(deletedPackage.applicationInfo.packageName);
16350                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16351            }
16352
16353            clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16354                    | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16355
16356            try {
16357                final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags,
16358                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
16359                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16360                        installReason);
16361
16362                // Update the in-memory copy of the previous code paths.
16363                PackageSetting ps = mSettings.mPackages.get(pkgName);
16364                if (!killApp) {
16365                    if (ps.oldCodePaths == null) {
16366                        ps.oldCodePaths = new ArraySet<>();
16367                    }
16368                    Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath);
16369                    if (deletedPackage.splitCodePaths != null) {
16370                        Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths);
16371                    }
16372                } else {
16373                    ps.oldCodePaths = null;
16374                }
16375                if (ps.childPackageNames != null) {
16376                    for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) {
16377                        final String childPkgName = ps.childPackageNames.get(i);
16378                        final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16379                        childPs.oldCodePaths = ps.oldCodePaths;
16380                    }
16381                }
16382                // set instant app status, but, only if it's explicitly specified
16383                final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
16384                final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
16385                setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp);
16386                prepareAppDataAfterInstallLIF(newPackage);
16387                addedPkg = true;
16388                mDexManager.notifyPackageUpdated(newPackage.packageName,
16389                        newPackage.baseCodePath, newPackage.splitCodePaths);
16390            } catch (PackageManagerException e) {
16391                res.setError("Package couldn't be installed in " + pkg.codePath, e);
16392            }
16393        }
16394
16395        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16396            if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
16397
16398            // Revert all internal state mutations and added folders for the failed install
16399            if (addedPkg) {
16400                deletePackageLIF(pkgName, null, true, allUsers, deleteFlags,
16401                        res.removedInfo, true, null);
16402            }
16403
16404            // Restore the old package
16405            if (deletedPkg) {
16406                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
16407                File restoreFile = new File(deletedPackage.codePath);
16408                // Parse old package
16409                boolean oldExternal = isExternal(deletedPackage);
16410                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
16411                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
16412                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
16413                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
16414                try {
16415                    scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime,
16416                            null);
16417                } catch (PackageManagerException e) {
16418                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
16419                            + e.getMessage());
16420                    return;
16421                }
16422
16423                synchronized (mPackages) {
16424                    // Ensure the installer package name up to date
16425                    setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16426
16427                    // Update permissions for restored package
16428                    mPermissionManager.updatePermissions(
16429                            deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16430                            mPermissionCallback);
16431
16432                    mSettings.writeLPr();
16433                }
16434
16435                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
16436            }
16437        } else {
16438            synchronized (mPackages) {
16439                PackageSetting ps = mSettings.getPackageLPr(pkg.packageName);
16440                if (ps != null) {
16441                    res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null;
16442                    if (res.removedInfo.removedChildPackages != null) {
16443                        final int childCount = res.removedInfo.removedChildPackages.size();
16444                        // Iterate in reverse as we may modify the collection
16445                        for (int i = childCount - 1; i >= 0; i--) {
16446                            String childPackageName = res.removedInfo.removedChildPackages.keyAt(i);
16447                            if (res.addedChildPackages.containsKey(childPackageName)) {
16448                                res.removedInfo.removedChildPackages.removeAt(i);
16449                            } else {
16450                                PackageRemovedInfo childInfo = res.removedInfo
16451                                        .removedChildPackages.valueAt(i);
16452                                childInfo.removedForAllUsers = mPackages.get(
16453                                        childInfo.removedPackage) == null;
16454                            }
16455                        }
16456                    }
16457                }
16458            }
16459        }
16460    }
16461
16462    private void replaceSystemPackageLIF(PackageParser.Package deletedPackage,
16463            PackageParser.Package pkg, final @ParseFlags int parseFlags,
16464            final @ScanFlags int scanFlags, UserHandle user,
16465            int[] allUsers, String installerPackageName, PackageInstalledInfo res,
16466            int installReason) {
16467        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
16468                + ", old=" + deletedPackage);
16469
16470        final boolean disabledSystem;
16471
16472        // Remove existing system package
16473        removePackageLI(deletedPackage, true);
16474
16475        synchronized (mPackages) {
16476            disabledSystem = disableSystemPackageLPw(deletedPackage, pkg);
16477        }
16478        if (!disabledSystem) {
16479            // We didn't need to disable the .apk as a current system package,
16480            // which means we are replacing another update that is already
16481            // installed.  We need to make sure to delete the older one's .apk.
16482            res.removedInfo.args = createInstallArgsForExisting(0,
16483                    deletedPackage.applicationInfo.getCodePath(),
16484                    deletedPackage.applicationInfo.getResourcePath(),
16485                    getAppDexInstructionSets(deletedPackage.applicationInfo));
16486        } else {
16487            res.removedInfo.args = null;
16488        }
16489
16490        // Successfully disabled the old package. Now proceed with re-installation
16491        clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE
16492                | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
16493
16494        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16495        pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
16496                ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
16497
16498        PackageParser.Package newPackage = null;
16499        try {
16500            // Add the package to the internal data structures
16501            newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user);
16502
16503            // Set the update and install times
16504            PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras;
16505            setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime,
16506                    System.currentTimeMillis());
16507
16508            // Update the package dynamic state if succeeded
16509            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16510                // Now that the install succeeded make sure we remove data
16511                // directories for any child package the update removed.
16512                final int deletedChildCount = (deletedPackage.childPackages != null)
16513                        ? deletedPackage.childPackages.size() : 0;
16514                final int newChildCount = (newPackage.childPackages != null)
16515                        ? newPackage.childPackages.size() : 0;
16516                for (int i = 0; i < deletedChildCount; i++) {
16517                    PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i);
16518                    boolean childPackageDeleted = true;
16519                    for (int j = 0; j < newChildCount; j++) {
16520                        PackageParser.Package newChildPkg = newPackage.childPackages.get(j);
16521                        if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16522                            childPackageDeleted = false;
16523                            break;
16524                        }
16525                    }
16526                    if (childPackageDeleted) {
16527                        PackageSetting ps = mSettings.getDisabledSystemPkgLPr(
16528                                deletedChildPkg.packageName);
16529                        if (ps != null && res.removedInfo.removedChildPackages != null) {
16530                            PackageRemovedInfo removedChildRes = res.removedInfo
16531                                    .removedChildPackages.get(deletedChildPkg.packageName);
16532                            removePackageDataLIF(ps, allUsers, removedChildRes, 0, false);
16533                            removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null;
16534                        }
16535                    }
16536                }
16537
16538                updateSettingsLI(newPackage, installerPackageName, allUsers, res, user,
16539                        installReason);
16540                prepareAppDataAfterInstallLIF(newPackage);
16541
16542                mDexManager.notifyPackageUpdated(newPackage.packageName,
16543                            newPackage.baseCodePath, newPackage.splitCodePaths);
16544            }
16545        } catch (PackageManagerException e) {
16546            res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR);
16547            res.setError("Package couldn't be installed in " + pkg.codePath, e);
16548        }
16549
16550        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
16551            // Re installation failed. Restore old information
16552            // Remove new pkg information
16553            if (newPackage != null) {
16554                removeInstalledPackageLI(newPackage, true);
16555            }
16556            // Add back the old system package
16557            try {
16558                scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
16559            } catch (PackageManagerException e) {
16560                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
16561            }
16562
16563            synchronized (mPackages) {
16564                if (disabledSystem) {
16565                    enableSystemPackageLPw(deletedPackage);
16566                }
16567
16568                // Ensure the installer package name up to date
16569                setInstallerPackageNameLPw(deletedPackage, installerPackageName);
16570
16571                // Update permissions for restored package
16572                mPermissionManager.updatePermissions(
16573                        deletedPackage.packageName, deletedPackage, false, mPackages.values(),
16574                        mPermissionCallback);
16575
16576                mSettings.writeLPr();
16577            }
16578
16579            Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName
16580                    + " after failed upgrade");
16581        }
16582    }
16583
16584    /**
16585     * Checks whether the parent or any of the child packages have a change shared
16586     * user. For a package to be a valid update the shred users of the parent and
16587     * the children should match. We may later support changing child shared users.
16588     * @param oldPkg The updated package.
16589     * @param newPkg The update package.
16590     * @return The shared user that change between the versions.
16591     */
16592    private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16593            PackageParser.Package newPkg) {
16594        // Check parent shared user
16595        if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16596            return newPkg.packageName;
16597        }
16598        // Check child shared users
16599        final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16600        final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16601        for (int i = 0; i < newChildCount; i++) {
16602            PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16603            // If this child was present, did it have the same shared user?
16604            for (int j = 0; j < oldChildCount; j++) {
16605                PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16606                if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16607                        && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16608                    return newChildPkg.packageName;
16609                }
16610            }
16611        }
16612        return null;
16613    }
16614
16615    private void removeNativeBinariesLI(PackageSetting ps) {
16616        // Remove the lib path for the parent package
16617        if (ps != null) {
16618            NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16619            // Remove the lib path for the child packages
16620            final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16621            for (int i = 0; i < childCount; i++) {
16622                PackageSetting childPs = null;
16623                synchronized (mPackages) {
16624                    childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16625                }
16626                if (childPs != null) {
16627                    NativeLibraryHelper.removeNativeBinariesLI(childPs
16628                            .legacyNativeLibraryPathString);
16629                }
16630            }
16631        }
16632    }
16633
16634    private void enableSystemPackageLPw(PackageParser.Package pkg) {
16635        // Enable the parent package
16636        mSettings.enableSystemPackageLPw(pkg.packageName);
16637        // Enable the child packages
16638        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16639        for (int i = 0; i < childCount; i++) {
16640            PackageParser.Package childPkg = pkg.childPackages.get(i);
16641            mSettings.enableSystemPackageLPw(childPkg.packageName);
16642        }
16643    }
16644
16645    private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16646            PackageParser.Package newPkg) {
16647        // Disable the parent package (parent always replaced)
16648        boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16649        // Disable the child packages
16650        final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16651        for (int i = 0; i < childCount; i++) {
16652            PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16653            final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16654            disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16655        }
16656        return disabled;
16657    }
16658
16659    private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16660            String installerPackageName) {
16661        // Enable the parent package
16662        mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16663        // Enable the child packages
16664        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16665        for (int i = 0; i < childCount; i++) {
16666            PackageParser.Package childPkg = pkg.childPackages.get(i);
16667            mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16668        }
16669    }
16670
16671    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16672            int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16673        // Update the parent package setting
16674        updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16675                res, user, installReason);
16676        // Update the child packages setting
16677        final int childCount = (newPackage.childPackages != null)
16678                ? newPackage.childPackages.size() : 0;
16679        for (int i = 0; i < childCount; i++) {
16680            PackageParser.Package childPackage = newPackage.childPackages.get(i);
16681            PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16682            updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16683                    childRes.origUsers, childRes, user, installReason);
16684        }
16685    }
16686
16687    private void updateSettingsInternalLI(PackageParser.Package pkg,
16688            String installerPackageName, int[] allUsers, int[] installedForUsers,
16689            PackageInstalledInfo res, UserHandle user, int installReason) {
16690        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16691
16692        final String pkgName = pkg.packageName;
16693
16694        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16695        synchronized (mPackages) {
16696// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16697            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16698                    mPermissionCallback);
16699            // For system-bundled packages, we assume that installing an upgraded version
16700            // of the package implies that the user actually wants to run that new code,
16701            // so we enable the package.
16702            PackageSetting ps = mSettings.mPackages.get(pkgName);
16703            final int userId = user.getIdentifier();
16704            if (ps != null) {
16705                if (isSystemApp(pkg)) {
16706                    if (DEBUG_INSTALL) {
16707                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16708                    }
16709                    // Enable system package for requested users
16710                    if (res.origUsers != null) {
16711                        for (int origUserId : res.origUsers) {
16712                            if (userId == UserHandle.USER_ALL || userId == origUserId) {
16713                                ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16714                                        origUserId, installerPackageName);
16715                            }
16716                        }
16717                    }
16718                    // Also convey the prior install/uninstall state
16719                    if (allUsers != null && installedForUsers != null) {
16720                        for (int currentUserId : allUsers) {
16721                            final boolean installed = ArrayUtils.contains(
16722                                    installedForUsers, currentUserId);
16723                            if (DEBUG_INSTALL) {
16724                                Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16725                            }
16726                            ps.setInstalled(installed, currentUserId);
16727                        }
16728                        // these install state changes will be persisted in the
16729                        // upcoming call to mSettings.writeLPr().
16730                    }
16731                }
16732                // It's implied that when a user requests installation, they want the app to be
16733                // installed and enabled.
16734                if (userId != UserHandle.USER_ALL) {
16735                    ps.setInstalled(true, userId);
16736                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16737                } else {
16738                    for (int currentUserId : sUserManager.getUserIds()) {
16739                        ps.setInstalled(true, currentUserId);
16740                        ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId,
16741                                installerPackageName);
16742                    }
16743                }
16744
16745                // When replacing an existing package, preserve the original install reason for all
16746                // users that had the package installed before.
16747                final Set<Integer> previousUserIds = new ArraySet<>();
16748                if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16749                    final int installReasonCount = res.removedInfo.installReasons.size();
16750                    for (int i = 0; i < installReasonCount; i++) {
16751                        final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16752                        final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16753                        ps.setInstallReason(previousInstallReason, previousUserId);
16754                        previousUserIds.add(previousUserId);
16755                    }
16756                }
16757
16758                // Set install reason for users that are having the package newly installed.
16759                if (userId == UserHandle.USER_ALL) {
16760                    for (int currentUserId : sUserManager.getUserIds()) {
16761                        if (!previousUserIds.contains(currentUserId)) {
16762                            ps.setInstallReason(installReason, currentUserId);
16763                        }
16764                    }
16765                } else if (!previousUserIds.contains(userId)) {
16766                    ps.setInstallReason(installReason, userId);
16767                }
16768                mSettings.writeKernelMappingLPr(ps);
16769            }
16770            res.name = pkgName;
16771            res.uid = pkg.applicationInfo.uid;
16772            res.pkg = pkg;
16773            mSettings.setInstallerPackageName(pkgName, installerPackageName);
16774            res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16775            //to update install status
16776            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16777            mSettings.writeLPr();
16778            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16779        }
16780
16781        Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16782    }
16783
16784    private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) {
16785        try {
16786            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage");
16787            installPackageLI(args, res);
16788        } finally {
16789            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16790        }
16791    }
16792
16793    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
16794        final int installFlags = args.installFlags;
16795        final String installerPackageName = args.installerPackageName;
16796        final String volumeUuid = args.volumeUuid;
16797        final File tmpPackageFile = new File(args.getCodePath());
16798        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
16799        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
16800                || (args.volumeUuid != null));
16801        final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
16802        final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
16803        final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0);
16804        final boolean virtualPreload =
16805                ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
16806        boolean replace = false;
16807        @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
16808        if (args.move != null) {
16809            // moving a complete application; perform an initial scan on the new install location
16810            scanFlags |= SCAN_INITIAL;
16811        }
16812        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
16813            scanFlags |= SCAN_DONT_KILL_APP;
16814        }
16815        if (instantApp) {
16816            scanFlags |= SCAN_AS_INSTANT_APP;
16817        }
16818        if (fullApp) {
16819            scanFlags |= SCAN_AS_FULL_APP;
16820        }
16821        if (virtualPreload) {
16822            scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
16823        }
16824
16825        // Result object to be returned
16826        res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16827        res.installerPackageName = installerPackageName;
16828
16829        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
16830
16831        // Sanity check
16832        if (instantApp && (forwardLocked || onExternal)) {
16833            Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked
16834                    + " external=" + onExternal);
16835            res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
16836            return;
16837        }
16838
16839        // Retrieve PackageSettings and parse package
16840        @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
16841                | PackageParser.PARSE_ENFORCE_CODE
16842                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
16843                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0)
16844                | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0);
16845        PackageParser pp = new PackageParser();
16846        pp.setSeparateProcesses(mSeparateProcesses);
16847        pp.setDisplayMetrics(mMetrics);
16848        pp.setCallback(mPackageParserCallback);
16849
16850        Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
16851        final PackageParser.Package pkg;
16852        try {
16853            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
16854            DexMetadataHelper.validatePackageDexMetadata(pkg);
16855        } catch (PackageParserException e) {
16856            res.setError("Failed parse during installPackageLI", e);
16857            return;
16858        } finally {
16859            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16860        }
16861
16862        // Instant apps have several additional install-time checks.
16863        if (instantApp) {
16864            if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
16865                Slog.w(TAG,
16866                        "Instant app package " + pkg.packageName + " does not target at least O");
16867                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16868                        "Instant app package must target at least O");
16869                return;
16870            }
16871            if (pkg.applicationInfo.targetSandboxVersion != 2) {
16872                Slog.w(TAG, "Instant app package " + pkg.packageName
16873                        + " does not target targetSandboxVersion 2");
16874                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16875                        "Instant app package must use targetSandboxVersion 2");
16876                return;
16877            }
16878            if (pkg.mSharedUserId != null) {
16879                Slog.w(TAG, "Instant app package " + pkg.packageName
16880                        + " may not declare sharedUserId.");
16881                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16882                        "Instant app package may not declare a sharedUserId");
16883                return;
16884            }
16885        }
16886
16887        if (pkg.applicationInfo.isStaticSharedLibrary()) {
16888            // Static shared libraries have synthetic package names
16889            renameStaticSharedLibraryPackage(pkg);
16890
16891            // No static shared libs on external storage
16892            if (onExternal) {
16893                Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
16894                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
16895                        "Packages declaring static-shared libs cannot be updated");
16896                return;
16897            }
16898        }
16899
16900        // If we are installing a clustered package add results for the children
16901        if (pkg.childPackages != null) {
16902            synchronized (mPackages) {
16903                final int childCount = pkg.childPackages.size();
16904                for (int i = 0; i < childCount; i++) {
16905                    PackageParser.Package childPkg = pkg.childPackages.get(i);
16906                    PackageInstalledInfo childRes = new PackageInstalledInfo();
16907                    childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16908                    childRes.pkg = childPkg;
16909                    childRes.name = childPkg.packageName;
16910                    PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16911                    if (childPs != null) {
16912                        childRes.origUsers = childPs.queryInstalledUsers(
16913                                sUserManager.getUserIds(), true);
16914                    }
16915                    if ((mPackages.containsKey(childPkg.packageName))) {
16916                        childRes.removedInfo = new PackageRemovedInfo(this);
16917                        childRes.removedInfo.removedPackage = childPkg.packageName;
16918                        childRes.removedInfo.installerPackageName = childPs.installerPackageName;
16919                    }
16920                    if (res.addedChildPackages == null) {
16921                        res.addedChildPackages = new ArrayMap<>();
16922                    }
16923                    res.addedChildPackages.put(childPkg.packageName, childRes);
16924                }
16925            }
16926        }
16927
16928        // If package doesn't declare API override, mark that we have an install
16929        // time CPU ABI override.
16930        if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
16931            pkg.cpuAbiOverride = args.abiOverride;
16932        }
16933
16934        String pkgName = res.name = pkg.packageName;
16935        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
16936            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
16937                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
16938                return;
16939            }
16940        }
16941
16942        try {
16943            // either use what we've been given or parse directly from the APK
16944            if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
16945                pkg.setSigningDetails(args.signingDetails);
16946            } else {
16947                PackageParser.collectCertificates(pkg, false /* skipVerify */);
16948            }
16949        } catch (PackageParserException e) {
16950            res.setError("Failed collect during installPackageLI", e);
16951            return;
16952        }
16953
16954        if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
16955                < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
16956            Slog.w(TAG, "Instant app package " + pkg.packageName
16957                    + " is not signed with at least APK Signature Scheme v2");
16958            res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
16959                    "Instant app package must be signed with APK Signature Scheme v2 or greater");
16960            return;
16961        }
16962
16963        // Get rid of all references to package scan path via parser.
16964        pp = null;
16965        String oldCodePath = null;
16966        boolean systemApp = false;
16967        synchronized (mPackages) {
16968            // Check if installing already existing package
16969            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
16970                String oldName = mSettings.getRenamedPackageLPr(pkgName);
16971                if (pkg.mOriginalPackages != null
16972                        && pkg.mOriginalPackages.contains(oldName)
16973                        && mPackages.containsKey(oldName)) {
16974                    // This package is derived from an original package,
16975                    // and this device has been updating from that original
16976                    // name.  We must continue using the original name, so
16977                    // rename the new package here.
16978                    pkg.setPackageName(oldName);
16979                    pkgName = pkg.packageName;
16980                    replace = true;
16981                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
16982                            + oldName + " pkgName=" + pkgName);
16983                } else if (mPackages.containsKey(pkgName)) {
16984                    // This package, under its official name, already exists
16985                    // on the device; we should replace it.
16986                    replace = true;
16987                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
16988                }
16989
16990                // Child packages are installed through the parent package
16991                if (pkg.parentPackage != null) {
16992                    res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
16993                            "Package " + pkg.packageName + " is child of package "
16994                                    + pkg.parentPackage.parentPackage + ". Child packages "
16995                                    + "can be updated only through the parent package.");
16996                    return;
16997                }
16998
16999                if (replace) {
17000                    // Prevent apps opting out from runtime permissions
17001                    PackageParser.Package oldPackage = mPackages.get(pkgName);
17002                    final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17003                    final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17004                    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17005                            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17006                        res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17007                                "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17008                                        + " doesn't support runtime permissions but the old"
17009                                        + " target SDK " + oldTargetSdk + " does.");
17010                        return;
17011                    }
17012                    // Prevent persistent apps from being updated
17013                    if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) {
17014                        res.setError(PackageManager.INSTALL_FAILED_INVALID_APK,
17015                                "Package " + oldPackage.packageName + " is a persistent app. "
17016                                        + "Persistent apps are not updateable.");
17017                        return;
17018                    }
17019                    // Prevent apps from downgrading their targetSandbox.
17020                    final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion;
17021                    final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion;
17022                    if (oldTargetSandbox == 2 && newTargetSandbox != 2) {
17023                        res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE,
17024                                "Package " + pkg.packageName + " new target sandbox "
17025                                + newTargetSandbox + " is incompatible with the previous value of"
17026                                + oldTargetSandbox + ".");
17027                        return;
17028                    }
17029
17030                    // Prevent installing of child packages
17031                    if (oldPackage.parentPackage != null) {
17032                        res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17033                                "Package " + pkg.packageName + " is child of package "
17034                                        + oldPackage.parentPackage + ". Child packages "
17035                                        + "can be updated only through the parent package.");
17036                        return;
17037                    }
17038                }
17039            }
17040
17041            PackageSetting ps = mSettings.mPackages.get(pkgName);
17042            if (ps != null) {
17043                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17044
17045                // Static shared libs have same package with different versions where
17046                // we internally use a synthetic package name to allow multiple versions
17047                // of the same package, therefore we need to compare signatures against
17048                // the package setting for the latest library version.
17049                PackageSetting signatureCheckPs = ps;
17050                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17051                    SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg);
17052                    if (libraryEntry != null) {
17053                        signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk);
17054                    }
17055                }
17056
17057                // Quick sanity check that we're signed correctly if updating;
17058                // we'll check this again later when scanning, but we want to
17059                // bail early here before tripping over redefined permissions.
17060                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17061                if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17062                    if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17063                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17064                                + pkg.packageName + " upgrade keys do not match the "
17065                                + "previously installed version");
17066                        return;
17067                    }
17068                } else {
17069                    try {
17070                        final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17071                        final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17072                        // We don't care about disabledPkgSetting on install for now.
17073                        final boolean compatMatch = verifySignatures(
17074                                signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17075                                compareRecover);
17076                        // The new KeySets will be re-added later in the scanning process.
17077                        if (compatMatch) {
17078                            synchronized (mPackages) {
17079                                ksms.removeAppKeySetDataLPw(pkg.packageName);
17080                            }
17081                        }
17082                    } catch (PackageManagerException e) {
17083                        res.setError(e.error, e.getMessage());
17084                        return;
17085                    }
17086                }
17087
17088                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
17089                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17090                    systemApp = (ps.pkg.applicationInfo.flags &
17091                            ApplicationInfo.FLAG_SYSTEM) != 0;
17092                }
17093                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17094            }
17095
17096            int N = pkg.permissions.size();
17097            for (int i = N-1; i >= 0; i--) {
17098                final PackageParser.Permission perm = pkg.permissions.get(i);
17099                final BasePermission bp =
17100                        (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17101
17102                // Don't allow anyone but the system to define ephemeral permissions.
17103                if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17104                        && !systemApp) {
17105                    Slog.w(TAG, "Non-System package " + pkg.packageName
17106                            + " attempting to delcare ephemeral permission "
17107                            + perm.info.name + "; Removing ephemeral.");
17108                    perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17109                }
17110
17111                // Check whether the newly-scanned package wants to define an already-defined perm
17112                if (bp != null) {
17113                    // If the defining package is signed with our cert, it's okay.  This
17114                    // also includes the "updating the same package" case, of course.
17115                    // "updating same package" could also involve key-rotation.
17116                    final boolean sigsOk;
17117                    final String sourcePackageName = bp.getSourcePackageName();
17118                    final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17119                    final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17120                    if (sourcePackageName.equals(pkg.packageName)
17121                            && (ksms.shouldCheckUpgradeKeySetLocked(
17122                                    sourcePackageSetting, scanFlags))) {
17123                        sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17124                    } else {
17125
17126                        // in the event of signing certificate rotation, we need to see if the
17127                        // package's certificate has rotated from the current one, or if it is an
17128                        // older certificate with which the current is ok with sharing permissions
17129                        if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17130                                        pkg.mSigningDetails,
17131                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17132                            sigsOk = true;
17133                        } else if (pkg.mSigningDetails.checkCapability(
17134                                        sourcePackageSetting.signatures.mSigningDetails,
17135                                        PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17136
17137                            // the scanned package checks out, has signing certificate rotation
17138                            // history, and is newer; bring it over
17139                            sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17140                            sigsOk = true;
17141                        } else {
17142                            sigsOk = false;
17143                        }
17144                    }
17145                    if (!sigsOk) {
17146                        // If the owning package is the system itself, we log but allow
17147                        // install to proceed; we fail the install on all other permission
17148                        // redefinitions.
17149                        if (!sourcePackageName.equals("android")) {
17150                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17151                                    + pkg.packageName + " attempting to redeclare permission "
17152                                    + perm.info.name + " already owned by " + sourcePackageName);
17153                            res.origPermission = perm.info.name;
17154                            res.origPackage = sourcePackageName;
17155                            return;
17156                        } else {
17157                            Slog.w(TAG, "Package " + pkg.packageName
17158                                    + " attempting to redeclare system permission "
17159                                    + perm.info.name + "; ignoring new declaration");
17160                            pkg.permissions.remove(i);
17161                        }
17162                    } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17163                        // Prevent apps to change protection level to dangerous from any other
17164                        // type as this would allow a privilege escalation where an app adds a
17165                        // normal/signature permission in other app's group and later redefines
17166                        // it as dangerous leading to the group auto-grant.
17167                        if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17168                                == PermissionInfo.PROTECTION_DANGEROUS) {
17169                            if (bp != null && !bp.isRuntime()) {
17170                                Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17171                                        + "non-runtime permission " + perm.info.name
17172                                        + " to runtime; keeping old protection level");
17173                                perm.info.protectionLevel = bp.getProtectionLevel();
17174                            }
17175                        }
17176                    }
17177                }
17178            }
17179        }
17180
17181        if (systemApp) {
17182            if (onExternal) {
17183                // Abort update; system app can't be replaced with app on sdcard
17184                res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17185                        "Cannot install updates to system apps on sdcard");
17186                return;
17187            } else if (instantApp) {
17188                // Abort update; system app can't be replaced with an instant app
17189                res.setError(INSTALL_FAILED_INSTANT_APP_INVALID,
17190                        "Cannot update a system app with an instant app");
17191                return;
17192            }
17193        }
17194
17195        if (args.move != null) {
17196            // We did an in-place move, so dex is ready to roll
17197            scanFlags |= SCAN_NO_DEX;
17198            scanFlags |= SCAN_MOVE;
17199
17200            synchronized (mPackages) {
17201                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17202                if (ps == null) {
17203                    res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17204                            "Missing settings for moved package " + pkgName);
17205                }
17206
17207                // We moved the entire application as-is, so bring over the
17208                // previously derived ABI information.
17209                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17210                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17211            }
17212
17213        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
17214            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17215            scanFlags |= SCAN_NO_DEX;
17216
17217            try {
17218                String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17219                    args.abiOverride : pkg.cpuAbiOverride);
17220                final boolean extractNativeLibs = !pkg.isLibrary();
17221                derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17222            } catch (PackageManagerException pme) {
17223                Slog.e(TAG, "Error deriving application ABI", pme);
17224                res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI");
17225                return;
17226            }
17227
17228            // Shared libraries for the package need to be updated.
17229            synchronized (mPackages) {
17230                try {
17231                    updateSharedLibrariesLPr(pkg, null);
17232                } catch (PackageManagerException e) {
17233                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
17234                }
17235            }
17236        }
17237
17238        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
17239            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17240            return;
17241        }
17242
17243        if (PackageManagerServiceUtils.isApkVerityEnabled()) {
17244            String apkPath = null;
17245            synchronized (mPackages) {
17246                // Note that if the attacker managed to skip verify setup, for example by tampering
17247                // with the package settings, upon reboot we will do full apk verification when
17248                // verity is not detected.
17249                final PackageSetting ps = mSettings.mPackages.get(pkgName);
17250                if (ps != null && ps.isPrivileged()) {
17251                    apkPath = pkg.baseCodePath;
17252                }
17253            }
17254
17255            if (apkPath != null) {
17256                final VerityUtils.SetupResult result =
17257                        VerityUtils.generateApkVeritySetupData(apkPath);
17258                if (result.isOk()) {
17259                    if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath);
17260                    FileDescriptor fd = result.getUnownedFileDescriptor();
17261                    try {
17262                        mInstaller.installApkVerity(apkPath, fd);
17263                    } catch (InstallerException e) {
17264                        res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17265                                "Failed to set up verity: " + e);
17266                        return;
17267                    } finally {
17268                        IoUtils.closeQuietly(fd);
17269                    }
17270                } else if (result.isFailed()) {
17271                    res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity");
17272                    return;
17273                } else {
17274                    // Do nothing if verity is skipped. Will fall back to full apk verification on
17275                    // reboot.
17276                }
17277            }
17278        }
17279
17280        if (!instantApp) {
17281            startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17282        } else {
17283            if (DEBUG_DOMAIN_VERIFICATION) {
17284                Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17285            }
17286        }
17287
17288        try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags,
17289                "installPackageLI")) {
17290            if (replace) {
17291                if (pkg.applicationInfo.isStaticSharedLibrary()) {
17292                    // Static libs have a synthetic package name containing the version
17293                    // and cannot be updated as an update would get a new package name,
17294                    // unless this is the exact same version code which is useful for
17295                    // development.
17296                    PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17297                    if (existingPkg != null &&
17298                            existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17299                        res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring "
17300                                + "static-shared libs cannot be updated");
17301                        return;
17302                    }
17303                }
17304                replacePackageLIF(pkg, parseFlags, scanFlags, args.user,
17305                        installerPackageName, res, args.installReason);
17306            } else {
17307                installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
17308                        args.user, installerPackageName, volumeUuid, res, args.installReason);
17309            }
17310        }
17311
17312        // Prepare the application profiles for the new code paths.
17313        // This needs to be done before invoking dexopt so that any install-time profile
17314        // can be used for optimizations.
17315        mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier()));
17316
17317        // Check whether we need to dexopt the app.
17318        //
17319        // NOTE: it is IMPORTANT to call dexopt:
17320        //   - after doRename which will sync the package data from PackageParser.Package and its
17321        //     corresponding ApplicationInfo.
17322        //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17323        //     uid of the application (pkg.applicationInfo.uid).
17324        //     This update happens in place!
17325        //
17326        // We only need to dexopt if the package meets ALL of the following conditions:
17327        //   1) it is not forward locked.
17328        //   2) it is not on on an external ASEC container.
17329        //   3) it is not an instant app or if it is then dexopt is enabled via gservices.
17330        //
17331        // Note that we do not dexopt instant apps by default. dexopt can take some time to
17332        // complete, so we skip this step during installation. Instead, we'll take extra time
17333        // the first time the instant app starts. It's preferred to do it this way to provide
17334        // continuous progress to the useur instead of mysteriously blocking somewhere in the
17335        // middle of running an instant app. The default behaviour can be overridden
17336        // via gservices.
17337        final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED)
17338                && !forwardLocked
17339                && !pkg.applicationInfo.isExternalAsec()
17340                && (!instantApp || Global.getInt(mContext.getContentResolver(),
17341                Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0);
17342
17343        if (performDexopt) {
17344            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17345            // Do not run PackageDexOptimizer through the local performDexOpt
17346            // method because `pkg` may not be in `mPackages` yet.
17347            //
17348            // Also, don't fail application installs if the dexopt step fails.
17349            DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName,
17350                    REASON_INSTALL,
17351                    DexoptOptions.DEXOPT_BOOT_COMPLETE |
17352                    DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17353            mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles,
17354                    null /* instructionSets */,
17355                    getOrCreateCompilerPackageStats(pkg),
17356                    mDexManager.getPackageUseInfoOrDefault(pkg.packageName),
17357                    dexoptOptions);
17358            Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17359        }
17360
17361        // Notify BackgroundDexOptService that the package has been changed.
17362        // If this is an update of a package which used to fail to compile,
17363        // BackgroundDexOptService will remove it from its blacklist.
17364        // TODO: Layering violation
17365        BackgroundDexOptService.notifyPackageChanged(pkg.packageName);
17366
17367        synchronized (mPackages) {
17368            final PackageSetting ps = mSettings.mPackages.get(pkgName);
17369            if (ps != null) {
17370                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17371                ps.setUpdateAvailable(false /*updateAvailable*/);
17372            }
17373
17374            final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17375            for (int i = 0; i < childCount; i++) {
17376                PackageParser.Package childPkg = pkg.childPackages.get(i);
17377                PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName);
17378                PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17379                if (childPs != null) {
17380                    childRes.newUsers = childPs.queryInstalledUsers(
17381                            sUserManager.getUserIds(), true);
17382                }
17383            }
17384
17385            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17386                updateSequenceNumberLP(ps, res.newUsers);
17387                updateInstantAppInstallerLocked(pkgName);
17388            }
17389        }
17390    }
17391
17392    private void startIntentFilterVerifications(int userId, boolean replacing,
17393            PackageParser.Package pkg) {
17394        if (mIntentFilterVerifierComponent == null) {
17395            Slog.w(TAG, "No IntentFilter verification will not be done as "
17396                    + "there is no IntentFilterVerifier available!");
17397            return;
17398        }
17399
17400        final int verifierUid = getPackageUid(
17401                mIntentFilterVerifierComponent.getPackageName(),
17402                MATCH_DEBUG_TRIAGED_MISSING,
17403                (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
17404
17405        Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17406        msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
17407        mHandler.sendMessage(msg);
17408
17409        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
17410        for (int i = 0; i < childCount; i++) {
17411            PackageParser.Package childPkg = pkg.childPackages.get(i);
17412            msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
17413            msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
17414            mHandler.sendMessage(msg);
17415        }
17416    }
17417
17418    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
17419            PackageParser.Package pkg) {
17420        int size = pkg.activities.size();
17421        if (size == 0) {
17422            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17423                    "No activity, so no need to verify any IntentFilter!");
17424            return;
17425        }
17426
17427        final boolean hasDomainURLs = hasDomainURLs(pkg);
17428        if (!hasDomainURLs) {
17429            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17430                    "No domain URLs, so no need to verify any IntentFilter!");
17431            return;
17432        }
17433
17434        if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
17435                + " if any IntentFilter from the " + size
17436                + " Activities needs verification ...");
17437
17438        int count = 0;
17439        final String packageName = pkg.packageName;
17440
17441        synchronized (mPackages) {
17442            // If this is a new install and we see that we've already run verification for this
17443            // package, we have nothing to do: it means the state was restored from backup.
17444            if (!replacing) {
17445                IntentFilterVerificationInfo ivi =
17446                        mSettings.getIntentFilterVerificationLPr(packageName);
17447                if (ivi != null) {
17448                    if (DEBUG_DOMAIN_VERIFICATION) {
17449                        Slog.i(TAG, "Package " + packageName+ " already verified: status="
17450                                + ivi.getStatusString());
17451                    }
17452                    return;
17453                }
17454            }
17455
17456            // If any filters need to be verified, then all need to be.
17457            boolean needToVerify = false;
17458            for (PackageParser.Activity a : pkg.activities) {
17459                for (ActivityIntentInfo filter : a.intents) {
17460                    if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
17461                        if (DEBUG_DOMAIN_VERIFICATION) {
17462                            Slog.d(TAG,
17463                                    "Intent filter needs verification, so processing all filters");
17464                        }
17465                        needToVerify = true;
17466                        break;
17467                    }
17468                }
17469            }
17470
17471            if (needToVerify) {
17472                final int verificationId = mIntentFilterVerificationToken++;
17473                for (PackageParser.Activity a : pkg.activities) {
17474                    for (ActivityIntentInfo filter : a.intents) {
17475                        if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
17476                            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
17477                                    "Verification needed for IntentFilter:" + filter.toString());
17478                            mIntentFilterVerifier.addOneIntentFilterVerification(
17479                                    verifierUid, userId, verificationId, filter, packageName);
17480                            count++;
17481                        }
17482                    }
17483                }
17484            }
17485        }
17486
17487        if (count > 0) {
17488            if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
17489                    + " IntentFilter verification" + (count > 1 ? "s" : "")
17490                    +  " for userId:" + userId);
17491            mIntentFilterVerifier.startVerifications(userId);
17492        } else {
17493            if (DEBUG_DOMAIN_VERIFICATION) {
17494                Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
17495            }
17496        }
17497    }
17498
17499    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
17500        final ComponentName cn  = filter.activity.getComponentName();
17501        final String packageName = cn.getPackageName();
17502
17503        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
17504                packageName);
17505        if (ivi == null) {
17506            return true;
17507        }
17508        int status = ivi.getStatus();
17509        switch (status) {
17510            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
17511            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
17512                return true;
17513
17514            default:
17515                // Nothing to do
17516                return false;
17517        }
17518    }
17519
17520    private static boolean isMultiArch(ApplicationInfo info) {
17521        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
17522    }
17523
17524    private static boolean isExternal(PackageParser.Package pkg) {
17525        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17526    }
17527
17528    private static boolean isExternal(PackageSetting ps) {
17529        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
17530    }
17531
17532    private static boolean isSystemApp(PackageParser.Package pkg) {
17533        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
17534    }
17535
17536    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
17537        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
17538    }
17539
17540    private static boolean isOemApp(PackageParser.Package pkg) {
17541        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
17542    }
17543
17544    private static boolean isVendorApp(PackageParser.Package pkg) {
17545        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
17546    }
17547
17548    private static boolean isProductApp(PackageParser.Package pkg) {
17549        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
17550    }
17551
17552    private static boolean hasDomainURLs(PackageParser.Package pkg) {
17553        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
17554    }
17555
17556    private static boolean isSystemApp(PackageSetting ps) {
17557        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
17558    }
17559
17560    private static boolean isUpdatedSystemApp(PackageSetting ps) {
17561        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
17562    }
17563
17564    private int packageFlagsToInstallFlags(PackageSetting ps) {
17565        int installFlags = 0;
17566        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
17567            // This existing package was an external ASEC install when we have
17568            // the external flag without a UUID
17569            installFlags |= PackageManager.INSTALL_EXTERNAL;
17570        }
17571        if (ps.isForwardLocked()) {
17572            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
17573        }
17574        return installFlags;
17575    }
17576
17577    private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
17578        if (isExternal(pkg)) {
17579            if (TextUtils.isEmpty(pkg.volumeUuid)) {
17580                return mSettings.getExternalVersion();
17581            } else {
17582                return mSettings.findOrCreateVersion(pkg.volumeUuid);
17583            }
17584        } else {
17585            return mSettings.getInternalVersion();
17586        }
17587    }
17588
17589    private void deleteTempPackageFiles() {
17590        final FilenameFilter filter = new FilenameFilter() {
17591            public boolean accept(File dir, String name) {
17592                return name.startsWith("vmdl") && name.endsWith(".tmp");
17593            }
17594        };
17595        for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) {
17596            file.delete();
17597        }
17598    }
17599
17600    @Override
17601    public void deletePackageAsUser(String packageName, int versionCode,
17602            IPackageDeleteObserver observer, int userId, int flags) {
17603        deletePackageVersioned(new VersionedPackage(packageName, versionCode),
17604                new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
17605    }
17606
17607    @Override
17608    public void deletePackageVersioned(VersionedPackage versionedPackage,
17609            final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
17610        final int callingUid = Binder.getCallingUid();
17611        mContext.enforceCallingOrSelfPermission(
17612                android.Manifest.permission.DELETE_PACKAGES, null);
17613        final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
17614        Preconditions.checkNotNull(versionedPackage);
17615        Preconditions.checkNotNull(observer);
17616        Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
17617                PackageManager.VERSION_CODE_HIGHEST,
17618                Long.MAX_VALUE, "versionCode must be >= -1");
17619
17620        final String packageName = versionedPackage.getPackageName();
17621        final long versionCode = versionedPackage.getLongVersionCode();
17622        final String internalPackageName;
17623        synchronized (mPackages) {
17624            // Normalize package name to handle renamed packages and static libs
17625            internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
17626        }
17627
17628        final int uid = Binder.getCallingUid();
17629        if (!isOrphaned(internalPackageName)
17630                && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
17631            try {
17632                final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
17633                intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
17634                intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
17635                observer.onUserActionRequired(intent);
17636            } catch (RemoteException re) {
17637            }
17638            return;
17639        }
17640        final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
17641        final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId };
17642        if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
17643            mContext.enforceCallingOrSelfPermission(
17644                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
17645                    "deletePackage for user " + userId);
17646        }
17647
17648        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
17649            try {
17650                observer.onPackageDeleted(packageName,
17651                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
17652            } catch (RemoteException re) {
17653            }
17654            return;
17655        }
17656
17657        if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
17658            try {
17659                observer.onPackageDeleted(packageName,
17660                        PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
17661            } catch (RemoteException re) {
17662            }
17663            return;
17664        }
17665
17666        if (DEBUG_REMOVE) {
17667            Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
17668                    + " deleteAllUsers: " + deleteAllUsers + " version="
17669                    + (versionCode == PackageManager.VERSION_CODE_HIGHEST
17670                    ? "VERSION_CODE_HIGHEST" : versionCode));
17671        }
17672        // Queue up an async operation since the package deletion may take a little while.
17673        mHandler.post(new Runnable() {
17674            public void run() {
17675                mHandler.removeCallbacks(this);
17676                int returnCode;
17677                final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
17678                boolean doDeletePackage = true;
17679                if (ps != null) {
17680                    final boolean targetIsInstantApp =
17681                            ps.getInstantApp(UserHandle.getUserId(callingUid));
17682                    doDeletePackage = !targetIsInstantApp
17683                            || canViewInstantApps;
17684                }
17685                if (doDeletePackage) {
17686                    if (!deleteAllUsers) {
17687                        returnCode = deletePackageX(internalPackageName, versionCode,
17688                                userId, deleteFlags);
17689                    } else {
17690                        int[] blockUninstallUserIds = getBlockUninstallForUsers(
17691                                internalPackageName, users);
17692                        // If nobody is blocking uninstall, proceed with delete for all users
17693                        if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
17694                            returnCode = deletePackageX(internalPackageName, versionCode,
17695                                    userId, deleteFlags);
17696                        } else {
17697                            // Otherwise uninstall individually for users with blockUninstalls=false
17698                            final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
17699                            for (int userId : users) {
17700                                if (!ArrayUtils.contains(blockUninstallUserIds, userId)) {
17701                                    returnCode = deletePackageX(internalPackageName, versionCode,
17702                                            userId, userFlags);
17703                                    if (returnCode != PackageManager.DELETE_SUCCEEDED) {
17704                                        Slog.w(TAG, "Package delete failed for user " + userId
17705                                                + ", returnCode " + returnCode);
17706                                    }
17707                                }
17708                            }
17709                            // The app has only been marked uninstalled for certain users.
17710                            // We still need to report that delete was blocked
17711                            returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
17712                        }
17713                    }
17714                } else {
17715                    returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17716                }
17717                try {
17718                    observer.onPackageDeleted(packageName, returnCode, null);
17719                } catch (RemoteException e) {
17720                    Log.i(TAG, "Observer no longer exists.");
17721                } //end catch
17722            } //end run
17723        });
17724    }
17725
17726    private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
17727        if (pkg.staticSharedLibName != null) {
17728            return pkg.manifestPackageName;
17729        }
17730        return pkg.packageName;
17731    }
17732
17733    private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
17734        // Handle renamed packages
17735        String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
17736        packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
17737
17738        // Is this a static library?
17739        LongSparseArray<SharedLibraryEntry> versionedLib =
17740                mStaticLibsByDeclaringPackage.get(packageName);
17741        if (versionedLib == null || versionedLib.size() <= 0) {
17742            return packageName;
17743        }
17744
17745        // Figure out which lib versions the caller can see
17746        LongSparseLongArray versionsCallerCanSee = null;
17747        final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
17748        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
17749                && callingAppId != Process.ROOT_UID) {
17750            versionsCallerCanSee = new LongSparseLongArray();
17751            String libName = versionedLib.valueAt(0).info.getName();
17752            String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
17753            if (uidPackages != null) {
17754                for (String uidPackage : uidPackages) {
17755                    PackageSetting ps = mSettings.getPackageLPr(uidPackage);
17756                    final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
17757                    if (libIdx >= 0) {
17758                        final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
17759                        versionsCallerCanSee.append(libVersion, libVersion);
17760                    }
17761                }
17762            }
17763        }
17764
17765        // Caller can see nothing - done
17766        if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
17767            return packageName;
17768        }
17769
17770        // Find the version the caller can see and the app version code
17771        SharedLibraryEntry highestVersion = null;
17772        final int versionCount = versionedLib.size();
17773        for (int i = 0; i < versionCount; i++) {
17774            SharedLibraryEntry libEntry = versionedLib.valueAt(i);
17775            if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
17776                    libEntry.info.getLongVersion()) < 0) {
17777                continue;
17778            }
17779            final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode();
17780            if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
17781                if (libVersionCode == versionCode) {
17782                    return libEntry.apk;
17783                }
17784            } else if (highestVersion == null) {
17785                highestVersion = libEntry;
17786            } else if (libVersionCode  > highestVersion.info
17787                    .getDeclaringPackage().getLongVersionCode()) {
17788                highestVersion = libEntry;
17789            }
17790        }
17791
17792        if (highestVersion != null) {
17793            return highestVersion.apk;
17794        }
17795
17796        return packageName;
17797    }
17798
17799    boolean isCallerVerifier(int callingUid) {
17800        final int callingUserId = UserHandle.getUserId(callingUid);
17801        return mRequiredVerifierPackage != null &&
17802                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
17803    }
17804
17805    private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
17806        if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
17807              || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
17808            return true;
17809        }
17810        final int callingUserId = UserHandle.getUserId(callingUid);
17811        // If the caller installed the pkgName, then allow it to silently uninstall.
17812        if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
17813            return true;
17814        }
17815
17816        // Allow package verifier to silently uninstall.
17817        if (mRequiredVerifierPackage != null &&
17818                callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
17819            return true;
17820        }
17821
17822        // Allow package uninstaller to silently uninstall.
17823        if (mRequiredUninstallerPackage != null &&
17824                callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
17825            return true;
17826        }
17827
17828        // Allow storage manager to silently uninstall.
17829        if (mStorageManagerPackage != null &&
17830                callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
17831            return true;
17832        }
17833
17834        // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
17835        // uninstall for device owner provisioning.
17836        if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
17837                == PERMISSION_GRANTED) {
17838            return true;
17839        }
17840
17841        return false;
17842    }
17843
17844    private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
17845        int[] result = EMPTY_INT_ARRAY;
17846        for (int userId : userIds) {
17847            if (getBlockUninstallForUser(packageName, userId)) {
17848                result = ArrayUtils.appendInt(result, userId);
17849            }
17850        }
17851        return result;
17852    }
17853
17854    @Override
17855    public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
17856        final int callingUid = Binder.getCallingUid();
17857        if (getInstantAppPackageName(callingUid) != null
17858                && !isCallerSameApp(packageName, callingUid)) {
17859            return false;
17860        }
17861        return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
17862    }
17863
17864    private boolean isPackageDeviceAdmin(String packageName, int userId) {
17865        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
17866                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
17867        try {
17868            if (dpm != null) {
17869                final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
17870                        /* callingUserOnly =*/ false);
17871                final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
17872                        : deviceOwnerComponentName.getPackageName();
17873                // Does the package contains the device owner?
17874                // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
17875                // this check is probably not needed, since DO should be registered as a device
17876                // admin on some user too. (Original bug for this: b/17657954)
17877                if (packageName.equals(deviceOwnerPackageName)) {
17878                    return true;
17879                }
17880                // Does it contain a device admin for any user?
17881                int[] users;
17882                if (userId == UserHandle.USER_ALL) {
17883                    users = sUserManager.getUserIds();
17884                } else {
17885                    users = new int[]{userId};
17886                }
17887                for (int i = 0; i < users.length; ++i) {
17888                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
17889                        return true;
17890                    }
17891                }
17892            }
17893        } catch (RemoteException e) {
17894        }
17895        return false;
17896    }
17897
17898    private boolean shouldKeepUninstalledPackageLPr(String packageName) {
17899        return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
17900    }
17901
17902    /**
17903     *  This method is an internal method that could be get invoked either
17904     *  to delete an installed package or to clean up a failed installation.
17905     *  After deleting an installed package, a broadcast is sent to notify any
17906     *  listeners that the package has been removed. For cleaning up a failed
17907     *  installation, the broadcast is not necessary since the package's
17908     *  installation wouldn't have sent the initial broadcast either
17909     *  The key steps in deleting a package are
17910     *  deleting the package information in internal structures like mPackages,
17911     *  deleting the packages base directories through installd
17912     *  updating mSettings to reflect current status
17913     *  persisting settings for later use
17914     *  sending a broadcast if necessary
17915     */
17916    int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
17917        final PackageRemovedInfo info = new PackageRemovedInfo(this);
17918        final boolean res;
17919
17920        final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
17921                ? UserHandle.USER_ALL : userId;
17922
17923        if (isPackageDeviceAdmin(packageName, removeUser)) {
17924            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
17925            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
17926        }
17927
17928        PackageSetting uninstalledPs = null;
17929        PackageParser.Package pkg = null;
17930
17931        // for the uninstall-updates case and restricted profiles, remember the per-
17932        // user handle installed state
17933        int[] allUsers;
17934        synchronized (mPackages) {
17935            uninstalledPs = mSettings.mPackages.get(packageName);
17936            if (uninstalledPs == null) {
17937                Slog.w(TAG, "Not removing non-existent package " + packageName);
17938                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17939            }
17940
17941            if (versionCode != PackageManager.VERSION_CODE_HIGHEST
17942                    && uninstalledPs.versionCode != versionCode) {
17943                Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
17944                        + uninstalledPs.versionCode + " != " + versionCode);
17945                return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
17946            }
17947
17948            // Static shared libs can be declared by any package, so let us not
17949            // allow removing a package if it provides a lib others depend on.
17950            pkg = mPackages.get(packageName);
17951
17952            allUsers = sUserManager.getUserIds();
17953
17954            if (pkg != null && pkg.staticSharedLibName != null) {
17955                SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName,
17956                        pkg.staticSharedLibVersion);
17957                if (libEntry != null) {
17958                    for (int currUserId : allUsers) {
17959                        if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
17960                            continue;
17961                        }
17962                        List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
17963                                libEntry.info, 0, currUserId);
17964                        if (!ArrayUtils.isEmpty(libClientPackages)) {
17965                            Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
17966                                    + " hosting lib " + libEntry.info.getName() + " version "
17967                                    + libEntry.info.getLongVersion() + " used by " + libClientPackages
17968                                    + " for user " + currUserId);
17969                            return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
17970                        }
17971                    }
17972                }
17973            }
17974
17975            info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
17976        }
17977
17978        final int freezeUser;
17979        if (isUpdatedSystemApp(uninstalledPs)
17980                && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
17981            // We're downgrading a system app, which will apply to all users, so
17982            // freeze them all during the downgrade
17983            freezeUser = UserHandle.USER_ALL;
17984        } else {
17985            freezeUser = removeUser;
17986        }
17987
17988        synchronized (mInstallLock) {
17989            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
17990            try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
17991                    deleteFlags, "deletePackageX")) {
17992                res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
17993                        deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
17994            }
17995            synchronized (mPackages) {
17996                if (res) {
17997                    if (pkg != null) {
17998                        mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
17999                    }
18000                    updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18001                    updateInstantAppInstallerLocked(packageName);
18002                }
18003            }
18004        }
18005
18006        if (res) {
18007            final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18008            info.sendPackageRemovedBroadcasts(killApp);
18009            info.sendSystemPackageUpdatedBroadcasts();
18010            info.sendSystemPackageAppearedBroadcasts();
18011        }
18012        // Force a gc here.
18013        Runtime.getRuntime().gc();
18014        // Delete the resources here after sending the broadcast to let
18015        // other processes clean up before deleting resources.
18016        if (info.args != null) {
18017            synchronized (mInstallLock) {
18018                info.args.doPostDeleteLI(true);
18019            }
18020        }
18021
18022        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18023    }
18024
18025    static class PackageRemovedInfo {
18026        final PackageSender packageSender;
18027        String removedPackage;
18028        String installerPackageName;
18029        int uid = -1;
18030        int removedAppId = -1;
18031        int[] origUsers;
18032        int[] removedUsers = null;
18033        int[] broadcastUsers = null;
18034        int[] instantUserIds = null;
18035        SparseArray<Integer> installReasons;
18036        boolean isRemovedPackageSystemUpdate = false;
18037        boolean isUpdate;
18038        boolean dataRemoved;
18039        boolean removedForAllUsers;
18040        boolean isStaticSharedLib;
18041        // Clean up resources deleted packages.
18042        InstallArgs args = null;
18043        ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18044        ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18045
18046        PackageRemovedInfo(PackageSender packageSender) {
18047            this.packageSender = packageSender;
18048        }
18049
18050        void sendPackageRemovedBroadcasts(boolean killApp) {
18051            sendPackageRemovedBroadcastInternal(killApp);
18052            final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18053            for (int i = 0; i < childCount; i++) {
18054                PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18055                childInfo.sendPackageRemovedBroadcastInternal(killApp);
18056            }
18057        }
18058
18059        void sendSystemPackageUpdatedBroadcasts() {
18060            if (isRemovedPackageSystemUpdate) {
18061                sendSystemPackageUpdatedBroadcastsInternal();
18062                final int childCount = (removedChildPackages != null)
18063                        ? removedChildPackages.size() : 0;
18064                for (int i = 0; i < childCount; i++) {
18065                    PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18066                    if (childInfo.isRemovedPackageSystemUpdate) {
18067                        childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18068                    }
18069                }
18070            }
18071        }
18072
18073        void sendSystemPackageAppearedBroadcasts() {
18074            final int packageCount = (appearedChildPackages != null)
18075                    ? appearedChildPackages.size() : 0;
18076            for (int i = 0; i < packageCount; i++) {
18077                PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18078                packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18079                    true /*sendBootCompleted*/, false /*startReceiver*/,
18080                    UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18081            }
18082        }
18083
18084        private void sendSystemPackageUpdatedBroadcastsInternal() {
18085            Bundle extras = new Bundle(2);
18086            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18087            extras.putBoolean(Intent.EXTRA_REPLACING, true);
18088            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18089                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18090            packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18091                removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18092            packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18093                null, null, 0, removedPackage, null, null, null);
18094            if (installerPackageName != null) {
18095                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18096                        removedPackage, extras, 0 /*flags*/,
18097                        installerPackageName, null, null, null);
18098                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18099                        removedPackage, extras, 0 /*flags*/,
18100                        installerPackageName, null, null, null);
18101            }
18102        }
18103
18104        private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18105            // Don't send static shared library removal broadcasts as these
18106            // libs are visible only the the apps that depend on them an one
18107            // cannot remove the library if it has a dependency.
18108            if (isStaticSharedLib) {
18109                return;
18110            }
18111            Bundle extras = new Bundle(2);
18112            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0  ? removedAppId : uid);
18113            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18114            extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18115            if (isUpdate || isRemovedPackageSystemUpdate) {
18116                extras.putBoolean(Intent.EXTRA_REPLACING, true);
18117            }
18118            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18119            if (removedPackage != null) {
18120                packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18121                    removedPackage, extras, 0, null /*targetPackage*/, null,
18122                    broadcastUsers, instantUserIds);
18123                if (installerPackageName != null) {
18124                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18125                            removedPackage, extras, 0 /*flags*/,
18126                            installerPackageName, null, broadcastUsers, instantUserIds);
18127                }
18128                if (dataRemoved && !isRemovedPackageSystemUpdate) {
18129                    packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18130                        removedPackage, extras,
18131                        Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18132                        null, null, broadcastUsers, instantUserIds);
18133                    packageSender.notifyPackageRemoved(removedPackage);
18134                }
18135            }
18136            if (removedAppId >= 0) {
18137                packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18138                    null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18139                    null, null, broadcastUsers, instantUserIds);
18140            }
18141        }
18142
18143        void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18144            removedUsers = userIds;
18145            if (removedUsers == null) {
18146                broadcastUsers = null;
18147                return;
18148            }
18149
18150            broadcastUsers = EMPTY_INT_ARRAY;
18151            instantUserIds = EMPTY_INT_ARRAY;
18152            for (int i = userIds.length - 1; i >= 0; --i) {
18153                final int userId = userIds[i];
18154                if (deletedPackageSetting.getInstantApp(userId)) {
18155                    instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18156                } else {
18157                    broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18158                }
18159            }
18160        }
18161    }
18162
18163    /*
18164     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18165     * flag is not set, the data directory is removed as well.
18166     * make sure this flag is set for partially installed apps. If not its meaningless to
18167     * delete a partially installed application.
18168     */
18169    private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles,
18170            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18171        String packageName = ps.name;
18172        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
18173        // Retrieve object to delete permissions for shared user later on
18174        final PackageParser.Package deletedPkg;
18175        final PackageSetting deletedPs;
18176        // reader
18177        synchronized (mPackages) {
18178            deletedPkg = mPackages.get(packageName);
18179            deletedPs = mSettings.mPackages.get(packageName);
18180            if (outInfo != null) {
18181                outInfo.removedPackage = packageName;
18182                outInfo.installerPackageName = ps.installerPackageName;
18183                outInfo.isStaticSharedLib = deletedPkg != null
18184                        && deletedPkg.staticSharedLibName != null;
18185                outInfo.populateUsers(deletedPs == null ? null
18186                        : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18187            }
18188        }
18189
18190        removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0);
18191
18192        if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18193            final PackageParser.Package resolvedPkg;
18194            if (deletedPkg != null) {
18195                resolvedPkg = deletedPkg;
18196            } else {
18197                // We don't have a parsed package when it lives on an ejected
18198                // adopted storage device, so fake something together
18199                resolvedPkg = new PackageParser.Package(ps.name);
18200                resolvedPkg.setVolumeUuid(ps.volumeUuid);
18201            }
18202            destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18203                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18204            destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL);
18205            if (outInfo != null) {
18206                outInfo.dataRemoved = true;
18207            }
18208            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
18209        }
18210
18211        int removedAppId = -1;
18212
18213        // writer
18214        synchronized (mPackages) {
18215            boolean installedStateChanged = false;
18216            if (deletedPs != null) {
18217                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
18218                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18219                    clearDefaultBrowserIfNeeded(packageName);
18220                    mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18221                    removedAppId = mSettings.removePackageLPw(packageName);
18222                    if (outInfo != null) {
18223                        outInfo.removedAppId = removedAppId;
18224                    }
18225                    mPermissionManager.updatePermissions(
18226                            deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18227                    if (deletedPs.sharedUser != null) {
18228                        // Remove permissions associated with package. Since runtime
18229                        // permissions are per user we have to kill the removed package
18230                        // or packages running under the shared user of the removed
18231                        // package if revoking the permissions requested only by the removed
18232                        // package is successful and this causes a change in gids.
18233                        for (int userId : UserManagerService.getInstance().getUserIds()) {
18234                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18235                                    userId);
18236                            if (userIdToKill == UserHandle.USER_ALL
18237                                    || userIdToKill >= UserHandle.USER_SYSTEM) {
18238                                // If gids changed for this user, kill all affected packages.
18239                                mHandler.post(new Runnable() {
18240                                    @Override
18241                                    public void run() {
18242                                        // This has to happen with no lock held.
18243                                        killApplication(deletedPs.name, deletedPs.appId,
18244                                                KILL_APP_REASON_GIDS_CHANGED);
18245                                    }
18246                                });
18247                                break;
18248                            }
18249                        }
18250                    }
18251                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
18252                }
18253                // make sure to preserve per-user disabled state if this removal was just
18254                // a downgrade of a system app to the factory package
18255                if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18256                    if (DEBUG_REMOVE) {
18257                        Slog.d(TAG, "Propagating install state across downgrade");
18258                    }
18259                    for (int userId : allUserHandles) {
18260                        final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18261                        if (DEBUG_REMOVE) {
18262                            Slog.d(TAG, "    user " + userId + " => " + installed);
18263                        }
18264                        if (installed != ps.getInstalled(userId)) {
18265                            installedStateChanged = true;
18266                        }
18267                        ps.setInstalled(installed, userId);
18268                    }
18269                }
18270            }
18271            // can downgrade to reader
18272            if (writeSettings) {
18273                // Save settings now
18274                mSettings.writeLPr();
18275            }
18276            if (installedStateChanged) {
18277                mSettings.writeKernelMappingLPr(ps);
18278            }
18279        }
18280        if (removedAppId != -1) {
18281            // A user ID was deleted here. Go through all users and remove it
18282            // from KeyStore.
18283            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18284        }
18285    }
18286
18287    static boolean locationIsPrivileged(String path) {
18288        try {
18289            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18290            final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18291            final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18292            final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18293            return path.startsWith(privilegedAppDir.getCanonicalPath())
18294                    || path.startsWith(privilegedVendorAppDir.getCanonicalPath())
18295                    || path.startsWith(privilegedOdmAppDir.getCanonicalPath())
18296                    || path.startsWith(privilegedProductAppDir.getCanonicalPath());
18297        } catch (IOException e) {
18298            Slog.e(TAG, "Unable to access code path " + path);
18299        }
18300        return false;
18301    }
18302
18303    static boolean locationIsOem(String path) {
18304        try {
18305            return path.startsWith(Environment.getOemDirectory().getCanonicalPath());
18306        } catch (IOException e) {
18307            Slog.e(TAG, "Unable to access code path " + path);
18308        }
18309        return false;
18310    }
18311
18312    static boolean locationIsVendor(String path) {
18313        try {
18314            return path.startsWith(Environment.getVendorDirectory().getCanonicalPath())
18315                    || path.startsWith(Environment.getOdmDirectory().getCanonicalPath());
18316        } catch (IOException e) {
18317            Slog.e(TAG, "Unable to access code path " + path);
18318        }
18319        return false;
18320    }
18321
18322    static boolean locationIsProduct(String path) {
18323        try {
18324            return path.startsWith(Environment.getProductDirectory().getCanonicalPath());
18325        } catch (IOException e) {
18326            Slog.e(TAG, "Unable to access code path " + path);
18327        }
18328        return false;
18329    }
18330
18331    /*
18332     * Tries to delete system package.
18333     */
18334    private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg,
18335            PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo,
18336            boolean writeSettings) {
18337        if (deletedPs.parentPackageName != null) {
18338            Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName);
18339            return false;
18340        }
18341
18342        final boolean applyUserRestrictions
18343                = (allUserHandles != null) && (outInfo.origUsers != null);
18344        final PackageSetting disabledPs;
18345        // Confirm if the system package has been updated
18346        // An updated system app can be deleted. This will also have to restore
18347        // the system pkg from system partition
18348        // reader
18349        synchronized (mPackages) {
18350            disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name);
18351        }
18352
18353        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
18354                + " disabledPs=" + disabledPs);
18355
18356        if (disabledPs == null) {
18357            Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName);
18358            return false;
18359        } else if (DEBUG_REMOVE) {
18360            Slog.d(TAG, "Deleting system pkg from data partition");
18361        }
18362
18363        if (DEBUG_REMOVE) {
18364            if (applyUserRestrictions) {
18365                Slog.d(TAG, "Remembering install states:");
18366                for (int userId : allUserHandles) {
18367                    final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
18368                    Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
18369                }
18370            }
18371        }
18372
18373        // Delete the updated package
18374        outInfo.isRemovedPackageSystemUpdate = true;
18375        if (outInfo.removedChildPackages != null) {
18376            final int childCount = (deletedPs.childPackageNames != null)
18377                    ? deletedPs.childPackageNames.size() : 0;
18378            for (int i = 0; i < childCount; i++) {
18379                String childPackageName = deletedPs.childPackageNames.get(i);
18380                if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
18381                        .contains(childPackageName)) {
18382                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18383                            childPackageName);
18384                    if (childInfo != null) {
18385                        childInfo.isRemovedPackageSystemUpdate = true;
18386                    }
18387                }
18388            }
18389        }
18390
18391        if (disabledPs.versionCode < deletedPs.versionCode) {
18392            // Delete data for downgrades
18393            flags &= ~PackageManager.DELETE_KEEP_DATA;
18394        } else {
18395            // Preserve data by setting flag
18396            flags |= PackageManager.DELETE_KEEP_DATA;
18397        }
18398
18399        boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
18400                outInfo, writeSettings, disabledPs.pkg);
18401        if (!ret) {
18402            return false;
18403        }
18404
18405        // writer
18406        synchronized (mPackages) {
18407            // NOTE: The system package always needs to be enabled; even if it's for
18408            // a compressed stub. If we don't, installing the system package fails
18409            // during scan [scanning checks the disabled packages]. We will reverse
18410            // this later, after we've "installed" the stub.
18411            // Reinstate the old system package
18412            enableSystemPackageLPw(disabledPs.pkg);
18413            // Remove any native libraries from the upgraded package.
18414            removeNativeBinariesLI(deletedPs);
18415        }
18416
18417        // Install the system package
18418        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
18419        try {
18420            installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles,
18421                    outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
18422        } catch (PackageManagerException e) {
18423            Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
18424                    + e.getMessage());
18425            return false;
18426        } finally {
18427            if (disabledPs.pkg.isStub) {
18428                mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/);
18429            }
18430        }
18431        return true;
18432    }
18433
18434    /**
18435     * Installs a package that's already on the system partition.
18436     */
18437    private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
18438            boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
18439            @Nullable PermissionsState origPermissionState, boolean writeSettings)
18440                    throws PackageManagerException {
18441        @ParseFlags int parseFlags =
18442                mDefParseFlags
18443                | PackageParser.PARSE_MUST_BE_APK
18444                | PackageParser.PARSE_IS_SYSTEM_DIR;
18445        @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
18446        if (isPrivileged || locationIsPrivileged(codePathString)) {
18447            scanFlags |= SCAN_AS_PRIVILEGED;
18448        }
18449        if (locationIsOem(codePathString)) {
18450            scanFlags |= SCAN_AS_OEM;
18451        }
18452        if (locationIsVendor(codePathString)) {
18453            scanFlags |= SCAN_AS_VENDOR;
18454        }
18455        if (locationIsProduct(codePathString)) {
18456            scanFlags |= SCAN_AS_PRODUCT;
18457        }
18458
18459        final File codePath = new File(codePathString);
18460        final PackageParser.Package pkg =
18461                scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
18462
18463        try {
18464            // update shared libraries for the newly re-installed system package
18465            updateSharedLibrariesLPr(pkg, null);
18466        } catch (PackageManagerException e) {
18467            Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
18468        }
18469
18470        prepareAppDataAfterInstallLIF(pkg);
18471
18472        // writer
18473        synchronized (mPackages) {
18474            PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
18475
18476            // Propagate the permissions state as we do not want to drop on the floor
18477            // runtime permissions. The update permissions method below will take
18478            // care of removing obsolete permissions and grant install permissions.
18479            if (origPermissionState != null) {
18480                ps.getPermissionsState().copyFrom(origPermissionState);
18481            }
18482            mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
18483                    mPermissionCallback);
18484
18485            final boolean applyUserRestrictions
18486                    = (allUserHandles != null) && (origUserHandles != null);
18487            if (applyUserRestrictions) {
18488                boolean installedStateChanged = false;
18489                if (DEBUG_REMOVE) {
18490                    Slog.d(TAG, "Propagating install state across reinstall");
18491                }
18492                for (int userId : allUserHandles) {
18493                    final boolean installed = ArrayUtils.contains(origUserHandles, userId);
18494                    if (DEBUG_REMOVE) {
18495                        Slog.d(TAG, "    user " + userId + " => " + installed);
18496                    }
18497                    if (installed != ps.getInstalled(userId)) {
18498                        installedStateChanged = true;
18499                    }
18500                    ps.setInstalled(installed, userId);
18501
18502                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
18503                }
18504                // Regardless of writeSettings we need to ensure that this restriction
18505                // state propagation is persisted
18506                mSettings.writeAllUsersPackageRestrictionsLPr();
18507                if (installedStateChanged) {
18508                    mSettings.writeKernelMappingLPr(ps);
18509                }
18510            }
18511            // can downgrade to reader here
18512            if (writeSettings) {
18513                mSettings.writeLPr();
18514            }
18515        }
18516        return pkg;
18517    }
18518
18519    private boolean deleteInstalledPackageLIF(PackageSetting ps,
18520            boolean deleteCodeAndResources, int flags, int[] allUserHandles,
18521            PackageRemovedInfo outInfo, boolean writeSettings,
18522            PackageParser.Package replacingPackage) {
18523        synchronized (mPackages) {
18524            if (outInfo != null) {
18525                outInfo.uid = ps.appId;
18526            }
18527
18528            if (outInfo != null && outInfo.removedChildPackages != null) {
18529                final int childCount = (ps.childPackageNames != null)
18530                        ? ps.childPackageNames.size() : 0;
18531                for (int i = 0; i < childCount; i++) {
18532                    String childPackageName = ps.childPackageNames.get(i);
18533                    PackageSetting childPs = mSettings.mPackages.get(childPackageName);
18534                    if (childPs == null) {
18535                        return false;
18536                    }
18537                    PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
18538                            childPackageName);
18539                    if (childInfo != null) {
18540                        childInfo.uid = childPs.appId;
18541                    }
18542                }
18543            }
18544        }
18545
18546        // Delete package data from internal structures and also remove data if flag is set
18547        removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
18548
18549        // Delete the child packages data
18550        final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
18551        for (int i = 0; i < childCount; i++) {
18552            PackageSetting childPs;
18553            synchronized (mPackages) {
18554                childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
18555            }
18556            if (childPs != null) {
18557                PackageRemovedInfo childOutInfo = (outInfo != null
18558                        && outInfo.removedChildPackages != null)
18559                        ? outInfo.removedChildPackages.get(childPs.name) : null;
18560                final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
18561                        && (replacingPackage != null
18562                        && !replacingPackage.hasChildPackage(childPs.name))
18563                        ? flags & ~DELETE_KEEP_DATA : flags;
18564                removePackageDataLIF(childPs, allUserHandles, childOutInfo,
18565                        deleteFlags, writeSettings);
18566            }
18567        }
18568
18569        // Delete application code and resources only for parent packages
18570        if (ps.parentPackageName == null) {
18571            if (deleteCodeAndResources && (outInfo != null)) {
18572                outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
18573                        ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
18574                if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
18575            }
18576        }
18577
18578        return true;
18579    }
18580
18581    @Override
18582    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
18583            int userId) {
18584        mContext.enforceCallingOrSelfPermission(
18585                android.Manifest.permission.DELETE_PACKAGES, null);
18586        synchronized (mPackages) {
18587            // Cannot block uninstall of static shared libs as they are
18588            // considered a part of the using app (emulating static linking).
18589            // Also static libs are installed always on internal storage.
18590            PackageParser.Package pkg = mPackages.get(packageName);
18591            if (pkg != null && pkg.staticSharedLibName != null) {
18592                Slog.w(TAG, "Cannot block uninstall of package: " + packageName
18593                        + " providing static shared library: " + pkg.staticSharedLibName);
18594                return false;
18595            }
18596            mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
18597            mSettings.writePackageRestrictionsLPr(userId);
18598        }
18599        return true;
18600    }
18601
18602    @Override
18603    public boolean getBlockUninstallForUser(String packageName, int userId) {
18604        synchronized (mPackages) {
18605            final PackageSetting ps = mSettings.mPackages.get(packageName);
18606            if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
18607                return false;
18608            }
18609            return mSettings.getBlockUninstallLPr(userId, packageName);
18610        }
18611    }
18612
18613    @Override
18614    public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
18615        enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
18616        synchronized (mPackages) {
18617            PackageSetting ps = mSettings.mPackages.get(packageName);
18618            if (ps == null) {
18619                Log.w(TAG, "Package doesn't exist: " + packageName);
18620                return false;
18621            }
18622            if (systemUserApp) {
18623                ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18624            } else {
18625                ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
18626            }
18627            mSettings.writeLPr();
18628        }
18629        return true;
18630    }
18631
18632    /*
18633     * This method handles package deletion in general
18634     */
18635    private boolean deletePackageLIF(String packageName, UserHandle user,
18636            boolean deleteCodeAndResources, int[] allUserHandles, int flags,
18637            PackageRemovedInfo outInfo, boolean writeSettings,
18638            PackageParser.Package replacingPackage) {
18639        if (packageName == null) {
18640            Slog.w(TAG, "Attempt to delete null packageName.");
18641            return false;
18642        }
18643
18644        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
18645
18646        PackageSetting ps;
18647        synchronized (mPackages) {
18648            ps = mSettings.mPackages.get(packageName);
18649            if (ps == null) {
18650                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
18651                return false;
18652            }
18653
18654            if (ps.parentPackageName != null && (!isSystemApp(ps)
18655                    || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
18656                if (DEBUG_REMOVE) {
18657                    Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
18658                            + ((user == null) ? UserHandle.USER_ALL : user));
18659                }
18660                final int removedUserId = (user != null) ? user.getIdentifier()
18661                        : UserHandle.USER_ALL;
18662
18663                if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) {
18664                    return false;
18665                }
18666                markPackageUninstalledForUserLPw(ps, user);
18667                scheduleWritePackageRestrictionsLocked(user);
18668                return true;
18669            }
18670        }
18671        if (ps.getPermissionsState().hasPermission(
18672                Manifest.permission.SUSPEND_APPS, user.getIdentifier())) {
18673            onSuspendingPackageRemoved(packageName, user.getIdentifier());
18674        }
18675
18676
18677        if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
18678                && user.getIdentifier() != UserHandle.USER_ALL)) {
18679            // The caller is asking that the package only be deleted for a single
18680            // user.  To do this, we just mark its uninstalled state and delete
18681            // its data. If this is a system app, we only allow this to happen if
18682            // they have set the special DELETE_SYSTEM_APP which requests different
18683            // semantics than normal for uninstalling system apps.
18684            markPackageUninstalledForUserLPw(ps, user);
18685
18686            if (!isSystemApp(ps)) {
18687                // Do not uninstall the APK if an app should be cached
18688                boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
18689                if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
18690                    // Other user still have this package installed, so all
18691                    // we need to do is clear this user's data and save that
18692                    // it is uninstalled.
18693                    if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
18694                    if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18695                        return false;
18696                    }
18697                    scheduleWritePackageRestrictionsLocked(user);
18698                    return true;
18699                } else {
18700                    // We need to set it back to 'installed' so the uninstall
18701                    // broadcasts will be sent correctly.
18702                    if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
18703                    ps.setInstalled(true, user.getIdentifier());
18704                    mSettings.writeKernelMappingLPr(ps);
18705                }
18706            } else {
18707                // This is a system app, so we assume that the
18708                // other users still have this package installed, so all
18709                // we need to do is clear this user's data and save that
18710                // it is uninstalled.
18711                if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
18712                if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) {
18713                    return false;
18714                }
18715                scheduleWritePackageRestrictionsLocked(user);
18716                return true;
18717            }
18718        }
18719
18720        // If we are deleting a composite package for all users, keep track
18721        // of result for each child.
18722        if (ps.childPackageNames != null && outInfo != null) {
18723            synchronized (mPackages) {
18724                final int childCount = ps.childPackageNames.size();
18725                outInfo.removedChildPackages = new ArrayMap<>(childCount);
18726                for (int i = 0; i < childCount; i++) {
18727                    String childPackageName = ps.childPackageNames.get(i);
18728                    PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
18729                    childInfo.removedPackage = childPackageName;
18730                    childInfo.installerPackageName = ps.installerPackageName;
18731                    outInfo.removedChildPackages.put(childPackageName, childInfo);
18732                    PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18733                    if (childPs != null) {
18734                        childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
18735                    }
18736                }
18737            }
18738        }
18739
18740        boolean ret = false;
18741        if (isSystemApp(ps)) {
18742            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
18743            // When an updated system application is deleted we delete the existing resources
18744            // as well and fall back to existing code in system partition
18745            ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings);
18746        } else {
18747            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
18748            ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
18749                    outInfo, writeSettings, replacingPackage);
18750        }
18751
18752        // Take a note whether we deleted the package for all users
18753        if (outInfo != null) {
18754            outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
18755            if (outInfo.removedChildPackages != null) {
18756                synchronized (mPackages) {
18757                    final int childCount = outInfo.removedChildPackages.size();
18758                    for (int i = 0; i < childCount; i++) {
18759                        PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
18760                        if (childInfo != null) {
18761                            childInfo.removedForAllUsers = mPackages.get(
18762                                    childInfo.removedPackage) == null;
18763                        }
18764                    }
18765                }
18766            }
18767            // If we uninstalled an update to a system app there may be some
18768            // child packages that appeared as they are declared in the system
18769            // app but were not declared in the update.
18770            if (isSystemApp(ps)) {
18771                synchronized (mPackages) {
18772                    PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
18773                    final int childCount = (updatedPs.childPackageNames != null)
18774                            ? updatedPs.childPackageNames.size() : 0;
18775                    for (int i = 0; i < childCount; i++) {
18776                        String childPackageName = updatedPs.childPackageNames.get(i);
18777                        if (outInfo.removedChildPackages == null
18778                                || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
18779                            PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
18780                            if (childPs == null) {
18781                                continue;
18782                            }
18783                            PackageInstalledInfo installRes = new PackageInstalledInfo();
18784                            installRes.name = childPackageName;
18785                            installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
18786                            installRes.pkg = mPackages.get(childPackageName);
18787                            installRes.uid = childPs.pkg.applicationInfo.uid;
18788                            if (outInfo.appearedChildPackages == null) {
18789                                outInfo.appearedChildPackages = new ArrayMap<>();
18790                            }
18791                            outInfo.appearedChildPackages.put(childPackageName, installRes);
18792                        }
18793                    }
18794                }
18795            }
18796        }
18797
18798        return ret;
18799    }
18800
18801    private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
18802        final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
18803                ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
18804        for (int nextUserId : userIds) {
18805            if (DEBUG_REMOVE) {
18806                Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
18807            }
18808            ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
18809                    false /*installed*/,
18810                    true /*stopped*/,
18811                    true /*notLaunched*/,
18812                    false /*hidden*/,
18813                    false /*suspended*/,
18814                    null, /*suspendingPackage*/
18815                    null, /*suspendedAppExtras*/
18816                    null, /*suspendedLauncherExtras*/
18817                    false /*instantApp*/,
18818                    false /*virtualPreload*/,
18819                    null /*lastDisableAppCaller*/,
18820                    null /*enabledComponents*/,
18821                    null /*disabledComponents*/,
18822                    ps.readUserState(nextUserId).domainVerificationStatus,
18823                    0, PackageManager.INSTALL_REASON_UNKNOWN,
18824                    null /*harmfulAppWarning*/);
18825        }
18826        mSettings.writeKernelMappingLPr(ps);
18827    }
18828
18829    private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId,
18830            PackageRemovedInfo outInfo) {
18831        final PackageParser.Package pkg;
18832        synchronized (mPackages) {
18833            pkg = mPackages.get(ps.name);
18834        }
18835
18836        final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
18837                : new int[] {userId};
18838        for (int nextUserId : userIds) {
18839            if (DEBUG_REMOVE) {
18840                Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
18841                        + nextUserId);
18842            }
18843
18844            destroyAppDataLIF(pkg, userId,
18845                    StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
18846            destroyAppProfilesLIF(pkg, userId);
18847            clearDefaultBrowserIfNeededForUser(ps.name, userId);
18848            removeKeystoreDataIfNeeded(nextUserId, ps.appId);
18849            schedulePackageCleaning(ps.name, nextUserId, false);
18850            synchronized (mPackages) {
18851                if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) {
18852                    scheduleWritePackageRestrictionsLocked(nextUserId);
18853                }
18854                resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
18855            }
18856        }
18857
18858        if (outInfo != null) {
18859            outInfo.removedPackage = ps.name;
18860            outInfo.installerPackageName = ps.installerPackageName;
18861            outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
18862            outInfo.removedAppId = ps.appId;
18863            outInfo.removedUsers = userIds;
18864            outInfo.broadcastUsers = userIds;
18865        }
18866
18867        return true;
18868    }
18869
18870    private static final class ClearStorageConnection implements ServiceConnection {
18871        IMediaContainerService mContainerService;
18872
18873        @Override
18874        public void onServiceConnected(ComponentName name, IBinder service) {
18875            synchronized (this) {
18876                mContainerService = IMediaContainerService.Stub
18877                        .asInterface(Binder.allowBlocking(service));
18878                notifyAll();
18879            }
18880        }
18881
18882        @Override
18883        public void onServiceDisconnected(ComponentName name) {
18884        }
18885    }
18886
18887    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
18888        if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return;
18889
18890        final boolean mounted;
18891        if (Environment.isExternalStorageEmulated()) {
18892            mounted = true;
18893        } else {
18894            final String status = Environment.getExternalStorageState();
18895
18896            mounted = status.equals(Environment.MEDIA_MOUNTED)
18897                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
18898        }
18899
18900        if (!mounted) {
18901            return;
18902        }
18903
18904        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
18905        int[] users;
18906        if (userId == UserHandle.USER_ALL) {
18907            users = sUserManager.getUserIds();
18908        } else {
18909            users = new int[] { userId };
18910        }
18911        final ClearStorageConnection conn = new ClearStorageConnection();
18912        if (mContext.bindServiceAsUser(
18913                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) {
18914            try {
18915                for (int curUser : users) {
18916                    long timeout = SystemClock.uptimeMillis() + 5000;
18917                    synchronized (conn) {
18918                        long now;
18919                        while (conn.mContainerService == null &&
18920                                (now = SystemClock.uptimeMillis()) < timeout) {
18921                            try {
18922                                conn.wait(timeout - now);
18923                            } catch (InterruptedException e) {
18924                            }
18925                        }
18926                    }
18927                    if (conn.mContainerService == null) {
18928                        return;
18929                    }
18930
18931                    final UserEnvironment userEnv = new UserEnvironment(curUser);
18932                    clearDirectory(conn.mContainerService,
18933                            userEnv.buildExternalStorageAppCacheDirs(packageName));
18934                    if (allData) {
18935                        clearDirectory(conn.mContainerService,
18936                                userEnv.buildExternalStorageAppDataDirs(packageName));
18937                        clearDirectory(conn.mContainerService,
18938                                userEnv.buildExternalStorageAppMediaDirs(packageName));
18939                    }
18940                }
18941            } finally {
18942                mContext.unbindService(conn);
18943            }
18944        }
18945    }
18946
18947    @Override
18948    public void clearApplicationProfileData(String packageName) {
18949        enforceSystemOrRoot("Only the system can clear all profile data");
18950
18951        final PackageParser.Package pkg;
18952        synchronized (mPackages) {
18953            pkg = mPackages.get(packageName);
18954        }
18955
18956        try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
18957            synchronized (mInstallLock) {
18958                clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
18959            }
18960        }
18961    }
18962
18963    @Override
18964    public void clearApplicationUserData(final String packageName,
18965            final IPackageDataObserver observer, final int userId) {
18966        mContext.enforceCallingOrSelfPermission(
18967                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
18968
18969        final int callingUid = Binder.getCallingUid();
18970        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
18971                true /* requireFullPermission */, false /* checkShell */, "clear application data");
18972
18973        final PackageSetting ps = mSettings.getPackageLPr(packageName);
18974        final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
18975        if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
18976            throw new SecurityException("Cannot clear data for a protected package: "
18977                    + packageName);
18978        }
18979        // Queue up an async operation since the package deletion may take a little while.
18980        mHandler.post(new Runnable() {
18981            public void run() {
18982                mHandler.removeCallbacks(this);
18983                final boolean succeeded;
18984                if (!filterApp) {
18985                    try (PackageFreezer freezer = freezePackage(packageName,
18986                            "clearApplicationUserData")) {
18987                        synchronized (mInstallLock) {
18988                            succeeded = clearApplicationUserDataLIF(packageName, userId);
18989                        }
18990                        clearExternalStorageDataSync(packageName, userId, true);
18991                        synchronized (mPackages) {
18992                            mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
18993                                    packageName, userId);
18994                        }
18995                    }
18996                    if (succeeded) {
18997                        // invoke DeviceStorageMonitor's update method to clear any notifications
18998                        DeviceStorageMonitorInternal dsm = LocalServices
18999                                .getService(DeviceStorageMonitorInternal.class);
19000                        if (dsm != null) {
19001                            dsm.checkMemory();
19002                        }
19003                    }
19004                } else {
19005                    succeeded = false;
19006                }
19007                if (observer != null) {
19008                    try {
19009                        observer.onRemoveCompleted(packageName, succeeded);
19010                    } catch (RemoteException e) {
19011                        Log.i(TAG, "Observer no longer exists.");
19012                    }
19013                } //end if observer
19014            } //end run
19015        });
19016    }
19017
19018    private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19019        if (packageName == null) {
19020            Slog.w(TAG, "Attempt to delete null packageName.");
19021            return false;
19022        }
19023
19024        // Try finding details about the requested package
19025        PackageParser.Package pkg;
19026        synchronized (mPackages) {
19027            pkg = mPackages.get(packageName);
19028            if (pkg == null) {
19029                final PackageSetting ps = mSettings.mPackages.get(packageName);
19030                if (ps != null) {
19031                    pkg = ps.pkg;
19032                }
19033            }
19034
19035            if (pkg == null) {
19036                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19037                return false;
19038            }
19039
19040            PackageSetting ps = (PackageSetting) pkg.mExtras;
19041            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19042        }
19043
19044        clearAppDataLIF(pkg, userId,
19045                StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
19046
19047        final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19048        removeKeystoreDataIfNeeded(userId, appId);
19049
19050        UserManagerInternal umInternal = getUserManagerInternal();
19051        final int flags;
19052        if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19053            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19054        } else if (umInternal.isUserRunning(userId)) {
19055            flags = StorageManager.FLAG_STORAGE_DE;
19056        } else {
19057            flags = 0;
19058        }
19059        prepareAppDataContentsLIF(pkg, userId, flags);
19060
19061        return true;
19062    }
19063
19064    /**
19065     * Reverts user permission state changes (permissions and flags) in
19066     * all packages for a given user.
19067     *
19068     * @param userId The device user for which to do a reset.
19069     */
19070    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19071        final int packageCount = mPackages.size();
19072        for (int i = 0; i < packageCount; i++) {
19073            PackageParser.Package pkg = mPackages.valueAt(i);
19074            PackageSetting ps = (PackageSetting) pkg.mExtras;
19075            resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19076        }
19077    }
19078
19079    private void resetNetworkPolicies(int userId) {
19080        LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19081    }
19082
19083    /**
19084     * Reverts user permission state changes (permissions and flags).
19085     *
19086     * @param ps The package for which to reset.
19087     * @param userId The device user for which to do a reset.
19088     */
19089    private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19090            final PackageSetting ps, final int userId) {
19091        if (ps.pkg == null) {
19092            return;
19093        }
19094
19095        // These are flags that can change base on user actions.
19096        final int userSettableMask = FLAG_PERMISSION_USER_SET
19097                | FLAG_PERMISSION_USER_FIXED
19098                | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19099                | FLAG_PERMISSION_REVIEW_REQUIRED;
19100
19101        final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19102                | FLAG_PERMISSION_POLICY_FIXED;
19103
19104        boolean writeInstallPermissions = false;
19105        boolean writeRuntimePermissions = false;
19106
19107        final int permissionCount = ps.pkg.requestedPermissions.size();
19108        for (int i = 0; i < permissionCount; i++) {
19109            final String permName = ps.pkg.requestedPermissions.get(i);
19110            final BasePermission bp =
19111                    (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19112            if (bp == null) {
19113                continue;
19114            }
19115
19116            // If shared user we just reset the state to which only this app contributed.
19117            if (ps.sharedUser != null) {
19118                boolean used = false;
19119                final int packageCount = ps.sharedUser.packages.size();
19120                for (int j = 0; j < packageCount; j++) {
19121                    PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19122                    if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19123                            && pkg.pkg.requestedPermissions.contains(permName)) {
19124                        used = true;
19125                        break;
19126                    }
19127                }
19128                if (used) {
19129                    continue;
19130                }
19131            }
19132
19133            final PermissionsState permissionsState = ps.getPermissionsState();
19134
19135            final int oldFlags = permissionsState.getPermissionFlags(permName, userId);
19136
19137            // Always clear the user settable flags.
19138            final boolean hasInstallState =
19139                    permissionsState.getInstallPermissionState(permName) != null;
19140            // If permission review is enabled and this is a legacy app, mark the
19141            // permission as requiring a review as this is the initial state.
19142            int flags = 0;
19143            if (mSettings.mPermissions.mPermissionReviewRequired
19144                    && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
19145                flags |= FLAG_PERMISSION_REVIEW_REQUIRED;
19146            }
19147            if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) {
19148                if (hasInstallState) {
19149                    writeInstallPermissions = true;
19150                } else {
19151                    writeRuntimePermissions = true;
19152                }
19153            }
19154
19155            // Below is only runtime permission handling.
19156            if (!bp.isRuntime()) {
19157                continue;
19158            }
19159
19160            // Never clobber system or policy.
19161            if ((oldFlags & policyOrSystemFlags) != 0) {
19162                continue;
19163            }
19164
19165            // If this permission was granted by default, make sure it is.
19166            if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19167                if (permissionsState.grantRuntimePermission(bp, userId)
19168                        != PERMISSION_OPERATION_FAILURE) {
19169                    writeRuntimePermissions = true;
19170                }
19171            // If permission review is enabled the permissions for a legacy apps
19172            // are represented as constantly granted runtime ones, so don't revoke.
19173            } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19174                // Otherwise, reset the permission.
19175                final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId);
19176                switch (revokeResult) {
19177                    case PERMISSION_OPERATION_SUCCESS:
19178                    case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
19179                        writeRuntimePermissions = true;
19180                        final int appId = ps.appId;
19181                        mHandler.post(new Runnable() {
19182                            @Override
19183                            public void run() {
19184                                killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
19185                            }
19186                        });
19187                    } break;
19188                }
19189            }
19190        }
19191
19192        // Synchronously write as we are taking permissions away.
19193        if (writeRuntimePermissions) {
19194            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
19195        }
19196
19197        // Synchronously write as we are taking permissions away.
19198        if (writeInstallPermissions) {
19199            mSettings.writeLPr();
19200        }
19201    }
19202
19203    /**
19204     * Remove entries from the keystore daemon. Will only remove it if the
19205     * {@code appId} is valid.
19206     */
19207    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19208        if (appId < 0) {
19209            return;
19210        }
19211
19212        final KeyStore keyStore = KeyStore.getInstance();
19213        if (keyStore != null) {
19214            if (userId == UserHandle.USER_ALL) {
19215                for (final int individual : sUserManager.getUserIds()) {
19216                    keyStore.clearUid(UserHandle.getUid(individual, appId));
19217                }
19218            } else {
19219                keyStore.clearUid(UserHandle.getUid(userId, appId));
19220            }
19221        } else {
19222            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19223        }
19224    }
19225
19226    @Override
19227    public void deleteApplicationCacheFiles(final String packageName,
19228            final IPackageDataObserver observer) {
19229        final int userId = UserHandle.getCallingUserId();
19230        deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19231    }
19232
19233    @Override
19234    public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
19235            final IPackageDataObserver observer) {
19236        final int callingUid = Binder.getCallingUid();
19237        if (mContext.checkCallingOrSelfPermission(
19238                android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
19239                != PackageManager.PERMISSION_GRANTED) {
19240            // If the caller has the old delete cache permission, silently ignore.  Else throw.
19241            if (mContext.checkCallingOrSelfPermission(
19242                    android.Manifest.permission.DELETE_CACHE_FILES)
19243                    == PackageManager.PERMISSION_GRANTED) {
19244                Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
19245                        android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
19246                        ", silently ignoring");
19247                return;
19248            }
19249            mContext.enforceCallingOrSelfPermission(
19250                    android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
19251        }
19252        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19253                /* requireFullPermission= */ true, /* checkShell= */ false,
19254                "delete application cache files");
19255        final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
19256                android.Manifest.permission.ACCESS_INSTANT_APPS);
19257
19258        final PackageParser.Package pkg;
19259        synchronized (mPackages) {
19260            pkg = mPackages.get(packageName);
19261        }
19262
19263        // Queue up an async operation since the package deletion may take a little while.
19264        mHandler.post(new Runnable() {
19265            public void run() {
19266                final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
19267                boolean doClearData = true;
19268                if (ps != null) {
19269                    final boolean targetIsInstantApp =
19270                            ps.getInstantApp(UserHandle.getUserId(callingUid));
19271                    doClearData = !targetIsInstantApp
19272                            || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
19273                }
19274                if (doClearData) {
19275                    synchronized (mInstallLock) {
19276                        final int flags = StorageManager.FLAG_STORAGE_DE
19277                                | StorageManager.FLAG_STORAGE_CE;
19278                        // We're only clearing cache files, so we don't care if the
19279                        // app is unfrozen and still able to run
19280                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
19281                        clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
19282                    }
19283                    clearExternalStorageDataSync(packageName, userId, false);
19284                }
19285                if (observer != null) {
19286                    try {
19287                        observer.onRemoveCompleted(packageName, true);
19288                    } catch (RemoteException e) {
19289                        Log.i(TAG, "Observer no longer exists.");
19290                    }
19291                }
19292            }
19293        });
19294    }
19295
19296    @Override
19297    public void getPackageSizeInfo(final String packageName, int userHandle,
19298            final IPackageStatsObserver observer) {
19299        throw new UnsupportedOperationException(
19300                "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
19301    }
19302
19303    private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
19304        final PackageSetting ps;
19305        synchronized (mPackages) {
19306            ps = mSettings.mPackages.get(packageName);
19307            if (ps == null) {
19308                Slog.w(TAG, "Failed to find settings for " + packageName);
19309                return false;
19310            }
19311        }
19312
19313        final String[] packageNames = { packageName };
19314        final long[] ceDataInodes = { ps.getCeDataInode(userId) };
19315        final String[] codePaths = { ps.codePathString };
19316
19317        try {
19318            mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
19319                    ps.appId, ceDataInodes, codePaths, stats);
19320
19321            // For now, ignore code size of packages on system partition
19322            if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
19323                stats.codeSize = 0;
19324            }
19325
19326            // External clients expect these to be tracked separately
19327            stats.dataSize -= stats.cacheSize;
19328
19329        } catch (InstallerException e) {
19330            Slog.w(TAG, String.valueOf(e));
19331            return false;
19332        }
19333
19334        return true;
19335    }
19336
19337    private int getUidTargetSdkVersionLockedLPr(int uid) {
19338        Object obj = mSettings.getUserIdLPr(uid);
19339        if (obj instanceof SharedUserSetting) {
19340            final SharedUserSetting sus = (SharedUserSetting) obj;
19341            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
19342            final Iterator<PackageSetting> it = sus.packages.iterator();
19343            while (it.hasNext()) {
19344                final PackageSetting ps = it.next();
19345                if (ps.pkg != null) {
19346                    int v = ps.pkg.applicationInfo.targetSdkVersion;
19347                    if (v < vers) vers = v;
19348                }
19349            }
19350            return vers;
19351        } else if (obj instanceof PackageSetting) {
19352            final PackageSetting ps = (PackageSetting) obj;
19353            if (ps.pkg != null) {
19354                return ps.pkg.applicationInfo.targetSdkVersion;
19355            }
19356        }
19357        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19358    }
19359
19360    private int getPackageTargetSdkVersionLockedLPr(String packageName) {
19361        final PackageParser.Package p = mPackages.get(packageName);
19362        if (p != null) {
19363            return p.applicationInfo.targetSdkVersion;
19364        }
19365        return Build.VERSION_CODES.CUR_DEVELOPMENT;
19366    }
19367
19368    @Override
19369    public void addPreferredActivity(IntentFilter filter, int match,
19370            ComponentName[] set, ComponentName activity, int userId) {
19371        addPreferredActivityInternal(filter, match, set, activity, true, userId,
19372                "Adding preferred");
19373    }
19374
19375    private void addPreferredActivityInternal(IntentFilter filter, int match,
19376            ComponentName[] set, ComponentName activity, boolean always, int userId,
19377            String opname) {
19378        // writer
19379        int callingUid = Binder.getCallingUid();
19380        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19381                true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
19382        if (filter.countActions() == 0) {
19383            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19384            return;
19385        }
19386        synchronized (mPackages) {
19387            if (mContext.checkCallingOrSelfPermission(
19388                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19389                    != PackageManager.PERMISSION_GRANTED) {
19390                if (getUidTargetSdkVersionLockedLPr(callingUid)
19391                        < Build.VERSION_CODES.FROYO) {
19392                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
19393                            + callingUid);
19394                    return;
19395                }
19396                mContext.enforceCallingOrSelfPermission(
19397                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19398            }
19399
19400            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
19401            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
19402                    + userId + ":");
19403            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19404            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
19405            scheduleWritePackageRestrictionsLocked(userId);
19406            postPreferredActivityChangedBroadcast(userId);
19407        }
19408    }
19409
19410    private void postPreferredActivityChangedBroadcast(int userId) {
19411        mHandler.post(() -> {
19412            final IActivityManager am = ActivityManager.getService();
19413            if (am == null) {
19414                return;
19415            }
19416
19417            final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
19418            intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
19419            try {
19420                am.broadcastIntent(null, intent, null, null,
19421                        0, null, null, null, android.app.AppOpsManager.OP_NONE,
19422                        null, false, false, userId);
19423            } catch (RemoteException e) {
19424            }
19425        });
19426    }
19427
19428    @Override
19429    public void replacePreferredActivity(IntentFilter filter, int match,
19430            ComponentName[] set, ComponentName activity, int userId) {
19431        if (filter.countActions() != 1) {
19432            throw new IllegalArgumentException(
19433                    "replacePreferredActivity expects filter to have only 1 action.");
19434        }
19435        if (filter.countDataAuthorities() != 0
19436                || filter.countDataPaths() != 0
19437                || filter.countDataSchemes() > 1
19438                || filter.countDataTypes() != 0) {
19439            throw new IllegalArgumentException(
19440                    "replacePreferredActivity expects filter to have no data authorities, " +
19441                    "paths, or types; and at most one scheme.");
19442        }
19443
19444        final int callingUid = Binder.getCallingUid();
19445        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19446                true /* requireFullPermission */, false /* checkShell */,
19447                "replace preferred activity");
19448        synchronized (mPackages) {
19449            if (mContext.checkCallingOrSelfPermission(
19450                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19451                    != PackageManager.PERMISSION_GRANTED) {
19452                if (getUidTargetSdkVersionLockedLPr(callingUid)
19453                        < Build.VERSION_CODES.FROYO) {
19454                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
19455                            + Binder.getCallingUid());
19456                    return;
19457                }
19458                mContext.enforceCallingOrSelfPermission(
19459                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19460            }
19461
19462            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19463            if (pir != null) {
19464                // Get all of the existing entries that exactly match this filter.
19465                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
19466                if (existing != null && existing.size() == 1) {
19467                    PreferredActivity cur = existing.get(0);
19468                    if (DEBUG_PREFERRED) {
19469                        Slog.i(TAG, "Checking replace of preferred:");
19470                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19471                        if (!cur.mPref.mAlways) {
19472                            Slog.i(TAG, "  -- CUR; not mAlways!");
19473                        } else {
19474                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
19475                            Slog.i(TAG, "  -- CUR: mSet="
19476                                    + Arrays.toString(cur.mPref.mSetComponents));
19477                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
19478                            Slog.i(TAG, "  -- NEW: mMatch="
19479                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
19480                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
19481                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
19482                        }
19483                    }
19484                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
19485                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
19486                            && cur.mPref.sameSet(set)) {
19487                        // Setting the preferred activity to what it happens to be already
19488                        if (DEBUG_PREFERRED) {
19489                            Slog.i(TAG, "Replacing with same preferred activity "
19490                                    + cur.mPref.mShortComponent + " for user "
19491                                    + userId + ":");
19492                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19493                        }
19494                        return;
19495                    }
19496                }
19497
19498                if (existing != null) {
19499                    if (DEBUG_PREFERRED) {
19500                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
19501                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19502                    }
19503                    for (int i = 0; i < existing.size(); i++) {
19504                        PreferredActivity pa = existing.get(i);
19505                        if (DEBUG_PREFERRED) {
19506                            Slog.i(TAG, "Removing existing preferred activity "
19507                                    + pa.mPref.mComponent + ":");
19508                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
19509                        }
19510                        pir.removeFilter(pa);
19511                    }
19512                }
19513            }
19514            addPreferredActivityInternal(filter, match, set, activity, true, userId,
19515                    "Replacing preferred");
19516        }
19517    }
19518
19519    @Override
19520    public void clearPackagePreferredActivities(String packageName) {
19521        final int callingUid = Binder.getCallingUid();
19522        if (getInstantAppPackageName(callingUid) != null) {
19523            return;
19524        }
19525        // writer
19526        synchronized (mPackages) {
19527            PackageParser.Package pkg = mPackages.get(packageName);
19528            if (pkg == null || pkg.applicationInfo.uid != callingUid) {
19529                if (mContext.checkCallingOrSelfPermission(
19530                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
19531                        != PackageManager.PERMISSION_GRANTED) {
19532                    if (getUidTargetSdkVersionLockedLPr(callingUid)
19533                            < Build.VERSION_CODES.FROYO) {
19534                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
19535                                + callingUid);
19536                        return;
19537                    }
19538                    mContext.enforceCallingOrSelfPermission(
19539                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19540                }
19541            }
19542            final PackageSetting ps = mSettings.getPackageLPr(packageName);
19543            if (ps != null
19544                    && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
19545                return;
19546            }
19547            int user = UserHandle.getCallingUserId();
19548            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
19549                scheduleWritePackageRestrictionsLocked(user);
19550            }
19551        }
19552    }
19553
19554    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19555    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
19556        ArrayList<PreferredActivity> removed = null;
19557        boolean changed = false;
19558        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
19559            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
19560            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
19561            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
19562                continue;
19563            }
19564            Iterator<PreferredActivity> it = pir.filterIterator();
19565            while (it.hasNext()) {
19566                PreferredActivity pa = it.next();
19567                // Mark entry for removal only if it matches the package name
19568                // and the entry is of type "always".
19569                if (packageName == null ||
19570                        (pa.mPref.mComponent.getPackageName().equals(packageName)
19571                                && pa.mPref.mAlways)) {
19572                    if (removed == null) {
19573                        removed = new ArrayList<PreferredActivity>();
19574                    }
19575                    removed.add(pa);
19576                }
19577            }
19578            if (removed != null) {
19579                for (int j=0; j<removed.size(); j++) {
19580                    PreferredActivity pa = removed.get(j);
19581                    pir.removeFilter(pa);
19582                }
19583                changed = true;
19584            }
19585        }
19586        if (changed) {
19587            postPreferredActivityChangedBroadcast(userId);
19588        }
19589        return changed;
19590    }
19591
19592    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19593    private void clearIntentFilterVerificationsLPw(int userId) {
19594        final int packageCount = mPackages.size();
19595        for (int i = 0; i < packageCount; i++) {
19596            PackageParser.Package pkg = mPackages.valueAt(i);
19597            clearIntentFilterVerificationsLPw(pkg.packageName, userId);
19598        }
19599    }
19600
19601    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
19602    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
19603        if (userId == UserHandle.USER_ALL) {
19604            if (mSettings.removeIntentFilterVerificationLPw(packageName,
19605                    sUserManager.getUserIds())) {
19606                for (int oneUserId : sUserManager.getUserIds()) {
19607                    scheduleWritePackageRestrictionsLocked(oneUserId);
19608                }
19609            }
19610        } else {
19611            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
19612                scheduleWritePackageRestrictionsLocked(userId);
19613            }
19614        }
19615    }
19616
19617    /** Clears state for all users, and touches intent filter verification policy */
19618    void clearDefaultBrowserIfNeeded(String packageName) {
19619        for (int oneUserId : sUserManager.getUserIds()) {
19620            clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
19621        }
19622    }
19623
19624    private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
19625        final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
19626        if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
19627            if (packageName.equals(defaultBrowserPackageName)) {
19628                setDefaultBrowserPackageName(null, userId);
19629            }
19630        }
19631    }
19632
19633    @Override
19634    public void resetApplicationPreferences(int userId) {
19635        mContext.enforceCallingOrSelfPermission(
19636                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
19637        final long identity = Binder.clearCallingIdentity();
19638        // writer
19639        try {
19640            synchronized (mPackages) {
19641                clearPackagePreferredActivitiesLPw(null, userId);
19642                mSettings.applyDefaultPreferredAppsLPw(this, userId);
19643                // TODO: We have to reset the default SMS and Phone. This requires
19644                // significant refactoring to keep all default apps in the package
19645                // manager (cleaner but more work) or have the services provide
19646                // callbacks to the package manager to request a default app reset.
19647                applyFactoryDefaultBrowserLPw(userId);
19648                clearIntentFilterVerificationsLPw(userId);
19649                primeDomainVerificationsLPw(userId);
19650                resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
19651                scheduleWritePackageRestrictionsLocked(userId);
19652            }
19653            resetNetworkPolicies(userId);
19654        } finally {
19655            Binder.restoreCallingIdentity(identity);
19656        }
19657    }
19658
19659    @Override
19660    public int getPreferredActivities(List<IntentFilter> outFilters,
19661            List<ComponentName> outActivities, String packageName) {
19662        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
19663            return 0;
19664        }
19665        int num = 0;
19666        final int userId = UserHandle.getCallingUserId();
19667        // reader
19668        synchronized (mPackages) {
19669            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
19670            if (pir != null) {
19671                final Iterator<PreferredActivity> it = pir.filterIterator();
19672                while (it.hasNext()) {
19673                    final PreferredActivity pa = it.next();
19674                    if (packageName == null
19675                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
19676                                    && pa.mPref.mAlways)) {
19677                        if (outFilters != null) {
19678                            outFilters.add(new IntentFilter(pa));
19679                        }
19680                        if (outActivities != null) {
19681                            outActivities.add(pa.mPref.mComponent);
19682                        }
19683                    }
19684                }
19685            }
19686        }
19687
19688        return num;
19689    }
19690
19691    @Override
19692    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
19693            int userId) {
19694        int callingUid = Binder.getCallingUid();
19695        if (callingUid != Process.SYSTEM_UID) {
19696            throw new SecurityException(
19697                    "addPersistentPreferredActivity can only be run by the system");
19698        }
19699        if (filter.countActions() == 0) {
19700            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
19701            return;
19702        }
19703        synchronized (mPackages) {
19704            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
19705                    ":");
19706            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
19707            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
19708                    new PersistentPreferredActivity(filter, activity));
19709            scheduleWritePackageRestrictionsLocked(userId);
19710            postPreferredActivityChangedBroadcast(userId);
19711        }
19712    }
19713
19714    @Override
19715    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
19716        int callingUid = Binder.getCallingUid();
19717        if (callingUid != Process.SYSTEM_UID) {
19718            throw new SecurityException(
19719                    "clearPackagePersistentPreferredActivities can only be run by the system");
19720        }
19721        ArrayList<PersistentPreferredActivity> removed = null;
19722        boolean changed = false;
19723        synchronized (mPackages) {
19724            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
19725                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
19726                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
19727                        .valueAt(i);
19728                if (userId != thisUserId) {
19729                    continue;
19730                }
19731                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
19732                while (it.hasNext()) {
19733                    PersistentPreferredActivity ppa = it.next();
19734                    // Mark entry for removal only if it matches the package name.
19735                    if (ppa.mComponent.getPackageName().equals(packageName)) {
19736                        if (removed == null) {
19737                            removed = new ArrayList<PersistentPreferredActivity>();
19738                        }
19739                        removed.add(ppa);
19740                    }
19741                }
19742                if (removed != null) {
19743                    for (int j=0; j<removed.size(); j++) {
19744                        PersistentPreferredActivity ppa = removed.get(j);
19745                        ppir.removeFilter(ppa);
19746                    }
19747                    changed = true;
19748                }
19749            }
19750
19751            if (changed) {
19752                scheduleWritePackageRestrictionsLocked(userId);
19753                postPreferredActivityChangedBroadcast(userId);
19754            }
19755        }
19756    }
19757
19758    /**
19759     * Common machinery for picking apart a restored XML blob and passing
19760     * it to a caller-supplied functor to be applied to the running system.
19761     */
19762    private void restoreFromXml(XmlPullParser parser, int userId,
19763            String expectedStartTag, BlobXmlRestorer functor)
19764            throws IOException, XmlPullParserException {
19765        int type;
19766        while ((type = parser.next()) != XmlPullParser.START_TAG
19767                && type != XmlPullParser.END_DOCUMENT) {
19768        }
19769        if (type != XmlPullParser.START_TAG) {
19770            // oops didn't find a start tag?!
19771            if (DEBUG_BACKUP) {
19772                Slog.e(TAG, "Didn't find start tag during restore");
19773            }
19774            return;
19775        }
19776Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName());
19777        // this is supposed to be TAG_PREFERRED_BACKUP
19778        if (!expectedStartTag.equals(parser.getName())) {
19779            if (DEBUG_BACKUP) {
19780                Slog.e(TAG, "Found unexpected tag " + parser.getName());
19781            }
19782            return;
19783        }
19784
19785        // skip interfering stuff, then we're aligned with the backing implementation
19786        while ((type = parser.next()) == XmlPullParser.TEXT) { }
19787Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName());
19788        functor.apply(parser, userId);
19789    }
19790
19791    private interface BlobXmlRestorer {
19792        public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
19793    }
19794
19795    /**
19796     * Non-Binder method, support for the backup/restore mechanism: write the
19797     * full set of preferred activities in its canonical XML format.  Returns the
19798     * XML output as a byte array, or null if there is none.
19799     */
19800    @Override
19801    public byte[] getPreferredActivityBackup(int userId) {
19802        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19803            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
19804        }
19805
19806        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19807        try {
19808            final XmlSerializer serializer = new FastXmlSerializer();
19809            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19810            serializer.startDocument(null, true);
19811            serializer.startTag(null, TAG_PREFERRED_BACKUP);
19812
19813            synchronized (mPackages) {
19814                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
19815            }
19816
19817            serializer.endTag(null, TAG_PREFERRED_BACKUP);
19818            serializer.endDocument();
19819            serializer.flush();
19820        } catch (Exception e) {
19821            if (DEBUG_BACKUP) {
19822                Slog.e(TAG, "Unable to write preferred activities for backup", e);
19823            }
19824            return null;
19825        }
19826
19827        return dataStream.toByteArray();
19828    }
19829
19830    @Override
19831    public void restorePreferredActivities(byte[] backup, int userId) {
19832        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19833            throw new SecurityException("Only the system may call restorePreferredActivities()");
19834        }
19835
19836        try {
19837            final XmlPullParser parser = Xml.newPullParser();
19838            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19839            restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
19840                    new BlobXmlRestorer() {
19841                        @Override
19842                        public void apply(XmlPullParser parser, int userId)
19843                                throws XmlPullParserException, IOException {
19844                            synchronized (mPackages) {
19845                                mSettings.readPreferredActivitiesLPw(parser, userId);
19846                            }
19847                        }
19848                    } );
19849        } catch (Exception e) {
19850            if (DEBUG_BACKUP) {
19851                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19852            }
19853        }
19854    }
19855
19856    /**
19857     * Non-Binder method, support for the backup/restore mechanism: write the
19858     * default browser (etc) settings in its canonical XML format.  Returns the default
19859     * browser XML representation as a byte array, or null if there is none.
19860     */
19861    @Override
19862    public byte[] getDefaultAppsBackup(int userId) {
19863        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19864            throw new SecurityException("Only the system may call getDefaultAppsBackup()");
19865        }
19866
19867        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19868        try {
19869            final XmlSerializer serializer = new FastXmlSerializer();
19870            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19871            serializer.startDocument(null, true);
19872            serializer.startTag(null, TAG_DEFAULT_APPS);
19873
19874            synchronized (mPackages) {
19875                mSettings.writeDefaultAppsLPr(serializer, userId);
19876            }
19877
19878            serializer.endTag(null, TAG_DEFAULT_APPS);
19879            serializer.endDocument();
19880            serializer.flush();
19881        } catch (Exception e) {
19882            if (DEBUG_BACKUP) {
19883                Slog.e(TAG, "Unable to write default apps for backup", e);
19884            }
19885            return null;
19886        }
19887
19888        return dataStream.toByteArray();
19889    }
19890
19891    @Override
19892    public void restoreDefaultApps(byte[] backup, int userId) {
19893        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19894            throw new SecurityException("Only the system may call restoreDefaultApps()");
19895        }
19896
19897        try {
19898            final XmlPullParser parser = Xml.newPullParser();
19899            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19900            restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
19901                    new BlobXmlRestorer() {
19902                        @Override
19903                        public void apply(XmlPullParser parser, int userId)
19904                                throws XmlPullParserException, IOException {
19905                            synchronized (mPackages) {
19906                                mSettings.readDefaultAppsLPw(parser, userId);
19907                            }
19908                        }
19909                    } );
19910        } catch (Exception e) {
19911            if (DEBUG_BACKUP) {
19912                Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
19913            }
19914        }
19915    }
19916
19917    @Override
19918    public byte[] getIntentFilterVerificationBackup(int userId) {
19919        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19920            throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
19921        }
19922
19923        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19924        try {
19925            final XmlSerializer serializer = new FastXmlSerializer();
19926            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19927            serializer.startDocument(null, true);
19928            serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
19929
19930            synchronized (mPackages) {
19931                mSettings.writeAllDomainVerificationsLPr(serializer, userId);
19932            }
19933
19934            serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
19935            serializer.endDocument();
19936            serializer.flush();
19937        } catch (Exception e) {
19938            if (DEBUG_BACKUP) {
19939                Slog.e(TAG, "Unable to write default apps for backup", e);
19940            }
19941            return null;
19942        }
19943
19944        return dataStream.toByteArray();
19945    }
19946
19947    @Override
19948    public void restoreIntentFilterVerification(byte[] backup, int userId) {
19949        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19950            throw new SecurityException("Only the system may call restorePreferredActivities()");
19951        }
19952
19953        try {
19954            final XmlPullParser parser = Xml.newPullParser();
19955            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
19956            restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
19957                    new BlobXmlRestorer() {
19958                        @Override
19959                        public void apply(XmlPullParser parser, int userId)
19960                                throws XmlPullParserException, IOException {
19961                            synchronized (mPackages) {
19962                                mSettings.readAllDomainVerificationsLPr(parser, userId);
19963                                mSettings.writeLPr();
19964                            }
19965                        }
19966                    } );
19967        } catch (Exception e) {
19968            if (DEBUG_BACKUP) {
19969                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
19970            }
19971        }
19972    }
19973
19974    @Override
19975    public byte[] getPermissionGrantBackup(int userId) {
19976        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
19977            throw new SecurityException("Only the system may call getPermissionGrantBackup()");
19978        }
19979
19980        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
19981        try {
19982            final XmlSerializer serializer = new FastXmlSerializer();
19983            serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
19984            serializer.startDocument(null, true);
19985            serializer.startTag(null, TAG_PERMISSION_BACKUP);
19986
19987            synchronized (mPackages) {
19988                serializeRuntimePermissionGrantsLPr(serializer, userId);
19989            }
19990
19991            serializer.endTag(null, TAG_PERMISSION_BACKUP);
19992            serializer.endDocument();
19993            serializer.flush();
19994        } catch (Exception e) {
19995            if (DEBUG_BACKUP) {
19996                Slog.e(TAG, "Unable to write default apps for backup", e);
19997            }
19998            return null;
19999        }
20000
20001        return dataStream.toByteArray();
20002    }
20003
20004    @Override
20005    public void restorePermissionGrants(byte[] backup, int userId) {
20006        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20007            throw new SecurityException("Only the system may call restorePermissionGrants()");
20008        }
20009
20010        try {
20011            final XmlPullParser parser = Xml.newPullParser();
20012            parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20013            restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP,
20014                    new BlobXmlRestorer() {
20015                        @Override
20016                        public void apply(XmlPullParser parser, int userId)
20017                                throws XmlPullParserException, IOException {
20018                            synchronized (mPackages) {
20019                                processRestoredPermissionGrantsLPr(parser, userId);
20020                            }
20021                        }
20022                    } );
20023        } catch (Exception e) {
20024            if (DEBUG_BACKUP) {
20025                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20026            }
20027        }
20028    }
20029
20030    private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId)
20031            throws IOException {
20032        serializer.startTag(null, TAG_ALL_GRANTS);
20033
20034        final int N = mSettings.mPackages.size();
20035        for (int i = 0; i < N; i++) {
20036            final PackageSetting ps = mSettings.mPackages.valueAt(i);
20037            boolean pkgGrantsKnown = false;
20038
20039            PermissionsState packagePerms = ps.getPermissionsState();
20040
20041            for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) {
20042                final int grantFlags = state.getFlags();
20043                // only look at grants that are not system/policy fixed
20044                if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) {
20045                    final boolean isGranted = state.isGranted();
20046                    // And only back up the user-twiddled state bits
20047                    if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) {
20048                        final String packageName = mSettings.mPackages.keyAt(i);
20049                        if (!pkgGrantsKnown) {
20050                            serializer.startTag(null, TAG_GRANT);
20051                            serializer.attribute(null, ATTR_PACKAGE_NAME, packageName);
20052                            pkgGrantsKnown = true;
20053                        }
20054
20055                        final boolean userSet =
20056                                (grantFlags & FLAG_PERMISSION_USER_SET) != 0;
20057                        final boolean userFixed =
20058                                (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0;
20059                        final boolean revoke =
20060                                (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0;
20061
20062                        serializer.startTag(null, TAG_PERMISSION);
20063                        serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName());
20064                        if (isGranted) {
20065                            serializer.attribute(null, ATTR_IS_GRANTED, "true");
20066                        }
20067                        if (userSet) {
20068                            serializer.attribute(null, ATTR_USER_SET, "true");
20069                        }
20070                        if (userFixed) {
20071                            serializer.attribute(null, ATTR_USER_FIXED, "true");
20072                        }
20073                        if (revoke) {
20074                            serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true");
20075                        }
20076                        serializer.endTag(null, TAG_PERMISSION);
20077                    }
20078                }
20079            }
20080
20081            if (pkgGrantsKnown) {
20082                serializer.endTag(null, TAG_GRANT);
20083            }
20084        }
20085
20086        serializer.endTag(null, TAG_ALL_GRANTS);
20087    }
20088
20089    private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId)
20090            throws XmlPullParserException, IOException {
20091        String pkgName = null;
20092        int outerDepth = parser.getDepth();
20093        int type;
20094        while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
20095                && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
20096            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
20097                continue;
20098            }
20099
20100            final String tagName = parser.getName();
20101            if (tagName.equals(TAG_GRANT)) {
20102                pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME);
20103                if (DEBUG_BACKUP) {
20104                    Slog.v(TAG, "+++ Restoring grants for package " + pkgName);
20105                }
20106            } else if (tagName.equals(TAG_PERMISSION)) {
20107
20108                final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED));
20109                final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME);
20110
20111                int newFlagSet = 0;
20112                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) {
20113                    newFlagSet |= FLAG_PERMISSION_USER_SET;
20114                }
20115                if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) {
20116                    newFlagSet |= FLAG_PERMISSION_USER_FIXED;
20117                }
20118                if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) {
20119                    newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE;
20120                }
20121                if (DEBUG_BACKUP) {
20122                    Slog.v(TAG, "  + Restoring grant:"
20123                            + " pkg=" + pkgName
20124                            + " perm=" + permName
20125                            + " granted=" + isGranted
20126                            + " bits=0x" + Integer.toHexString(newFlagSet));
20127                }
20128                final PackageSetting ps = mSettings.mPackages.get(pkgName);
20129                if (ps != null) {
20130                    // Already installed so we apply the grant immediately
20131                    if (DEBUG_BACKUP) {
20132                        Slog.v(TAG, "        + already installed; applying");
20133                    }
20134                    PermissionsState perms = ps.getPermissionsState();
20135                    BasePermission bp =
20136                            (BasePermission) mPermissionManager.getPermissionTEMP(permName);
20137                    if (bp != null) {
20138                        if (isGranted) {
20139                            perms.grantRuntimePermission(bp, userId);
20140                        }
20141                        if (newFlagSet != 0) {
20142                            perms.updatePermissionFlags(
20143                                    bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet);
20144                        }
20145                    }
20146                } else {
20147                    // Need to wait for post-restore install to apply the grant
20148                    if (DEBUG_BACKUP) {
20149                        Slog.v(TAG, "        - not yet installed; saving for later");
20150                    }
20151                    mSettings.processRestoredPermissionGrantLPr(pkgName, permName,
20152                            isGranted, newFlagSet, userId);
20153                }
20154            } else {
20155                PackageManagerService.reportSettingsProblem(Log.WARN,
20156                        "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName);
20157                XmlUtils.skipCurrentTag(parser);
20158            }
20159        }
20160
20161        scheduleWriteSettingsLocked();
20162        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
20163    }
20164
20165    @Override
20166    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20167            int sourceUserId, int targetUserId, int flags) {
20168        mContext.enforceCallingOrSelfPermission(
20169                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20170        int callingUid = Binder.getCallingUid();
20171        enforceOwnerRights(ownerPackage, callingUid);
20172        PackageManagerServiceUtils.enforceShellRestriction(
20173                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20174        if (intentFilter.countActions() == 0) {
20175            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20176            return;
20177        }
20178        synchronized (mPackages) {
20179            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20180                    ownerPackage, targetUserId, flags);
20181            CrossProfileIntentResolver resolver =
20182                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20183            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20184            // We have all those whose filter is equal. Now checking if the rest is equal as well.
20185            if (existing != null) {
20186                int size = existing.size();
20187                for (int i = 0; i < size; i++) {
20188                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20189                        return;
20190                    }
20191                }
20192            }
20193            resolver.addFilter(newFilter);
20194            scheduleWritePackageRestrictionsLocked(sourceUserId);
20195        }
20196    }
20197
20198    @Override
20199    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20200        mContext.enforceCallingOrSelfPermission(
20201                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20202        final int callingUid = Binder.getCallingUid();
20203        enforceOwnerRights(ownerPackage, callingUid);
20204        PackageManagerServiceUtils.enforceShellRestriction(
20205                UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20206        synchronized (mPackages) {
20207            CrossProfileIntentResolver resolver =
20208                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20209            ArraySet<CrossProfileIntentFilter> set =
20210                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
20211            for (CrossProfileIntentFilter filter : set) {
20212                if (filter.getOwnerPackage().equals(ownerPackage)) {
20213                    resolver.removeFilter(filter);
20214                }
20215            }
20216            scheduleWritePackageRestrictionsLocked(sourceUserId);
20217        }
20218    }
20219
20220    // Enforcing that callingUid is owning pkg on userId
20221    private void enforceOwnerRights(String pkg, int callingUid) {
20222        // The system owns everything.
20223        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20224            return;
20225        }
20226        final int callingUserId = UserHandle.getUserId(callingUid);
20227        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20228        if (pi == null) {
20229            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20230                    + callingUserId);
20231        }
20232        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20233            throw new SecurityException("Calling uid " + callingUid
20234                    + " does not own package " + pkg);
20235        }
20236    }
20237
20238    @Override
20239    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20240        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20241            return null;
20242        }
20243        return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20244    }
20245
20246    public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20247        UserManagerService ums = UserManagerService.getInstance();
20248        if (ums != null) {
20249            final UserInfo parent = ums.getProfileParent(userId);
20250            final int launcherUid = (parent != null) ? parent.id : userId;
20251            final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20252            if (launcherComponent != null) {
20253                Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20254                        .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20255                        .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20256                        .setPackage(launcherComponent.getPackageName());
20257                mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20258            }
20259        }
20260    }
20261
20262    /**
20263     * Report the 'Home' activity which is currently set as "always use this one". If non is set
20264     * then reports the most likely home activity or null if there are more than one.
20265     */
20266    private ComponentName getDefaultHomeActivity(int userId) {
20267        List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20268        ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20269        if (cn != null) {
20270            return cn;
20271        }
20272
20273        // Find the launcher with the highest priority and return that component if there are no
20274        // other home activity with the same priority.
20275        int lastPriority = Integer.MIN_VALUE;
20276        ComponentName lastComponent = null;
20277        final int size = allHomeCandidates.size();
20278        for (int i = 0; i < size; i++) {
20279            final ResolveInfo ri = allHomeCandidates.get(i);
20280            if (ri.priority > lastPriority) {
20281                lastComponent = ri.activityInfo.getComponentName();
20282                lastPriority = ri.priority;
20283            } else if (ri.priority == lastPriority) {
20284                // Two components found with same priority.
20285                lastComponent = null;
20286            }
20287        }
20288        return lastComponent;
20289    }
20290
20291    private Intent getHomeIntent() {
20292        Intent intent = new Intent(Intent.ACTION_MAIN);
20293        intent.addCategory(Intent.CATEGORY_HOME);
20294        intent.addCategory(Intent.CATEGORY_DEFAULT);
20295        return intent;
20296    }
20297
20298    private IntentFilter getHomeFilter() {
20299        IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20300        filter.addCategory(Intent.CATEGORY_HOME);
20301        filter.addCategory(Intent.CATEGORY_DEFAULT);
20302        return filter;
20303    }
20304
20305    ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20306            int userId) {
20307        Intent intent  = getHomeIntent();
20308        List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null,
20309                PackageManager.GET_META_DATA, userId);
20310        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
20311                true, false, false, userId);
20312
20313        allHomeCandidates.clear();
20314        if (list != null) {
20315            for (ResolveInfo ri : list) {
20316                allHomeCandidates.add(ri);
20317            }
20318        }
20319        return (preferred == null || preferred.activityInfo == null)
20320                ? null
20321                : new ComponentName(preferred.activityInfo.packageName,
20322                        preferred.activityInfo.name);
20323    }
20324
20325    @Override
20326    public void setHomeActivity(ComponentName comp, int userId) {
20327        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20328            return;
20329        }
20330        ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
20331        getHomeActivitiesAsUser(homeActivities, userId);
20332
20333        boolean found = false;
20334
20335        final int size = homeActivities.size();
20336        final ComponentName[] set = new ComponentName[size];
20337        for (int i = 0; i < size; i++) {
20338            final ResolveInfo candidate = homeActivities.get(i);
20339            final ActivityInfo info = candidate.activityInfo;
20340            final ComponentName activityName = new ComponentName(info.packageName, info.name);
20341            set[i] = activityName;
20342            if (!found && activityName.equals(comp)) {
20343                found = true;
20344            }
20345        }
20346        if (!found) {
20347            throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
20348                    + userId);
20349        }
20350        replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
20351                set, comp, userId);
20352    }
20353
20354    private @Nullable String getSetupWizardPackageName() {
20355        final Intent intent = new Intent(Intent.ACTION_MAIN);
20356        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
20357
20358        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20359                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20360                        | MATCH_DISABLED_COMPONENTS,
20361                UserHandle.myUserId());
20362        if (matches.size() == 1) {
20363            return matches.get(0).getComponentInfo().packageName;
20364        } else {
20365            Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
20366                    + ": matches=" + matches);
20367            return null;
20368        }
20369    }
20370
20371    private @Nullable String getStorageManagerPackageName() {
20372        final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
20373
20374        final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
20375                MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
20376                        | MATCH_DISABLED_COMPONENTS,
20377                UserHandle.myUserId());
20378        if (matches.size() == 1) {
20379            return matches.get(0).getComponentInfo().packageName;
20380        } else {
20381            Slog.e(TAG, "There should probably be exactly one storage manager; found "
20382                    + matches.size() + ": matches=" + matches);
20383            return null;
20384        }
20385    }
20386
20387    @Override
20388    public String getSystemTextClassifierPackageName() {
20389        return mContext.getString(R.string.config_defaultTextClassifierPackage);
20390    }
20391
20392    @Override
20393    public void setApplicationEnabledSetting(String appPackageName,
20394            int newState, int flags, int userId, String callingPackage) {
20395        if (!sUserManager.exists(userId)) return;
20396        if (callingPackage == null) {
20397            callingPackage = Integer.toString(Binder.getCallingUid());
20398        }
20399        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
20400    }
20401
20402    @Override
20403    public void setUpdateAvailable(String packageName, boolean updateAvailable) {
20404        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
20405        synchronized (mPackages) {
20406            final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
20407            if (pkgSetting != null) {
20408                pkgSetting.setUpdateAvailable(updateAvailable);
20409            }
20410        }
20411    }
20412
20413    @Override
20414    public void setComponentEnabledSetting(ComponentName componentName,
20415            int newState, int flags, int userId) {
20416        if (!sUserManager.exists(userId)) return;
20417        setEnabledSetting(componentName.getPackageName(),
20418                componentName.getClassName(), newState, flags, userId, null);
20419    }
20420
20421    private void setEnabledSetting(final String packageName, String className, int newState,
20422            final int flags, int userId, String callingPackage) {
20423        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
20424              || newState == COMPONENT_ENABLED_STATE_ENABLED
20425              || newState == COMPONENT_ENABLED_STATE_DISABLED
20426              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20427              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
20428            throw new IllegalArgumentException("Invalid new component state: "
20429                    + newState);
20430        }
20431        PackageSetting pkgSetting;
20432        final int callingUid = Binder.getCallingUid();
20433        final int permission;
20434        if (callingUid == Process.SYSTEM_UID) {
20435            permission = PackageManager.PERMISSION_GRANTED;
20436        } else {
20437            permission = mContext.checkCallingOrSelfPermission(
20438                    android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20439        }
20440        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20441                false /* requireFullPermission */, true /* checkShell */, "set enabled");
20442        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20443        boolean sendNow = false;
20444        boolean isApp = (className == null);
20445        final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
20446        String componentName = isApp ? packageName : className;
20447        int packageUid = -1;
20448        ArrayList<String> components;
20449
20450        // reader
20451        synchronized (mPackages) {
20452            pkgSetting = mSettings.mPackages.get(packageName);
20453            if (pkgSetting == null) {
20454                if (!isCallerInstantApp) {
20455                    if (className == null) {
20456                        throw new IllegalArgumentException("Unknown package: " + packageName);
20457                    }
20458                    throw new IllegalArgumentException(
20459                            "Unknown component: " + packageName + "/" + className);
20460                } else {
20461                    // throw SecurityException to prevent leaking package information
20462                    throw new SecurityException(
20463                            "Attempt to change component state; "
20464                            + "pid=" + Binder.getCallingPid()
20465                            + ", uid=" + callingUid
20466                            + (className == null
20467                                    ? ", package=" + packageName
20468                                    : ", component=" + packageName + "/" + className));
20469                }
20470            }
20471        }
20472
20473        // Limit who can change which apps
20474        if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
20475            // Don't allow apps that don't have permission to modify other apps
20476            if (!allowedByPermission
20477                    || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
20478                throw new SecurityException(
20479                        "Attempt to change component state; "
20480                        + "pid=" + Binder.getCallingPid()
20481                        + ", uid=" + callingUid
20482                        + (className == null
20483                                ? ", package=" + packageName
20484                                : ", component=" + packageName + "/" + className));
20485            }
20486            // Don't allow changing protected packages.
20487            if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
20488                throw new SecurityException("Cannot disable a protected package: " + packageName);
20489            }
20490        }
20491
20492        synchronized (mPackages) {
20493            if (callingUid == Process.SHELL_UID
20494                    && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
20495                // Shell can only change whole packages between ENABLED and DISABLED_USER states
20496                // unless it is a test package.
20497                int oldState = pkgSetting.getEnabled(userId);
20498                if (className == null
20499                        &&
20500                        (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
20501                                || oldState == COMPONENT_ENABLED_STATE_DEFAULT
20502                                || oldState == COMPONENT_ENABLED_STATE_ENABLED)
20503                        &&
20504                        (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
20505                                || newState == COMPONENT_ENABLED_STATE_DEFAULT
20506                                || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
20507                    // ok
20508                } else {
20509                    throw new SecurityException(
20510                            "Shell cannot change component state for " + packageName + "/"
20511                                    + className + " to " + newState);
20512                }
20513            }
20514        }
20515        if (className == null) {
20516            // We're dealing with an application/package level state change
20517            synchronized (mPackages) {
20518                if (pkgSetting.getEnabled(userId) == newState) {
20519                    // Nothing to do
20520                    return;
20521                }
20522            }
20523            // If we're enabling a system stub, there's a little more work to do.
20524            // Prior to enabling the package, we need to decompress the APK(s) to the
20525            // data partition and then replace the version on the system partition.
20526            final PackageParser.Package deletedPkg = pkgSetting.pkg;
20527            final boolean isSystemStub = deletedPkg.isStub
20528                    && deletedPkg.isSystem();
20529            if (isSystemStub
20530                    && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20531                            || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
20532                final File codePath = decompressPackage(deletedPkg);
20533                if (codePath == null) {
20534                    Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name);
20535                    return;
20536                }
20537                // TODO remove direct parsing of the package object during internal cleanup
20538                // of scan package
20539                // We need to call parse directly here for no other reason than we need
20540                // the new package in order to disable the old one [we use the information
20541                // for some internal optimization to optionally create a new package setting
20542                // object on replace]. However, we can't get the package from the scan
20543                // because the scan modifies live structures and we need to remove the
20544                // old [system] package from the system before a scan can be attempted.
20545                // Once scan is indempotent we can remove this parse and use the package
20546                // object we scanned, prior to adding it to package settings.
20547                final PackageParser pp = new PackageParser();
20548                pp.setSeparateProcesses(mSeparateProcesses);
20549                pp.setDisplayMetrics(mMetrics);
20550                pp.setCallback(mPackageParserCallback);
20551                final PackageParser.Package tmpPkg;
20552                try {
20553                    final @ParseFlags int parseFlags = mDefParseFlags
20554                            | PackageParser.PARSE_MUST_BE_APK
20555                            | PackageParser.PARSE_IS_SYSTEM_DIR;
20556                    tmpPkg = pp.parsePackage(codePath, parseFlags);
20557                } catch (PackageParserException e) {
20558                    Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e);
20559                    return;
20560                }
20561                synchronized (mInstallLock) {
20562                    // Disable the stub and remove any package entries
20563                    removePackageLI(deletedPkg, true);
20564                    synchronized (mPackages) {
20565                        disableSystemPackageLPw(deletedPkg, tmpPkg);
20566                    }
20567                    final PackageParser.Package pkg;
20568                    try (PackageFreezer freezer =
20569                            freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20570                        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
20571                                | PackageParser.PARSE_ENFORCE_CODE;
20572                        pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/,
20573                                0 /*currentTime*/, null /*user*/);
20574                        prepareAppDataAfterInstallLIF(pkg);
20575                        synchronized (mPackages) {
20576                            try {
20577                                updateSharedLibrariesLPr(pkg, null);
20578                            } catch (PackageManagerException e) {
20579                                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
20580                            }
20581                            mPermissionManager.updatePermissions(
20582                                    pkg.packageName, pkg, true, mPackages.values(),
20583                                    mPermissionCallback);
20584                            mSettings.writeLPr();
20585                        }
20586                    } catch (PackageManagerException e) {
20587                        // Whoops! Something went wrong; try to roll back to the stub
20588                        Slog.w(TAG, "Failed to install compressed system package:"
20589                                + pkgSetting.name, e);
20590                        // Remove the failed install
20591                        removeCodePathLI(codePath);
20592
20593                        // Install the system package
20594                        try (PackageFreezer freezer =
20595                                freezePackage(deletedPkg.packageName, "setEnabledSetting")) {
20596                            synchronized (mPackages) {
20597                                // NOTE: The system package always needs to be enabled; even
20598                                // if it's for a compressed stub. If we don't, installing the
20599                                // system package fails during scan [scanning checks the disabled
20600                                // packages]. We will reverse this later, after we've "installed"
20601                                // the stub.
20602                                // This leaves us in a fragile state; the stub should never be
20603                                // enabled, so, cross your fingers and hope nothing goes wrong
20604                                // until we can disable the package later.
20605                                enableSystemPackageLPw(deletedPkg);
20606                            }
20607                            installPackageFromSystemLIF(deletedPkg.codePath,
20608                                    false /*isPrivileged*/, null /*allUserHandles*/,
20609                                    null /*origUserHandles*/, null /*origPermissionsState*/,
20610                                    true /*writeSettings*/);
20611                        } catch (PackageManagerException pme) {
20612                            Slog.w(TAG, "Failed to restore system package:"
20613                                    + deletedPkg.packageName, pme);
20614                        } finally {
20615                            synchronized (mPackages) {
20616                                mSettings.disableSystemPackageLPw(
20617                                        deletedPkg.packageName, true /*replaced*/);
20618                                mSettings.writeLPr();
20619                            }
20620                        }
20621                        return;
20622                    }
20623                    clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE
20624                            | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20625                    mDexManager.notifyPackageUpdated(pkg.packageName,
20626                            pkg.baseCodePath, pkg.splitCodePaths);
20627                }
20628            }
20629            if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
20630                || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
20631                // Don't care about who enables an app.
20632                callingPackage = null;
20633            }
20634            synchronized (mPackages) {
20635                pkgSetting.setEnabled(newState, userId, callingPackage);
20636            }
20637        } else {
20638            synchronized (mPackages) {
20639                // We're dealing with a component level state change
20640                // First, verify that this is a valid class name.
20641                PackageParser.Package pkg = pkgSetting.pkg;
20642                if (pkg == null || !pkg.hasComponentClassName(className)) {
20643                    if (pkg != null &&
20644                            pkg.applicationInfo.targetSdkVersion >=
20645                                    Build.VERSION_CODES.JELLY_BEAN) {
20646                        throw new IllegalArgumentException("Component class " + className
20647                                + " does not exist in " + packageName);
20648                    } else {
20649                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
20650                                + className + " does not exist in " + packageName);
20651                    }
20652                }
20653                switch (newState) {
20654                    case COMPONENT_ENABLED_STATE_ENABLED:
20655                        if (!pkgSetting.enableComponentLPw(className, userId)) {
20656                            return;
20657                        }
20658                        break;
20659                    case COMPONENT_ENABLED_STATE_DISABLED:
20660                        if (!pkgSetting.disableComponentLPw(className, userId)) {
20661                            return;
20662                        }
20663                        break;
20664                    case COMPONENT_ENABLED_STATE_DEFAULT:
20665                        if (!pkgSetting.restoreComponentLPw(className, userId)) {
20666                            return;
20667                        }
20668                        break;
20669                    default:
20670                        Slog.e(TAG, "Invalid new component state: " + newState);
20671                        return;
20672                }
20673            }
20674        }
20675        synchronized (mPackages) {
20676            scheduleWritePackageRestrictionsLocked(userId);
20677            updateSequenceNumberLP(pkgSetting, new int[] { userId });
20678            final long callingId = Binder.clearCallingIdentity();
20679            try {
20680                updateInstantAppInstallerLocked(packageName);
20681            } finally {
20682                Binder.restoreCallingIdentity(callingId);
20683            }
20684            components = mPendingBroadcasts.get(userId, packageName);
20685            final boolean newPackage = components == null;
20686            if (newPackage) {
20687                components = new ArrayList<String>();
20688            }
20689            if (!components.contains(componentName)) {
20690                components.add(componentName);
20691            }
20692            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
20693                sendNow = true;
20694                // Purge entry from pending broadcast list if another one exists already
20695                // since we are sending one right away.
20696                mPendingBroadcasts.remove(userId, packageName);
20697            } else {
20698                if (newPackage) {
20699                    mPendingBroadcasts.put(userId, packageName, components);
20700                }
20701                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
20702                    // Schedule a message
20703                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
20704                }
20705            }
20706        }
20707
20708        long callingId = Binder.clearCallingIdentity();
20709        try {
20710            if (sendNow) {
20711                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
20712                sendPackageChangedBroadcast(packageName,
20713                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
20714            }
20715        } finally {
20716            Binder.restoreCallingIdentity(callingId);
20717        }
20718    }
20719
20720    @Override
20721    public void flushPackageRestrictionsAsUser(int userId) {
20722        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20723            return;
20724        }
20725        if (!sUserManager.exists(userId)) {
20726            return;
20727        }
20728        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
20729                false /* checkShell */, "flushPackageRestrictions");
20730        synchronized (mPackages) {
20731            mSettings.writePackageRestrictionsLPr(userId);
20732            mDirtyUsers.remove(userId);
20733            if (mDirtyUsers.isEmpty()) {
20734                mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
20735            }
20736        }
20737    }
20738
20739    private void sendPackageChangedBroadcast(String packageName,
20740            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
20741        if (DEBUG_INSTALL)
20742            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
20743                    + componentNames);
20744        Bundle extras = new Bundle(4);
20745        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
20746        String nameList[] = new String[componentNames.size()];
20747        componentNames.toArray(nameList);
20748        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
20749        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
20750        extras.putInt(Intent.EXTRA_UID, packageUid);
20751        // If this is not reporting a change of the overall package, then only send it
20752        // to registered receivers.  We don't want to launch a swath of apps for every
20753        // little component state change.
20754        final int flags = !componentNames.contains(packageName)
20755                ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
20756        final int userId = UserHandle.getUserId(packageUid);
20757        final boolean isInstantApp = isInstantApp(packageName, userId);
20758        final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
20759        final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
20760        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
20761                userIds, instantUserIds);
20762    }
20763
20764    @Override
20765    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
20766        if (!sUserManager.exists(userId)) return;
20767        final int callingUid = Binder.getCallingUid();
20768        if (getInstantAppPackageName(callingUid) != null) {
20769            return;
20770        }
20771        final int permission = mContext.checkCallingOrSelfPermission(
20772                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
20773        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
20774        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20775                true /* requireFullPermission */, true /* checkShell */, "stop package");
20776        // writer
20777        synchronized (mPackages) {
20778            final PackageSetting ps = mSettings.mPackages.get(packageName);
20779            if (!filterAppAccessLPr(ps, callingUid, userId)
20780                    && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
20781                            allowedByPermission, callingUid, userId)) {
20782                scheduleWritePackageRestrictionsLocked(userId);
20783            }
20784        }
20785    }
20786
20787    @Override
20788    public String getInstallerPackageName(String packageName) {
20789        final int callingUid = Binder.getCallingUid();
20790        synchronized (mPackages) {
20791            final PackageSetting ps = mSettings.mPackages.get(packageName);
20792            if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20793                return null;
20794            }
20795            return mSettings.getInstallerPackageNameLPr(packageName);
20796        }
20797    }
20798
20799    public boolean isOrphaned(String packageName) {
20800        // reader
20801        synchronized (mPackages) {
20802            return mSettings.isOrphaned(packageName);
20803        }
20804    }
20805
20806    @Override
20807    public int getApplicationEnabledSetting(String packageName, int userId) {
20808        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20809        int callingUid = Binder.getCallingUid();
20810        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20811                false /* requireFullPermission */, false /* checkShell */, "get enabled");
20812        // reader
20813        synchronized (mPackages) {
20814            if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
20815                return COMPONENT_ENABLED_STATE_DISABLED;
20816            }
20817            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
20818        }
20819    }
20820
20821    @Override
20822    public int getComponentEnabledSetting(ComponentName component, int userId) {
20823        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
20824        int callingUid = Binder.getCallingUid();
20825        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20826                false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
20827        synchronized (mPackages) {
20828            if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
20829                    component, TYPE_UNKNOWN, userId)) {
20830                return COMPONENT_ENABLED_STATE_DISABLED;
20831            }
20832            return mSettings.getComponentEnabledSettingLPr(component, userId);
20833        }
20834    }
20835
20836    @Override
20837    public void enterSafeMode() {
20838        enforceSystemOrRoot("Only the system can request entering safe mode");
20839
20840        if (!mSystemReady) {
20841            mSafeMode = true;
20842        }
20843    }
20844
20845    @Override
20846    public void systemReady() {
20847        enforceSystemOrRoot("Only the system can claim the system is ready");
20848
20849        mSystemReady = true;
20850        final ContentResolver resolver = mContext.getContentResolver();
20851        ContentObserver co = new ContentObserver(mHandler) {
20852            @Override
20853            public void onChange(boolean selfChange) {
20854                mWebInstantAppsDisabled =
20855                        (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) ||
20856                                (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0);
20857            }
20858        };
20859        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
20860                        .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
20861                false, co, UserHandle.USER_SYSTEM);
20862        mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
20863                        .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM);
20864        co.onChange(true);
20865
20866        // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to
20867        // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once
20868        // it is done.
20869        ContentObserver privAppOobObserver = new ContentObserver(mHandler) {
20870            @Override
20871            public void onChange(boolean selfChange) {
20872                int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0);
20873                SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB,
20874                        oobEnabled == 1 ? "true" : "false");
20875            }
20876        };
20877        mContext.getContentResolver().registerContentObserver(
20878                Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver,
20879                UserHandle.USER_SYSTEM);
20880        // At boot, restore the value from the setting, which persists across reboot.
20881        privAppOobObserver.onChange(true);
20882
20883        // Disable any carrier apps. We do this very early in boot to prevent the apps from being
20884        // disabled after already being started.
20885        CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
20886                mContext.getContentResolver(), UserHandle.USER_SYSTEM);
20887
20888        // Read the compatibilty setting when the system is ready.
20889        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
20890                mContext.getContentResolver(),
20891                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
20892        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
20893        if (DEBUG_SETTINGS) {
20894            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
20895        }
20896
20897        int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
20898
20899        synchronized (mPackages) {
20900            // Verify that all of the preferred activity components actually
20901            // exist.  It is possible for applications to be updated and at
20902            // that point remove a previously declared activity component that
20903            // had been set as a preferred activity.  We try to clean this up
20904            // the next time we encounter that preferred activity, but it is
20905            // possible for the user flow to never be able to return to that
20906            // situation so here we do a sanity check to make sure we haven't
20907            // left any junk around.
20908            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
20909            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20910                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20911                removed.clear();
20912                for (PreferredActivity pa : pir.filterSet()) {
20913                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
20914                        removed.add(pa);
20915                    }
20916                }
20917                if (removed.size() > 0) {
20918                    for (int r=0; r<removed.size(); r++) {
20919                        PreferredActivity pa = removed.get(r);
20920                        Slog.w(TAG, "Removing dangling preferred activity: "
20921                                + pa.mPref.mComponent);
20922                        pir.removeFilter(pa);
20923                    }
20924                    mSettings.writePackageRestrictionsLPr(
20925                            mSettings.mPreferredActivities.keyAt(i));
20926                }
20927            }
20928
20929            for (int userId : UserManagerService.getInstance().getUserIds()) {
20930                if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
20931                    grantPermissionsUserIds = ArrayUtils.appendInt(
20932                            grantPermissionsUserIds, userId);
20933                }
20934            }
20935        }
20936        sUserManager.systemReady();
20937        // If we upgraded grant all default permissions before kicking off.
20938        for (int userId : grantPermissionsUserIds) {
20939            mDefaultPermissionPolicy.grantDefaultPermissions(userId);
20940        }
20941
20942        if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
20943            // If we did not grant default permissions, we preload from this the
20944            // default permission exceptions lazily to ensure we don't hit the
20945            // disk on a new user creation.
20946            mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
20947        }
20948
20949        // Now that we've scanned all packages, and granted any default
20950        // permissions, ensure permissions are updated. Beware of dragons if you
20951        // try optimizing this.
20952        synchronized (mPackages) {
20953            mPermissionManager.updateAllPermissions(
20954                    StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
20955                    mPermissionCallback);
20956        }
20957
20958        // Kick off any messages waiting for system ready
20959        if (mPostSystemReadyMessages != null) {
20960            for (Message msg : mPostSystemReadyMessages) {
20961                msg.sendToTarget();
20962            }
20963            mPostSystemReadyMessages = null;
20964        }
20965
20966        // Watch for external volumes that come and go over time
20967        final StorageManager storage = mContext.getSystemService(StorageManager.class);
20968        storage.registerListener(mStorageListener);
20969
20970        mInstallerService.systemReady();
20971        mPackageDexOptimizer.systemReady();
20972
20973        StorageManagerInternal StorageManagerInternal = LocalServices.getService(
20974                StorageManagerInternal.class);
20975        StorageManagerInternal.addExternalStoragePolicy(
20976                new StorageManagerInternal.ExternalStorageMountPolicy() {
20977            @Override
20978            public int getMountMode(int uid, String packageName) {
20979                if (Process.isIsolated(uid)) {
20980                    return Zygote.MOUNT_EXTERNAL_NONE;
20981                }
20982                if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20983                    return Zygote.MOUNT_EXTERNAL_DEFAULT;
20984                }
20985                if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
20986                    return Zygote.MOUNT_EXTERNAL_READ;
20987                }
20988                return Zygote.MOUNT_EXTERNAL_WRITE;
20989            }
20990
20991            @Override
20992            public boolean hasExternalStorage(int uid, String packageName) {
20993                return true;
20994            }
20995        });
20996
20997        // Now that we're mostly running, clean up stale users and apps
20998        sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
20999        reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21000
21001        mPermissionManager.systemReady();
21002
21003        if (mInstantAppResolverConnection != null) {
21004            mContext.registerReceiver(new BroadcastReceiver() {
21005                @Override
21006                public void onReceive(Context context, Intent intent) {
21007                    mInstantAppResolverConnection.optimisticBind();
21008                    mContext.unregisterReceiver(this);
21009                }
21010            }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21011        }
21012    }
21013
21014    public void waitForAppDataPrepared() {
21015        if (mPrepareAppDataFuture == null) {
21016            return;
21017        }
21018        ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21019        mPrepareAppDataFuture = null;
21020    }
21021
21022    @Override
21023    public boolean isSafeMode() {
21024        // allow instant applications
21025        return mSafeMode;
21026    }
21027
21028    @Override
21029    public boolean hasSystemUidErrors() {
21030        // allow instant applications
21031        return mHasSystemUidErrors;
21032    }
21033
21034    static String arrayToString(int[] array) {
21035        StringBuffer buf = new StringBuffer(128);
21036        buf.append('[');
21037        if (array != null) {
21038            for (int i=0; i<array.length; i++) {
21039                if (i > 0) buf.append(", ");
21040                buf.append(array[i]);
21041            }
21042        }
21043        buf.append(']');
21044        return buf.toString();
21045    }
21046
21047    @Override
21048    public void onShellCommand(FileDescriptor in, FileDescriptor out,
21049            FileDescriptor err, String[] args, ShellCallback callback,
21050            ResultReceiver resultReceiver) {
21051        (new PackageManagerShellCommand(this)).exec(
21052                this, in, out, err, args, callback, resultReceiver);
21053    }
21054
21055    @Override
21056    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21057        if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21058
21059        DumpState dumpState = new DumpState();
21060        boolean fullPreferred = false;
21061        boolean checkin = false;
21062
21063        String packageName = null;
21064        ArraySet<String> permissionNames = null;
21065
21066        int opti = 0;
21067        while (opti < args.length) {
21068            String opt = args[opti];
21069            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21070                break;
21071            }
21072            opti++;
21073
21074            if ("-a".equals(opt)) {
21075                // Right now we only know how to print all.
21076            } else if ("-h".equals(opt)) {
21077                pw.println("Package manager dump options:");
21078                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
21079                pw.println("    --checkin: dump for a checkin");
21080                pw.println("    -f: print details of intent filters");
21081                pw.println("    -h: print this help");
21082                pw.println("  cmd may be one of:");
21083                pw.println("    l[ibraries]: list known shared libraries");
21084                pw.println("    f[eatures]: list device features");
21085                pw.println("    k[eysets]: print known keysets");
21086                pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21087                pw.println("    perm[issions]: dump permissions");
21088                pw.println("    permission [name ...]: dump declaration and use of given permission");
21089                pw.println("    pref[erred]: print preferred package settings");
21090                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21091                pw.println("    prov[iders]: dump content providers");
21092                pw.println("    p[ackages]: dump installed packages");
21093                pw.println("    s[hared-users]: dump shared user IDs");
21094                pw.println("    m[essages]: print collected runtime messages");
21095                pw.println("    v[erifiers]: print package verifier info");
21096                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21097                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21098                pw.println("    version: print database version info");
21099                pw.println("    write: write current settings now");
21100                pw.println("    installs: details about install sessions");
21101                pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21102                pw.println("    dexopt: dump dexopt state");
21103                pw.println("    compiler-stats: dump compiler statistics");
21104                pw.println("    service-permissions: dump permissions required by services");
21105                pw.println("    <package.name>: info about given package");
21106                return;
21107            } else if ("--checkin".equals(opt)) {
21108                checkin = true;
21109            } else if ("-f".equals(opt)) {
21110                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21111            } else if ("--proto".equals(opt)) {
21112                dumpProto(fd);
21113                return;
21114            } else {
21115                pw.println("Unknown argument: " + opt + "; use -h for help");
21116            }
21117        }
21118
21119        // Is the caller requesting to dump a particular piece of data?
21120        if (opti < args.length) {
21121            String cmd = args[opti];
21122            opti++;
21123            // Is this a package name?
21124            if ("android".equals(cmd) || cmd.contains(".")) {
21125                packageName = cmd;
21126                // When dumping a single package, we always dump all of its
21127                // filter information since the amount of data will be reasonable.
21128                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21129            } else if ("check-permission".equals(cmd)) {
21130                if (opti >= args.length) {
21131                    pw.println("Error: check-permission missing permission argument");
21132                    return;
21133                }
21134                String perm = args[opti];
21135                opti++;
21136                if (opti >= args.length) {
21137                    pw.println("Error: check-permission missing package argument");
21138                    return;
21139                }
21140
21141                String pkg = args[opti];
21142                opti++;
21143                int user = UserHandle.getUserId(Binder.getCallingUid());
21144                if (opti < args.length) {
21145                    try {
21146                        user = Integer.parseInt(args[opti]);
21147                    } catch (NumberFormatException e) {
21148                        pw.println("Error: check-permission user argument is not a number: "
21149                                + args[opti]);
21150                        return;
21151                    }
21152                }
21153
21154                // Normalize package name to handle renamed packages and static libs
21155                pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21156
21157                pw.println(checkPermission(perm, pkg, user));
21158                return;
21159            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21160                dumpState.setDump(DumpState.DUMP_LIBS);
21161            } else if ("f".equals(cmd) || "features".equals(cmd)) {
21162                dumpState.setDump(DumpState.DUMP_FEATURES);
21163            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21164                if (opti >= args.length) {
21165                    dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21166                            | DumpState.DUMP_SERVICE_RESOLVERS
21167                            | DumpState.DUMP_RECEIVER_RESOLVERS
21168                            | DumpState.DUMP_CONTENT_RESOLVERS);
21169                } else {
21170                    while (opti < args.length) {
21171                        String name = args[opti];
21172                        if ("a".equals(name) || "activity".equals(name)) {
21173                            dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21174                        } else if ("s".equals(name) || "service".equals(name)) {
21175                            dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21176                        } else if ("r".equals(name) || "receiver".equals(name)) {
21177                            dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21178                        } else if ("c".equals(name) || "content".equals(name)) {
21179                            dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21180                        } else {
21181                            pw.println("Error: unknown resolver table type: " + name);
21182                            return;
21183                        }
21184                        opti++;
21185                    }
21186                }
21187            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21188                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21189            } else if ("permission".equals(cmd)) {
21190                if (opti >= args.length) {
21191                    pw.println("Error: permission requires permission name");
21192                    return;
21193                }
21194                permissionNames = new ArraySet<>();
21195                while (opti < args.length) {
21196                    permissionNames.add(args[opti]);
21197                    opti++;
21198                }
21199                dumpState.setDump(DumpState.DUMP_PERMISSIONS
21200                        | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21201            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21202                dumpState.setDump(DumpState.DUMP_PREFERRED);
21203            } else if ("preferred-xml".equals(cmd)) {
21204                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21205                if (opti < args.length && "--full".equals(args[opti])) {
21206                    fullPreferred = true;
21207                    opti++;
21208                }
21209            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21210                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21211            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21212                dumpState.setDump(DumpState.DUMP_PACKAGES);
21213            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21214                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21215            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21216                dumpState.setDump(DumpState.DUMP_PROVIDERS);
21217            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21218                dumpState.setDump(DumpState.DUMP_MESSAGES);
21219            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21220                dumpState.setDump(DumpState.DUMP_VERIFIERS);
21221            } else if ("i".equals(cmd) || "ifv".equals(cmd)
21222                    || "intent-filter-verifiers".equals(cmd)) {
21223                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21224            } else if ("version".equals(cmd)) {
21225                dumpState.setDump(DumpState.DUMP_VERSION);
21226            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21227                dumpState.setDump(DumpState.DUMP_KEYSETS);
21228            } else if ("installs".equals(cmd)) {
21229                dumpState.setDump(DumpState.DUMP_INSTALLS);
21230            } else if ("frozen".equals(cmd)) {
21231                dumpState.setDump(DumpState.DUMP_FROZEN);
21232            } else if ("volumes".equals(cmd)) {
21233                dumpState.setDump(DumpState.DUMP_VOLUMES);
21234            } else if ("dexopt".equals(cmd)) {
21235                dumpState.setDump(DumpState.DUMP_DEXOPT);
21236            } else if ("compiler-stats".equals(cmd)) {
21237                dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21238            } else if ("changes".equals(cmd)) {
21239                dumpState.setDump(DumpState.DUMP_CHANGES);
21240            } else if ("service-permissions".equals(cmd)) {
21241                dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21242            } else if ("write".equals(cmd)) {
21243                synchronized (mPackages) {
21244                    mSettings.writeLPr();
21245                    pw.println("Settings written.");
21246                    return;
21247                }
21248            }
21249        }
21250
21251        if (checkin) {
21252            pw.println("vers,1");
21253        }
21254
21255        // reader
21256        synchronized (mPackages) {
21257            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21258                if (!checkin) {
21259                    if (dumpState.onTitlePrinted())
21260                        pw.println();
21261                    pw.println("Database versions:");
21262                    mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21263                }
21264            }
21265
21266            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21267                if (!checkin) {
21268                    if (dumpState.onTitlePrinted())
21269                        pw.println();
21270                    pw.println("Verifiers:");
21271                    pw.print("  Required: ");
21272                    pw.print(mRequiredVerifierPackage);
21273                    pw.print(" (uid=");
21274                    pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21275                            UserHandle.USER_SYSTEM));
21276                    pw.println(")");
21277                } else if (mRequiredVerifierPackage != null) {
21278                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21279                    pw.print(",");
21280                    pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21281                            UserHandle.USER_SYSTEM));
21282                }
21283            }
21284
21285            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21286                    packageName == null) {
21287                if (mIntentFilterVerifierComponent != null) {
21288                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21289                    if (!checkin) {
21290                        if (dumpState.onTitlePrinted())
21291                            pw.println();
21292                        pw.println("Intent Filter Verifier:");
21293                        pw.print("  Using: ");
21294                        pw.print(verifierPackageName);
21295                        pw.print(" (uid=");
21296                        pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21297                                UserHandle.USER_SYSTEM));
21298                        pw.println(")");
21299                    } else if (verifierPackageName != null) {
21300                        pw.print("ifv,"); pw.print(verifierPackageName);
21301                        pw.print(",");
21302                        pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21303                                UserHandle.USER_SYSTEM));
21304                    }
21305                } else {
21306                    pw.println();
21307                    pw.println("No Intent Filter Verifier available!");
21308                }
21309            }
21310
21311            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
21312                boolean printedHeader = false;
21313                final Iterator<String> it = mSharedLibraries.keySet().iterator();
21314                while (it.hasNext()) {
21315                    String libName = it.next();
21316                    LongSparseArray<SharedLibraryEntry> versionedLib
21317                            = mSharedLibraries.get(libName);
21318                    if (versionedLib == null) {
21319                        continue;
21320                    }
21321                    final int versionCount = versionedLib.size();
21322                    for (int i = 0; i < versionCount; i++) {
21323                        SharedLibraryEntry libEntry = versionedLib.valueAt(i);
21324                        if (!checkin) {
21325                            if (!printedHeader) {
21326                                if (dumpState.onTitlePrinted())
21327                                    pw.println();
21328                                pw.println("Libraries:");
21329                                printedHeader = true;
21330                            }
21331                            pw.print("  ");
21332                        } else {
21333                            pw.print("lib,");
21334                        }
21335                        pw.print(libEntry.info.getName());
21336                        if (libEntry.info.isStatic()) {
21337                            pw.print(" version=" + libEntry.info.getLongVersion());
21338                        }
21339                        if (!checkin) {
21340                            pw.print(" -> ");
21341                        }
21342                        if (libEntry.path != null) {
21343                            pw.print(" (jar) ");
21344                            pw.print(libEntry.path);
21345                        } else {
21346                            pw.print(" (apk) ");
21347                            pw.print(libEntry.apk);
21348                        }
21349                        pw.println();
21350                    }
21351                }
21352            }
21353
21354            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
21355                if (dumpState.onTitlePrinted())
21356                    pw.println();
21357                if (!checkin) {
21358                    pw.println("Features:");
21359                }
21360
21361                synchronized (mAvailableFeatures) {
21362                    for (FeatureInfo feat : mAvailableFeatures.values()) {
21363                        if (checkin) {
21364                            pw.print("feat,");
21365                            pw.print(feat.name);
21366                            pw.print(",");
21367                            pw.println(feat.version);
21368                        } else {
21369                            pw.print("  ");
21370                            pw.print(feat.name);
21371                            if (feat.version > 0) {
21372                                pw.print(" version=");
21373                                pw.print(feat.version);
21374                            }
21375                            pw.println();
21376                        }
21377                    }
21378                }
21379            }
21380
21381            if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
21382                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
21383                        : "Activity Resolver Table:", "  ", packageName,
21384                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21385                    dumpState.setTitlePrinted(true);
21386                }
21387            }
21388            if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
21389                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
21390                        : "Receiver Resolver Table:", "  ", packageName,
21391                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21392                    dumpState.setTitlePrinted(true);
21393                }
21394            }
21395            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
21396                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
21397                        : "Service Resolver Table:", "  ", packageName,
21398                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21399                    dumpState.setTitlePrinted(true);
21400                }
21401            }
21402            if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
21403                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
21404                        : "Provider Resolver Table:", "  ", packageName,
21405                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
21406                    dumpState.setTitlePrinted(true);
21407                }
21408            }
21409
21410            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
21411                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21412                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21413                    int user = mSettings.mPreferredActivities.keyAt(i);
21414                    if (pir.dump(pw,
21415                            dumpState.getTitlePrinted()
21416                                ? "\nPreferred Activities User " + user + ":"
21417                                : "Preferred Activities User " + user + ":", "  ",
21418                            packageName, true, false)) {
21419                        dumpState.setTitlePrinted(true);
21420                    }
21421                }
21422            }
21423
21424            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
21425                pw.flush();
21426                FileOutputStream fout = new FileOutputStream(fd);
21427                BufferedOutputStream str = new BufferedOutputStream(fout);
21428                XmlSerializer serializer = new FastXmlSerializer();
21429                try {
21430                    serializer.setOutput(str, StandardCharsets.UTF_8.name());
21431                    serializer.startDocument(null, true);
21432                    serializer.setFeature(
21433                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
21434                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
21435                    serializer.endDocument();
21436                    serializer.flush();
21437                } catch (IllegalArgumentException e) {
21438                    pw.println("Failed writing: " + e);
21439                } catch (IllegalStateException e) {
21440                    pw.println("Failed writing: " + e);
21441                } catch (IOException e) {
21442                    pw.println("Failed writing: " + e);
21443                }
21444            }
21445
21446            if (!checkin
21447                    && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
21448                    && packageName == null) {
21449                pw.println();
21450                int count = mSettings.mPackages.size();
21451                if (count == 0) {
21452                    pw.println("No applications!");
21453                    pw.println();
21454                } else {
21455                    final String prefix = "  ";
21456                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
21457                    if (allPackageSettings.size() == 0) {
21458                        pw.println("No domain preferred apps!");
21459                        pw.println();
21460                    } else {
21461                        pw.println("App verification status:");
21462                        pw.println();
21463                        count = 0;
21464                        for (PackageSetting ps : allPackageSettings) {
21465                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
21466                            if (ivi == null || ivi.getPackageName() == null) continue;
21467                            pw.println(prefix + "Package: " + ivi.getPackageName());
21468                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
21469                            pw.println(prefix + "Status:  " + ivi.getStatusString());
21470                            pw.println();
21471                            count++;
21472                        }
21473                        if (count == 0) {
21474                            pw.println(prefix + "No app verification established.");
21475                            pw.println();
21476                        }
21477                        for (int userId : sUserManager.getUserIds()) {
21478                            pw.println("App linkages for user " + userId + ":");
21479                            pw.println();
21480                            count = 0;
21481                            for (PackageSetting ps : allPackageSettings) {
21482                                final long status = ps.getDomainVerificationStatusForUser(userId);
21483                                if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
21484                                        && !DEBUG_DOMAIN_VERIFICATION) {
21485                                    continue;
21486                                }
21487                                pw.println(prefix + "Package: " + ps.name);
21488                                pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
21489                                String statusStr = IntentFilterVerificationInfo.
21490                                        getStatusStringFromValue(status);
21491                                pw.println(prefix + "Status:  " + statusStr);
21492                                pw.println();
21493                                count++;
21494                            }
21495                            if (count == 0) {
21496                                pw.println(prefix + "No configured app linkages.");
21497                                pw.println();
21498                            }
21499                        }
21500                    }
21501                }
21502            }
21503
21504            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
21505                mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
21506            }
21507
21508            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
21509                boolean printedSomething = false;
21510                for (PackageParser.Provider p : mProviders.mProviders.values()) {
21511                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21512                        continue;
21513                    }
21514                    if (!printedSomething) {
21515                        if (dumpState.onTitlePrinted())
21516                            pw.println();
21517                        pw.println("Registered ContentProviders:");
21518                        printedSomething = true;
21519                    }
21520                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
21521                    pw.print("    "); pw.println(p.toString());
21522                }
21523                printedSomething = false;
21524                for (Map.Entry<String, PackageParser.Provider> entry :
21525                        mProvidersByAuthority.entrySet()) {
21526                    PackageParser.Provider p = entry.getValue();
21527                    if (packageName != null && !packageName.equals(p.info.packageName)) {
21528                        continue;
21529                    }
21530                    if (!printedSomething) {
21531                        if (dumpState.onTitlePrinted())
21532                            pw.println();
21533                        pw.println("ContentProvider Authorities:");
21534                        printedSomething = true;
21535                    }
21536                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
21537                    pw.print("    "); pw.println(p.toString());
21538                    if (p.info != null && p.info.applicationInfo != null) {
21539                        final String appInfo = p.info.applicationInfo.toString();
21540                        pw.print("      applicationInfo="); pw.println(appInfo);
21541                    }
21542                }
21543            }
21544
21545            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
21546                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
21547            }
21548
21549            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
21550                mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
21551            }
21552
21553            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
21554                mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
21555            }
21556
21557            if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
21558                if (dumpState.onTitlePrinted()) pw.println();
21559                pw.println("Package Changes:");
21560                pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
21561                final int K = mChangedPackages.size();
21562                for (int i = 0; i < K; i++) {
21563                    final SparseArray<String> changes = mChangedPackages.valueAt(i);
21564                    pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
21565                    final int N = changes.size();
21566                    if (N == 0) {
21567                        pw.print("    "); pw.println("No packages changed");
21568                    } else {
21569                        for (int j = 0; j < N; j++) {
21570                            final String pkgName = changes.valueAt(j);
21571                            final int sequenceNumber = changes.keyAt(j);
21572                            pw.print("    ");
21573                            pw.print("seq=");
21574                            pw.print(sequenceNumber);
21575                            pw.print(", package=");
21576                            pw.println(pkgName);
21577                        }
21578                    }
21579                }
21580            }
21581
21582            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) {
21583                mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState);
21584            }
21585
21586            if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
21587                // XXX should handle packageName != null by dumping only install data that
21588                // the given package is involved with.
21589                if (dumpState.onTitlePrinted()) pw.println();
21590
21591                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21592                    ipw.println();
21593                    ipw.println("Frozen packages:");
21594                    ipw.increaseIndent();
21595                    if (mFrozenPackages.size() == 0) {
21596                        ipw.println("(none)");
21597                    } else {
21598                        for (int i = 0; i < mFrozenPackages.size(); i++) {
21599                            ipw.println(mFrozenPackages.valueAt(i));
21600                        }
21601                    }
21602                    ipw.decreaseIndent();
21603                }
21604            }
21605
21606            if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
21607                if (dumpState.onTitlePrinted()) pw.println();
21608
21609                try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120)) {
21610                    ipw.println();
21611                    ipw.println("Loaded volumes:");
21612                    ipw.increaseIndent();
21613                    if (mLoadedVolumes.size() == 0) {
21614                        ipw.println("(none)");
21615                    } else {
21616                        for (int i = 0; i < mLoadedVolumes.size(); i++) {
21617                            ipw.println(mLoadedVolumes.valueAt(i));
21618                        }
21619                    }
21620                    ipw.decreaseIndent();
21621                }
21622            }
21623
21624            if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
21625                    && packageName == null) {
21626                if (dumpState.onTitlePrinted()) pw.println();
21627                pw.println("Service permissions:");
21628
21629                final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator();
21630                while (filterIterator.hasNext()) {
21631                    final ServiceIntentInfo info = filterIterator.next();
21632                    final ServiceInfo serviceInfo = info.service.info;
21633                    final String permission = serviceInfo.permission;
21634                    if (permission != null) {
21635                        pw.print("    ");
21636                        pw.print(serviceInfo.getComponentName().flattenToShortString());
21637                        pw.print(": ");
21638                        pw.println(permission);
21639                    }
21640                }
21641            }
21642
21643            if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
21644                if (dumpState.onTitlePrinted()) pw.println();
21645                dumpDexoptStateLPr(pw, packageName);
21646            }
21647
21648            if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
21649                if (dumpState.onTitlePrinted()) pw.println();
21650                dumpCompilerStatsLPr(pw, packageName);
21651            }
21652
21653            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
21654                if (dumpState.onTitlePrinted()) pw.println();
21655                mSettings.dumpReadMessagesLPr(pw, dumpState);
21656
21657                pw.println();
21658                pw.println("Package warning messages:");
21659                dumpCriticalInfo(pw, null);
21660            }
21661
21662            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
21663                dumpCriticalInfo(pw, "msg,");
21664            }
21665        }
21666
21667        // PackageInstaller should be called outside of mPackages lock
21668        if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
21669            // XXX should handle packageName != null by dumping only install data that
21670            // the given package is involved with.
21671            if (dumpState.onTitlePrinted()) pw.println();
21672            mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
21673        }
21674    }
21675
21676    private void dumpProto(FileDescriptor fd) {
21677        final ProtoOutputStream proto = new ProtoOutputStream(fd);
21678
21679        synchronized (mPackages) {
21680            final long requiredVerifierPackageToken =
21681                    proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
21682            proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
21683            proto.write(
21684                    PackageServiceDumpProto.PackageShortProto.UID,
21685                    getPackageUid(
21686                            mRequiredVerifierPackage,
21687                            MATCH_DEBUG_TRIAGED_MISSING,
21688                            UserHandle.USER_SYSTEM));
21689            proto.end(requiredVerifierPackageToken);
21690
21691            if (mIntentFilterVerifierComponent != null) {
21692                String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21693                final long verifierPackageToken =
21694                        proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
21695                proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
21696                proto.write(
21697                        PackageServiceDumpProto.PackageShortProto.UID,
21698                        getPackageUid(
21699                                verifierPackageName,
21700                                MATCH_DEBUG_TRIAGED_MISSING,
21701                                UserHandle.USER_SYSTEM));
21702                proto.end(verifierPackageToken);
21703            }
21704
21705            dumpSharedLibrariesProto(proto);
21706            dumpFeaturesProto(proto);
21707            mSettings.dumpPackagesProto(proto);
21708            mSettings.dumpSharedUsersProto(proto);
21709            dumpCriticalInfo(proto);
21710        }
21711        proto.flush();
21712    }
21713
21714    private void dumpFeaturesProto(ProtoOutputStream proto) {
21715        synchronized (mAvailableFeatures) {
21716            final int count = mAvailableFeatures.size();
21717            for (int i = 0; i < count; i++) {
21718                mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
21719            }
21720        }
21721    }
21722
21723    private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
21724        final int count = mSharedLibraries.size();
21725        for (int i = 0; i < count; i++) {
21726            final String libName = mSharedLibraries.keyAt(i);
21727            LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName);
21728            if (versionedLib == null) {
21729                continue;
21730            }
21731            final int versionCount = versionedLib.size();
21732            for (int j = 0; j < versionCount; j++) {
21733                final SharedLibraryEntry libEntry = versionedLib.valueAt(j);
21734                final long sharedLibraryToken =
21735                        proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
21736                proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName());
21737                final boolean isJar = (libEntry.path != null);
21738                proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
21739                if (isJar) {
21740                    proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path);
21741                } else {
21742                    proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk);
21743                }
21744                proto.end(sharedLibraryToken);
21745            }
21746        }
21747    }
21748
21749    private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
21750        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21751            ipw.println();
21752            ipw.println("Dexopt state:");
21753            ipw.increaseIndent();
21754            Collection<PackageParser.Package> packages = null;
21755            if (packageName != null) {
21756                PackageParser.Package targetPackage = mPackages.get(packageName);
21757                if (targetPackage != null) {
21758                    packages = Collections.singletonList(targetPackage);
21759                } else {
21760                    ipw.println("Unable to find package: " + packageName);
21761                    return;
21762                }
21763            } else {
21764                packages = mPackages.values();
21765            }
21766
21767            for (PackageParser.Package pkg : packages) {
21768                ipw.println("[" + pkg.packageName + "]");
21769                ipw.increaseIndent();
21770                mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
21771                        mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
21772                ipw.decreaseIndent();
21773            }
21774        }
21775    }
21776
21777    private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
21778        try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ")) {
21779            ipw.println();
21780            ipw.println("Compiler stats:");
21781            ipw.increaseIndent();
21782            Collection<PackageParser.Package> packages = null;
21783            if (packageName != null) {
21784                PackageParser.Package targetPackage = mPackages.get(packageName);
21785                if (targetPackage != null) {
21786                    packages = Collections.singletonList(targetPackage);
21787                } else {
21788                    ipw.println("Unable to find package: " + packageName);
21789                    return;
21790                }
21791            } else {
21792                packages = mPackages.values();
21793            }
21794
21795            for (PackageParser.Package pkg : packages) {
21796                ipw.println("[" + pkg.packageName + "]");
21797                ipw.increaseIndent();
21798
21799                CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
21800                if (stats == null) {
21801                    ipw.println("(No recorded stats)");
21802                } else {
21803                    stats.dump(ipw);
21804                }
21805                ipw.decreaseIndent();
21806            }
21807        }
21808    }
21809
21810    private String dumpDomainString(String packageName) {
21811        List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
21812                .getList();
21813        List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
21814
21815        ArraySet<String> result = new ArraySet<>();
21816        if (iviList.size() > 0) {
21817            for (IntentFilterVerificationInfo ivi : iviList) {
21818                for (String host : ivi.getDomains()) {
21819                    result.add(host);
21820                }
21821            }
21822        }
21823        if (filters != null && filters.size() > 0) {
21824            for (IntentFilter filter : filters) {
21825                if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
21826                        && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
21827                                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
21828                    result.addAll(filter.getHostsList());
21829                }
21830            }
21831        }
21832
21833        StringBuilder sb = new StringBuilder(result.size() * 16);
21834        for (String domain : result) {
21835            if (sb.length() > 0) sb.append(" ");
21836            sb.append(domain);
21837        }
21838        return sb.toString();
21839    }
21840
21841    // ------- apps on sdcard specific code -------
21842    static final boolean DEBUG_SD_INSTALL = false;
21843
21844    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
21845
21846    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
21847
21848    private boolean mMediaMounted = false;
21849
21850    static String getEncryptKey() {
21851        try {
21852            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
21853                    SD_ENCRYPTION_KEYSTORE_NAME);
21854            if (sdEncKey == null) {
21855                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
21856                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
21857                if (sdEncKey == null) {
21858                    Slog.e(TAG, "Failed to create encryption keys");
21859                    return null;
21860                }
21861            }
21862            return sdEncKey;
21863        } catch (NoSuchAlgorithmException nsae) {
21864            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
21865            return null;
21866        } catch (IOException ioe) {
21867            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
21868            return null;
21869        }
21870    }
21871
21872    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21873            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
21874        final int size = infos.size();
21875        final String[] packageNames = new String[size];
21876        final int[] packageUids = new int[size];
21877        for (int i = 0; i < size; i++) {
21878            final ApplicationInfo info = infos.get(i);
21879            packageNames[i] = info.packageName;
21880            packageUids[i] = info.uid;
21881        }
21882        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
21883                finishedReceiver);
21884    }
21885
21886    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21887            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21888        sendResourcesChangedBroadcast(mediaStatus, replacing,
21889                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
21890    }
21891
21892    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
21893            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
21894        int size = pkgList.length;
21895        if (size > 0) {
21896            // Send broadcasts here
21897            Bundle extras = new Bundle();
21898            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
21899            if (uidArr != null) {
21900                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
21901            }
21902            if (replacing) {
21903                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
21904            }
21905            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
21906                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
21907            sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
21908        }
21909    }
21910
21911    private void loadPrivatePackages(final VolumeInfo vol) {
21912        mHandler.post(new Runnable() {
21913            @Override
21914            public void run() {
21915                loadPrivatePackagesInner(vol);
21916            }
21917        });
21918    }
21919
21920    private void loadPrivatePackagesInner(VolumeInfo vol) {
21921        final String volumeUuid = vol.fsUuid;
21922        if (TextUtils.isEmpty(volumeUuid)) {
21923            Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
21924            return;
21925        }
21926
21927        final ArrayList<PackageFreezer> freezers = new ArrayList<>();
21928        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
21929        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
21930
21931        final VersionInfo ver;
21932        final List<PackageSetting> packages;
21933        synchronized (mPackages) {
21934            ver = mSettings.findOrCreateVersion(volumeUuid);
21935            packages = mSettings.getVolumePackagesLPr(volumeUuid);
21936        }
21937
21938        for (PackageSetting ps : packages) {
21939            freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
21940            synchronized (mInstallLock) {
21941                final PackageParser.Package pkg;
21942                try {
21943                    pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
21944                    loaded.add(pkg.applicationInfo);
21945
21946                } catch (PackageManagerException e) {
21947                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
21948                }
21949
21950                if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
21951                    clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
21952                            StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE
21953                                    | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
21954                }
21955            }
21956        }
21957
21958        // Reconcile app data for all started/unlocked users
21959        final StorageManager sm = mContext.getSystemService(StorageManager.class);
21960        final UserManager um = mContext.getSystemService(UserManager.class);
21961        UserManagerInternal umInternal = getUserManagerInternal();
21962        for (UserInfo user : um.getUsers()) {
21963            final int flags;
21964            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
21965                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
21966            } else if (umInternal.isUserRunning(user.id)) {
21967                flags = StorageManager.FLAG_STORAGE_DE;
21968            } else {
21969                continue;
21970            }
21971
21972            try {
21973                sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
21974                synchronized (mInstallLock) {
21975                    reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
21976                }
21977            } catch (IllegalStateException e) {
21978                // Device was probably ejected, and we'll process that event momentarily
21979                Slog.w(TAG, "Failed to prepare storage: " + e);
21980            }
21981        }
21982
21983        synchronized (mPackages) {
21984            final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
21985            if (sdkUpdated) {
21986                logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
21987                        + mSdkVersion + "; regranting permissions for " + volumeUuid);
21988            }
21989            mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
21990                    mPermissionCallback);
21991
21992            // Yay, everything is now upgraded
21993            ver.forceCurrent();
21994
21995            mSettings.writeLPr();
21996        }
21997
21998        for (PackageFreezer freezer : freezers) {
21999            freezer.close();
22000        }
22001
22002        if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22003        sendResourcesChangedBroadcast(true, false, loaded, null);
22004        mLoadedVolumes.add(vol.getId());
22005    }
22006
22007    private void unloadPrivatePackages(final VolumeInfo vol) {
22008        mHandler.post(new Runnable() {
22009            @Override
22010            public void run() {
22011                unloadPrivatePackagesInner(vol);
22012            }
22013        });
22014    }
22015
22016    private void unloadPrivatePackagesInner(VolumeInfo vol) {
22017        final String volumeUuid = vol.fsUuid;
22018        if (TextUtils.isEmpty(volumeUuid)) {
22019            Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22020            return;
22021        }
22022
22023        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22024        synchronized (mInstallLock) {
22025        synchronized (mPackages) {
22026            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22027            for (PackageSetting ps : packages) {
22028                if (ps.pkg == null) continue;
22029
22030                final ApplicationInfo info = ps.pkg.applicationInfo;
22031                final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22032                final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22033
22034                try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22035                        "unloadPrivatePackagesInner")) {
22036                    if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22037                            false, null)) {
22038                        unloaded.add(info);
22039                    } else {
22040                        Slog.w(TAG, "Failed to unload " + ps.codePath);
22041                    }
22042                }
22043
22044                // Try very hard to release any references to this package
22045                // so we don't risk the system server being killed due to
22046                // open FDs
22047                AttributeCache.instance().removePackage(ps.name);
22048            }
22049
22050            mSettings.writeLPr();
22051        }
22052        }
22053
22054        if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22055        sendResourcesChangedBroadcast(false, false, unloaded, null);
22056        mLoadedVolumes.remove(vol.getId());
22057
22058        // Try very hard to release any references to this path so we don't risk
22059        // the system server being killed due to open FDs
22060        ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22061
22062        for (int i = 0; i < 3; i++) {
22063            System.gc();
22064            System.runFinalization();
22065        }
22066    }
22067
22068    private void assertPackageKnown(String volumeUuid, String packageName)
22069            throws PackageManagerException {
22070        synchronized (mPackages) {
22071            // Normalize package name to handle renamed packages
22072            packageName = normalizePackageNameLPr(packageName);
22073
22074            final PackageSetting ps = mSettings.mPackages.get(packageName);
22075            if (ps == null) {
22076                throw new PackageManagerException("Package " + packageName + " is unknown");
22077            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22078                throw new PackageManagerException(
22079                        "Package " + packageName + " found on unknown volume " + volumeUuid
22080                                + "; expected volume " + ps.volumeUuid);
22081            }
22082        }
22083    }
22084
22085    private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22086            throws PackageManagerException {
22087        synchronized (mPackages) {
22088            // Normalize package name to handle renamed packages
22089            packageName = normalizePackageNameLPr(packageName);
22090
22091            final PackageSetting ps = mSettings.mPackages.get(packageName);
22092            if (ps == null) {
22093                throw new PackageManagerException("Package " + packageName + " is unknown");
22094            } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22095                throw new PackageManagerException(
22096                        "Package " + packageName + " found on unknown volume " + volumeUuid
22097                                + "; expected volume " + ps.volumeUuid);
22098            } else if (!ps.getInstalled(userId)) {
22099                throw new PackageManagerException(
22100                        "Package " + packageName + " not installed for user " + userId);
22101            }
22102        }
22103    }
22104
22105    private List<String> collectAbsoluteCodePaths() {
22106        synchronized (mPackages) {
22107            List<String> codePaths = new ArrayList<>();
22108            final int packageCount = mSettings.mPackages.size();
22109            for (int i = 0; i < packageCount; i++) {
22110                final PackageSetting ps = mSettings.mPackages.valueAt(i);
22111                codePaths.add(ps.codePath.getAbsolutePath());
22112            }
22113            return codePaths;
22114        }
22115    }
22116
22117    /**
22118     * Examine all apps present on given mounted volume, and destroy apps that
22119     * aren't expected, either due to uninstallation or reinstallation on
22120     * another volume.
22121     */
22122    private void reconcileApps(String volumeUuid) {
22123        List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22124        List<File> filesToDelete = null;
22125
22126        final File[] files = FileUtils.listFilesOrEmpty(
22127                Environment.getDataAppDirectory(volumeUuid));
22128        for (File file : files) {
22129            final boolean isPackage = (isApkFile(file) || file.isDirectory())
22130                    && !PackageInstallerService.isStageName(file.getName());
22131            if (!isPackage) {
22132                // Ignore entries which are not packages
22133                continue;
22134            }
22135
22136            String absolutePath = file.getAbsolutePath();
22137
22138            boolean pathValid = false;
22139            final int absoluteCodePathCount = absoluteCodePaths.size();
22140            for (int i = 0; i < absoluteCodePathCount; i++) {
22141                String absoluteCodePath = absoluteCodePaths.get(i);
22142                if (absolutePath.startsWith(absoluteCodePath)) {
22143                    pathValid = true;
22144                    break;
22145                }
22146            }
22147
22148            if (!pathValid) {
22149                if (filesToDelete == null) {
22150                    filesToDelete = new ArrayList<>();
22151                }
22152                filesToDelete.add(file);
22153            }
22154        }
22155
22156        if (filesToDelete != null) {
22157            final int fileToDeleteCount = filesToDelete.size();
22158            for (int i = 0; i < fileToDeleteCount; i++) {
22159                File fileToDelete = filesToDelete.get(i);
22160                logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22161                synchronized (mInstallLock) {
22162                    removeCodePathLI(fileToDelete);
22163                }
22164            }
22165        }
22166    }
22167
22168    /**
22169     * Reconcile all app data for the given user.
22170     * <p>
22171     * Verifies that directories exist and that ownership and labeling is
22172     * correct for all installed apps on all mounted volumes.
22173     */
22174    void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22175        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22176        for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22177            final String volumeUuid = vol.getFsUuid();
22178            synchronized (mInstallLock) {
22179                reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22180            }
22181        }
22182    }
22183
22184    private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22185            boolean migrateAppData) {
22186        reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22187    }
22188
22189    /**
22190     * Reconcile all app data on given mounted volume.
22191     * <p>
22192     * Destroys app data that isn't expected, either due to uninstallation or
22193     * reinstallation on another volume.
22194     * <p>
22195     * Verifies that directories exist and that ownership and labeling is
22196     * correct for all installed apps.
22197     * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true)
22198     */
22199    private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22200            boolean migrateAppData, boolean onlyCoreApps) {
22201        Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22202                + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22203        List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22204
22205        final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22206        final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22207
22208        // First look for stale data that doesn't belong, and check if things
22209        // have changed since we did our last restorecon
22210        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22211            if (StorageManager.isFileEncryptedNativeOrEmulated()
22212                    && !StorageManager.isUserKeyUnlocked(userId)) {
22213                throw new RuntimeException(
22214                        "Yikes, someone asked us to reconcile CE storage while " + userId
22215                                + " was still locked; this would have caused massive data loss!");
22216            }
22217
22218            final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22219            for (File file : files) {
22220                final String packageName = file.getName();
22221                try {
22222                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22223                } catch (PackageManagerException e) {
22224                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22225                    try {
22226                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22227                                StorageManager.FLAG_STORAGE_CE, 0);
22228                    } catch (InstallerException e2) {
22229                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22230                    }
22231                }
22232            }
22233        }
22234        if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22235            final File[] files = FileUtils.listFilesOrEmpty(deDir);
22236            for (File file : files) {
22237                final String packageName = file.getName();
22238                try {
22239                    assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22240                } catch (PackageManagerException e) {
22241                    logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22242                    try {
22243                        mInstaller.destroyAppData(volumeUuid, packageName, userId,
22244                                StorageManager.FLAG_STORAGE_DE, 0);
22245                    } catch (InstallerException e2) {
22246                        logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22247                    }
22248                }
22249            }
22250        }
22251
22252        // Ensure that data directories are ready to roll for all packages
22253        // installed for this volume and user
22254        final List<PackageSetting> packages;
22255        synchronized (mPackages) {
22256            packages = mSettings.getVolumePackagesLPr(volumeUuid);
22257        }
22258        int preparedCount = 0;
22259        for (PackageSetting ps : packages) {
22260            final String packageName = ps.name;
22261            if (ps.pkg == null) {
22262                Slog.w(TAG, "Odd, missing scanned package " + packageName);
22263                // TODO: might be due to legacy ASEC apps; we should circle back
22264                // and reconcile again once they're scanned
22265                continue;
22266            }
22267            // Skip non-core apps if requested
22268            if (onlyCoreApps && !ps.pkg.coreApp) {
22269                result.add(packageName);
22270                continue;
22271            }
22272
22273            if (ps.getInstalled(userId)) {
22274                prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22275                preparedCount++;
22276            }
22277        }
22278
22279        Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22280        return result;
22281    }
22282
22283    /**
22284     * Prepare app data for the given app just after it was installed or
22285     * upgraded. This method carefully only touches users that it's installed
22286     * for, and it forces a restorecon to handle any seinfo changes.
22287     * <p>
22288     * Verifies that directories exist and that ownership and labeling is
22289     * correct for all installed apps. If there is an ownership mismatch, it
22290     * will try recovering system apps by wiping data; third-party app data is
22291     * left intact.
22292     * <p>
22293     * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22294     */
22295    private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22296        final PackageSetting ps;
22297        synchronized (mPackages) {
22298            ps = mSettings.mPackages.get(pkg.packageName);
22299            mSettings.writeKernelMappingLPr(ps);
22300        }
22301
22302        final UserManager um = mContext.getSystemService(UserManager.class);
22303        UserManagerInternal umInternal = getUserManagerInternal();
22304        for (UserInfo user : um.getUsers()) {
22305            final int flags;
22306            if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22307                flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22308            } else if (umInternal.isUserRunning(user.id)) {
22309                flags = StorageManager.FLAG_STORAGE_DE;
22310            } else {
22311                continue;
22312            }
22313
22314            if (ps.getInstalled(user.id)) {
22315                // TODO: when user data is locked, mark that we're still dirty
22316                prepareAppDataLIF(pkg, user.id, flags);
22317            }
22318        }
22319    }
22320
22321    /**
22322     * Prepare app data for the given app.
22323     * <p>
22324     * Verifies that directories exist and that ownership and labeling is
22325     * correct for all installed apps. If there is an ownership mismatch, this
22326     * will try recovering system apps by wiping data; third-party app data is
22327     * left intact.
22328     */
22329    private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22330        if (pkg == null) {
22331            Slog.wtf(TAG, "Package was null!", new Throwable());
22332            return;
22333        }
22334        prepareAppDataLeafLIF(pkg, userId, flags);
22335        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22336        for (int i = 0; i < childCount; i++) {
22337            prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22338        }
22339    }
22340
22341    private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22342            boolean maybeMigrateAppData) {
22343        prepareAppDataLIF(pkg, userId, flags);
22344
22345        if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22346            // We may have just shuffled around app data directories, so
22347            // prepare them one more time
22348            prepareAppDataLIF(pkg, userId, flags);
22349        }
22350    }
22351
22352    private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22353        if (DEBUG_APP_DATA) {
22354            Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22355                    + Integer.toHexString(flags));
22356        }
22357
22358        final String volumeUuid = pkg.volumeUuid;
22359        final String packageName = pkg.packageName;
22360        final ApplicationInfo app = pkg.applicationInfo;
22361        final int appId = UserHandle.getAppId(app.uid);
22362
22363        Preconditions.checkNotNull(app.seInfo);
22364
22365        long ceDataInode = -1;
22366        try {
22367            ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22368                    appId, app.seInfo, app.targetSdkVersion);
22369        } catch (InstallerException e) {
22370            if (app.isSystemApp()) {
22371                logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
22372                        + ", but trying to recover: " + e);
22373                destroyAppDataLeafLIF(pkg, userId, flags);
22374                try {
22375                    ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
22376                            appId, app.seInfo, app.targetSdkVersion);
22377                    logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
22378                } catch (InstallerException e2) {
22379                    logCriticalInfo(Log.DEBUG, "Recovery failed!");
22380                }
22381            } else {
22382                Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
22383            }
22384        }
22385        // Prepare the application profiles only for upgrades and first boot (so that we don't
22386        // repeat the same operation at each boot).
22387        // We only have to cover the upgrade and first boot here because for app installs we
22388        // prepare the profiles before invoking dexopt (in installPackageLI).
22389        //
22390        // We also have to cover non system users because we do not call the usual install package
22391        // methods for them.
22392        if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
22393            mArtManagerService.prepareAppProfiles(pkg, userId);
22394        }
22395
22396        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
22397            // TODO: mark this structure as dirty so we persist it!
22398            synchronized (mPackages) {
22399                final PackageSetting ps = mSettings.mPackages.get(packageName);
22400                if (ps != null) {
22401                    ps.setCeDataInode(ceDataInode, userId);
22402                }
22403            }
22404        }
22405
22406        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22407    }
22408
22409    private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
22410        if (pkg == null) {
22411            Slog.wtf(TAG, "Package was null!", new Throwable());
22412            return;
22413        }
22414        prepareAppDataContentsLeafLIF(pkg, userId, flags);
22415        final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22416        for (int i = 0; i < childCount; i++) {
22417            prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
22418        }
22419    }
22420
22421    private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22422        final String volumeUuid = pkg.volumeUuid;
22423        final String packageName = pkg.packageName;
22424        final ApplicationInfo app = pkg.applicationInfo;
22425
22426        if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22427            // Create a native library symlink only if we have native libraries
22428            // and if the native libraries are 32 bit libraries. We do not provide
22429            // this symlink for 64 bit libraries.
22430            if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
22431                final String nativeLibPath = app.nativeLibraryDir;
22432                try {
22433                    mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
22434                            nativeLibPath, userId);
22435                } catch (InstallerException e) {
22436                    Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
22437                }
22438            }
22439        }
22440    }
22441
22442    /**
22443     * For system apps on non-FBE devices, this method migrates any existing
22444     * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
22445     * requested by the app.
22446     */
22447    private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
22448        if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
22449                && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
22450            final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
22451                    ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
22452            try {
22453                mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
22454                        storageTarget);
22455            } catch (InstallerException e) {
22456                logCriticalInfo(Log.WARN,
22457                        "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
22458            }
22459            return true;
22460        } else {
22461            return false;
22462        }
22463    }
22464
22465    public PackageFreezer freezePackage(String packageName, String killReason) {
22466        return freezePackage(packageName, UserHandle.USER_ALL, killReason);
22467    }
22468
22469    public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
22470        return new PackageFreezer(packageName, userId, killReason);
22471    }
22472
22473    public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
22474            String killReason) {
22475        return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
22476    }
22477
22478    public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
22479            String killReason) {
22480        if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
22481            return new PackageFreezer();
22482        } else {
22483            return freezePackage(packageName, userId, killReason);
22484        }
22485    }
22486
22487    public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
22488            String killReason) {
22489        return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
22490    }
22491
22492    public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
22493            String killReason) {
22494        if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
22495            return new PackageFreezer();
22496        } else {
22497            return freezePackage(packageName, userId, killReason);
22498        }
22499    }
22500
22501    /**
22502     * Class that freezes and kills the given package upon creation, and
22503     * unfreezes it upon closing. This is typically used when doing surgery on
22504     * app code/data to prevent the app from running while you're working.
22505     */
22506    private class PackageFreezer implements AutoCloseable {
22507        private final String mPackageName;
22508        private final PackageFreezer[] mChildren;
22509
22510        private final boolean mWeFroze;
22511
22512        private final AtomicBoolean mClosed = new AtomicBoolean();
22513        private final CloseGuard mCloseGuard = CloseGuard.get();
22514
22515        /**
22516         * Create and return a stub freezer that doesn't actually do anything,
22517         * typically used when someone requested
22518         * {@link PackageManager#INSTALL_DONT_KILL_APP} or
22519         * {@link PackageManager#DELETE_DONT_KILL_APP}.
22520         */
22521        public PackageFreezer() {
22522            mPackageName = null;
22523            mChildren = null;
22524            mWeFroze = false;
22525            mCloseGuard.open("close");
22526        }
22527
22528        public PackageFreezer(String packageName, int userId, String killReason) {
22529            synchronized (mPackages) {
22530                mPackageName = packageName;
22531                mWeFroze = mFrozenPackages.add(mPackageName);
22532
22533                final PackageSetting ps = mSettings.mPackages.get(mPackageName);
22534                if (ps != null) {
22535                    killApplication(ps.name, ps.appId, userId, killReason);
22536                }
22537
22538                final PackageParser.Package p = mPackages.get(packageName);
22539                if (p != null && p.childPackages != null) {
22540                    final int N = p.childPackages.size();
22541                    mChildren = new PackageFreezer[N];
22542                    for (int i = 0; i < N; i++) {
22543                        mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
22544                                userId, killReason);
22545                    }
22546                } else {
22547                    mChildren = null;
22548                }
22549            }
22550            mCloseGuard.open("close");
22551        }
22552
22553        @Override
22554        protected void finalize() throws Throwable {
22555            try {
22556                if (mCloseGuard != null) {
22557                    mCloseGuard.warnIfOpen();
22558                }
22559
22560                close();
22561            } finally {
22562                super.finalize();
22563            }
22564        }
22565
22566        @Override
22567        public void close() {
22568            mCloseGuard.close();
22569            if (mClosed.compareAndSet(false, true)) {
22570                synchronized (mPackages) {
22571                    if (mWeFroze) {
22572                        mFrozenPackages.remove(mPackageName);
22573                    }
22574
22575                    if (mChildren != null) {
22576                        for (PackageFreezer freezer : mChildren) {
22577                            freezer.close();
22578                        }
22579                    }
22580                }
22581            }
22582        }
22583    }
22584
22585    /**
22586     * Verify that given package is currently frozen.
22587     */
22588    private void checkPackageFrozen(String packageName) {
22589        synchronized (mPackages) {
22590            if (!mFrozenPackages.contains(packageName)) {
22591                Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
22592            }
22593        }
22594    }
22595
22596    @Override
22597    public int movePackage(final String packageName, final String volumeUuid) {
22598        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22599
22600        final int callingUid = Binder.getCallingUid();
22601        final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
22602        final int moveId = mNextMoveId.getAndIncrement();
22603        mHandler.post(new Runnable() {
22604            @Override
22605            public void run() {
22606                try {
22607                    movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
22608                } catch (PackageManagerException e) {
22609                    Slog.w(TAG, "Failed to move " + packageName, e);
22610                    mMoveCallbacks.notifyStatusChanged(moveId, e.error);
22611                }
22612            }
22613        });
22614        return moveId;
22615    }
22616
22617    private void movePackageInternal(final String packageName, final String volumeUuid,
22618            final int moveId, final int callingUid, UserHandle user)
22619                    throws PackageManagerException {
22620        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22621        final PackageManager pm = mContext.getPackageManager();
22622
22623        final boolean currentAsec;
22624        final String currentVolumeUuid;
22625        final File codeFile;
22626        final String installerPackageName;
22627        final String packageAbiOverride;
22628        final int appId;
22629        final String seinfo;
22630        final String label;
22631        final int targetSdkVersion;
22632        final PackageFreezer freezer;
22633        final int[] installedUserIds;
22634
22635        // reader
22636        synchronized (mPackages) {
22637            final PackageParser.Package pkg = mPackages.get(packageName);
22638            final PackageSetting ps = mSettings.mPackages.get(packageName);
22639            if (pkg == null
22640                    || ps == null
22641                    || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
22642                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
22643            }
22644            if (pkg.applicationInfo.isSystemApp()) {
22645                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
22646                        "Cannot move system application");
22647            }
22648
22649            final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
22650            final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
22651                    com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
22652            if (isInternalStorage && !allow3rdPartyOnInternal) {
22653                throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
22654                        "3rd party apps are not allowed on internal storage");
22655            }
22656
22657            if (pkg.applicationInfo.isExternalAsec()) {
22658                currentAsec = true;
22659                currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
22660            } else if (pkg.applicationInfo.isForwardLocked()) {
22661                currentAsec = true;
22662                currentVolumeUuid = "forward_locked";
22663            } else {
22664                currentAsec = false;
22665                currentVolumeUuid = ps.volumeUuid;
22666
22667                final File probe = new File(pkg.codePath);
22668                final File probeOat = new File(probe, "oat");
22669                if (!probe.isDirectory() || !probeOat.isDirectory()) {
22670                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22671                            "Move only supported for modern cluster style installs");
22672                }
22673            }
22674
22675            if (Objects.equals(currentVolumeUuid, volumeUuid)) {
22676                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22677                        "Package already moved to " + volumeUuid);
22678            }
22679            if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
22680                throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
22681                        "Device admin cannot be moved");
22682            }
22683
22684            if (mFrozenPackages.contains(packageName)) {
22685                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
22686                        "Failed to move already frozen package");
22687            }
22688
22689            codeFile = new File(pkg.codePath);
22690            installerPackageName = ps.installerPackageName;
22691            packageAbiOverride = ps.cpuAbiOverrideString;
22692            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
22693            seinfo = pkg.applicationInfo.seInfo;
22694            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
22695            targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
22696            freezer = freezePackage(packageName, "movePackageInternal");
22697            installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
22698        }
22699
22700        final Bundle extras = new Bundle();
22701        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
22702        extras.putString(Intent.EXTRA_TITLE, label);
22703        mMoveCallbacks.notifyCreated(moveId, extras);
22704
22705        int installFlags;
22706        final boolean moveCompleteApp;
22707        final File measurePath;
22708
22709        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
22710            installFlags = INSTALL_INTERNAL;
22711            moveCompleteApp = !currentAsec;
22712            measurePath = Environment.getDataAppDirectory(volumeUuid);
22713        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
22714            installFlags = INSTALL_EXTERNAL;
22715            moveCompleteApp = false;
22716            measurePath = storage.getPrimaryPhysicalVolume().getPath();
22717        } else {
22718            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
22719            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
22720                    || !volume.isMountedWritable()) {
22721                freezer.close();
22722                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22723                        "Move location not mounted private volume");
22724            }
22725
22726            Preconditions.checkState(!currentAsec);
22727
22728            installFlags = INSTALL_INTERNAL;
22729            moveCompleteApp = true;
22730            measurePath = Environment.getDataAppDirectory(volumeUuid);
22731        }
22732
22733        // If we're moving app data around, we need all the users unlocked
22734        if (moveCompleteApp) {
22735            for (int userId : installedUserIds) {
22736                if (StorageManager.isFileEncryptedNativeOrEmulated()
22737                        && !StorageManager.isUserKeyUnlocked(userId)) {
22738                    throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
22739                            "User " + userId + " must be unlocked");
22740                }
22741            }
22742        }
22743
22744        final PackageStats stats = new PackageStats(null, -1);
22745        synchronized (mInstaller) {
22746            for (int userId : installedUserIds) {
22747                if (!getPackageSizeInfoLI(packageName, userId, stats)) {
22748                    freezer.close();
22749                    throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22750                            "Failed to measure package size");
22751                }
22752            }
22753        }
22754
22755        if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
22756                + stats.dataSize);
22757
22758        final long startFreeBytes = measurePath.getUsableSpace();
22759        final long sizeBytes;
22760        if (moveCompleteApp) {
22761            sizeBytes = stats.codeSize + stats.dataSize;
22762        } else {
22763            sizeBytes = stats.codeSize;
22764        }
22765
22766        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
22767            freezer.close();
22768            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
22769                    "Not enough free space to move");
22770        }
22771
22772        mMoveCallbacks.notifyStatusChanged(moveId, 10);
22773
22774        final CountDownLatch installedLatch = new CountDownLatch(1);
22775        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
22776            @Override
22777            public void onUserActionRequired(Intent intent) throws RemoteException {
22778                throw new IllegalStateException();
22779            }
22780
22781            @Override
22782            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
22783                    Bundle extras) throws RemoteException {
22784                if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
22785                        + PackageManager.installStatusToString(returnCode, msg));
22786
22787                installedLatch.countDown();
22788                freezer.close();
22789
22790                final int status = PackageManager.installStatusToPublicStatus(returnCode);
22791                switch (status) {
22792                    case PackageInstaller.STATUS_SUCCESS:
22793                        mMoveCallbacks.notifyStatusChanged(moveId,
22794                                PackageManager.MOVE_SUCCEEDED);
22795                        break;
22796                    case PackageInstaller.STATUS_FAILURE_STORAGE:
22797                        mMoveCallbacks.notifyStatusChanged(moveId,
22798                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
22799                        break;
22800                    default:
22801                        mMoveCallbacks.notifyStatusChanged(moveId,
22802                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
22803                        break;
22804                }
22805            }
22806        };
22807
22808        final MoveInfo move;
22809        if (moveCompleteApp) {
22810            // Kick off a thread to report progress estimates
22811            new Thread() {
22812                @Override
22813                public void run() {
22814                    while (true) {
22815                        try {
22816                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
22817                                break;
22818                            }
22819                        } catch (InterruptedException ignored) {
22820                        }
22821
22822                        final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
22823                        final int progress = 10 + (int) MathUtils.constrain(
22824                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
22825                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
22826                    }
22827                }
22828            }.start();
22829
22830            final String dataAppName = codeFile.getName();
22831            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
22832                    dataAppName, appId, seinfo, targetSdkVersion);
22833        } else {
22834            move = null;
22835        }
22836
22837        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
22838
22839        final Message msg = mHandler.obtainMessage(INIT_COPY);
22840        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
22841        final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
22842                installerPackageName, volumeUuid, null /*verificationInfo*/, user,
22843                packageAbiOverride, null /*grantedPermissions*/,
22844                PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN);
22845        params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
22846        msg.obj = params;
22847
22848        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
22849                System.identityHashCode(msg.obj));
22850        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
22851                System.identityHashCode(msg.obj));
22852
22853        mHandler.sendMessage(msg);
22854    }
22855
22856    @Override
22857    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
22858        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
22859
22860        final int realMoveId = mNextMoveId.getAndIncrement();
22861        final Bundle extras = new Bundle();
22862        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
22863        mMoveCallbacks.notifyCreated(realMoveId, extras);
22864
22865        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
22866            @Override
22867            public void onCreated(int moveId, Bundle extras) {
22868                // Ignored
22869            }
22870
22871            @Override
22872            public void onStatusChanged(int moveId, int status, long estMillis) {
22873                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
22874            }
22875        };
22876
22877        final StorageManager storage = mContext.getSystemService(StorageManager.class);
22878        storage.setPrimaryStorageUuid(volumeUuid, callback);
22879        return realMoveId;
22880    }
22881
22882    @Override
22883    public int getMoveStatus(int moveId) {
22884        mContext.enforceCallingOrSelfPermission(
22885                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22886        return mMoveCallbacks.mLastStatus.get(moveId);
22887    }
22888
22889    @Override
22890    public void registerMoveCallback(IPackageMoveObserver callback) {
22891        mContext.enforceCallingOrSelfPermission(
22892                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22893        mMoveCallbacks.register(callback);
22894    }
22895
22896    @Override
22897    public void unregisterMoveCallback(IPackageMoveObserver callback) {
22898        mContext.enforceCallingOrSelfPermission(
22899                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
22900        mMoveCallbacks.unregister(callback);
22901    }
22902
22903    @Override
22904    public boolean setInstallLocation(int loc) {
22905        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
22906                null);
22907        if (getInstallLocation() == loc) {
22908            return true;
22909        }
22910        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
22911                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
22912            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
22913                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
22914            return true;
22915        }
22916        return false;
22917   }
22918
22919    @Override
22920    public int getInstallLocation() {
22921        // allow instant app access
22922        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
22923                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
22924                PackageHelper.APP_INSTALL_AUTO);
22925    }
22926
22927    /** Called by UserManagerService */
22928    void cleanUpUser(UserManagerService userManager, int userHandle) {
22929        synchronized (mPackages) {
22930            mDirtyUsers.remove(userHandle);
22931            mUserNeedsBadging.delete(userHandle);
22932            mSettings.removeUserLPw(userHandle);
22933            mPendingBroadcasts.remove(userHandle);
22934            mInstantAppRegistry.onUserRemovedLPw(userHandle);
22935            removeUnusedPackagesLPw(userManager, userHandle);
22936        }
22937    }
22938
22939    /**
22940     * We're removing userHandle and would like to remove any downloaded packages
22941     * that are no longer in use by any other user.
22942     * @param userHandle the user being removed
22943     */
22944    private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
22945        final boolean DEBUG_CLEAN_APKS = false;
22946        int [] users = userManager.getUserIds();
22947        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
22948        while (psit.hasNext()) {
22949            PackageSetting ps = psit.next();
22950            if (ps.pkg == null) {
22951                continue;
22952            }
22953            final String packageName = ps.pkg.packageName;
22954            // Skip over if system app
22955            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
22956                continue;
22957            }
22958            if (DEBUG_CLEAN_APKS) {
22959                Slog.i(TAG, "Checking package " + packageName);
22960            }
22961            boolean keep = shouldKeepUninstalledPackageLPr(packageName);
22962            if (keep) {
22963                if (DEBUG_CLEAN_APKS) {
22964                    Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
22965                }
22966            } else {
22967                for (int i = 0; i < users.length; i++) {
22968                    if (users[i] != userHandle && ps.getInstalled(users[i])) {
22969                        keep = true;
22970                        if (DEBUG_CLEAN_APKS) {
22971                            Slog.i(TAG, "  Keeping package " + packageName + " for user "
22972                                    + users[i]);
22973                        }
22974                        break;
22975                    }
22976                }
22977            }
22978            if (!keep) {
22979                if (DEBUG_CLEAN_APKS) {
22980                    Slog.i(TAG, "  Removing package " + packageName);
22981                }
22982                mHandler.post(new Runnable() {
22983                    public void run() {
22984                        deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
22985                                userHandle, 0);
22986                    } //end run
22987                });
22988            }
22989        }
22990    }
22991
22992    /** Called by UserManagerService */
22993    void createNewUser(int userId, String[] disallowedPackages) {
22994        synchronized (mInstallLock) {
22995            mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
22996        }
22997        synchronized (mPackages) {
22998            scheduleWritePackageRestrictionsLocked(userId);
22999            scheduleWritePackageListLocked(userId);
23000            applyFactoryDefaultBrowserLPw(userId);
23001            primeDomainVerificationsLPw(userId);
23002        }
23003    }
23004
23005    void onNewUserCreated(final int userId) {
23006        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23007        synchronized(mPackages) {
23008            // If permission review for legacy apps is required, we represent
23009            // dagerous permissions for such apps as always granted runtime
23010            // permissions to keep per user flag state whether review is needed.
23011            // Hence, if a new user is added we have to propagate dangerous
23012            // permission grants for these legacy apps.
23013            if (mSettings.mPermissions.mPermissionReviewRequired) {
23014// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23015                mPermissionManager.updateAllPermissions(
23016                        StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23017                        mPermissionCallback);
23018            }
23019        }
23020    }
23021
23022    @Override
23023    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23024        mContext.enforceCallingOrSelfPermission(
23025                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23026                "Only package verification agents can read the verifier device identity");
23027
23028        synchronized (mPackages) {
23029            return mSettings.getVerifierDeviceIdentityLPw();
23030        }
23031    }
23032
23033    @Override
23034    public void setPermissionEnforced(String permission, boolean enforced) {
23035        // TODO: Now that we no longer change GID for storage, this should to away.
23036        mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23037                "setPermissionEnforced");
23038        if (READ_EXTERNAL_STORAGE.equals(permission)) {
23039            synchronized (mPackages) {
23040                if (mSettings.mReadExternalStorageEnforced == null
23041                        || mSettings.mReadExternalStorageEnforced != enforced) {
23042                    mSettings.mReadExternalStorageEnforced =
23043                            enforced ? Boolean.TRUE : Boolean.FALSE;
23044                    mSettings.writeLPr();
23045                }
23046            }
23047            // kill any non-foreground processes so we restart them and
23048            // grant/revoke the GID.
23049            final IActivityManager am = ActivityManager.getService();
23050            if (am != null) {
23051                final long token = Binder.clearCallingIdentity();
23052                try {
23053                    am.killProcessesBelowForeground("setPermissionEnforcement");
23054                } catch (RemoteException e) {
23055                } finally {
23056                    Binder.restoreCallingIdentity(token);
23057                }
23058            }
23059        } else {
23060            throw new IllegalArgumentException("No selective enforcement for " + permission);
23061        }
23062    }
23063
23064    @Override
23065    @Deprecated
23066    public boolean isPermissionEnforced(String permission) {
23067        // allow instant applications
23068        return true;
23069    }
23070
23071    @Override
23072    public boolean isStorageLow() {
23073        // allow instant applications
23074        final long token = Binder.clearCallingIdentity();
23075        try {
23076            final DeviceStorageMonitorInternal
23077                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23078            if (dsm != null) {
23079                return dsm.isMemoryLow();
23080            } else {
23081                return false;
23082            }
23083        } finally {
23084            Binder.restoreCallingIdentity(token);
23085        }
23086    }
23087
23088    @Override
23089    public IPackageInstaller getPackageInstaller() {
23090        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23091            return null;
23092        }
23093        return mInstallerService;
23094    }
23095
23096    @Override
23097    public IArtManager getArtManager() {
23098        return mArtManagerService;
23099    }
23100
23101    private boolean userNeedsBadging(int userId) {
23102        int index = mUserNeedsBadging.indexOfKey(userId);
23103        if (index < 0) {
23104            final UserInfo userInfo;
23105            final long token = Binder.clearCallingIdentity();
23106            try {
23107                userInfo = sUserManager.getUserInfo(userId);
23108            } finally {
23109                Binder.restoreCallingIdentity(token);
23110            }
23111            final boolean b;
23112            if (userInfo != null && userInfo.isManagedProfile()) {
23113                b = true;
23114            } else {
23115                b = false;
23116            }
23117            mUserNeedsBadging.put(userId, b);
23118            return b;
23119        }
23120        return mUserNeedsBadging.valueAt(index);
23121    }
23122
23123    @Override
23124    public KeySet getKeySetByAlias(String packageName, String alias) {
23125        if (packageName == null || alias == null) {
23126            return null;
23127        }
23128        synchronized(mPackages) {
23129            final PackageParser.Package pkg = mPackages.get(packageName);
23130            if (pkg == null) {
23131                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23132                throw new IllegalArgumentException("Unknown package: " + packageName);
23133            }
23134            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23135            if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23136                Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23137                throw new IllegalArgumentException("Unknown package: " + packageName);
23138            }
23139            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23140            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23141        }
23142    }
23143
23144    @Override
23145    public KeySet getSigningKeySet(String packageName) {
23146        if (packageName == null) {
23147            return null;
23148        }
23149        synchronized(mPackages) {
23150            final int callingUid = Binder.getCallingUid();
23151            final int callingUserId = UserHandle.getUserId(callingUid);
23152            final PackageParser.Package pkg = mPackages.get(packageName);
23153            if (pkg == null) {
23154                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23155                throw new IllegalArgumentException("Unknown package: " + packageName);
23156            }
23157            final PackageSetting ps = (PackageSetting) pkg.mExtras;
23158            if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23159                // filter and pretend the package doesn't exist
23160                Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23161                        + ", uid:" + callingUid);
23162                throw new IllegalArgumentException("Unknown package: " + packageName);
23163            }
23164            if (pkg.applicationInfo.uid != callingUid
23165                    && Process.SYSTEM_UID != callingUid) {
23166                throw new SecurityException("May not access signing KeySet of other apps.");
23167            }
23168            final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23169            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23170        }
23171    }
23172
23173    @Override
23174    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23175        final int callingUid = Binder.getCallingUid();
23176        if (getInstantAppPackageName(callingUid) != null) {
23177            return false;
23178        }
23179        if (packageName == null || ks == null) {
23180            return false;
23181        }
23182        synchronized(mPackages) {
23183            final PackageParser.Package pkg = mPackages.get(packageName);
23184            if (pkg == null
23185                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23186                            UserHandle.getUserId(callingUid))) {
23187                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23188                throw new IllegalArgumentException("Unknown package: " + packageName);
23189            }
23190            IBinder ksh = ks.getToken();
23191            if (ksh instanceof KeySetHandle) {
23192                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23193                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23194            }
23195            return false;
23196        }
23197    }
23198
23199    @Override
23200    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23201        final int callingUid = Binder.getCallingUid();
23202        if (getInstantAppPackageName(callingUid) != null) {
23203            return false;
23204        }
23205        if (packageName == null || ks == null) {
23206            return false;
23207        }
23208        synchronized(mPackages) {
23209            final PackageParser.Package pkg = mPackages.get(packageName);
23210            if (pkg == null
23211                    || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23212                            UserHandle.getUserId(callingUid))) {
23213                Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23214                throw new IllegalArgumentException("Unknown package: " + packageName);
23215            }
23216            IBinder ksh = ks.getToken();
23217            if (ksh instanceof KeySetHandle) {
23218                final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23219                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23220            }
23221            return false;
23222        }
23223    }
23224
23225    private void deletePackageIfUnusedLPr(final String packageName) {
23226        PackageSetting ps = mSettings.mPackages.get(packageName);
23227        if (ps == null) {
23228            return;
23229        }
23230        if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23231            // TODO Implement atomic delete if package is unused
23232            // It is currently possible that the package will be deleted even if it is installed
23233            // after this method returns.
23234            mHandler.post(new Runnable() {
23235                public void run() {
23236                    deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23237                            0, PackageManager.DELETE_ALL_USERS);
23238                }
23239            });
23240        }
23241    }
23242
23243    /**
23244     * Check and throw if the given before/after packages would be considered a
23245     * downgrade.
23246     */
23247    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23248            throws PackageManagerException {
23249        if (after.getLongVersionCode() < before.getLongVersionCode()) {
23250            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23251                    "Update version code " + after.versionCode + " is older than current "
23252                    + before.getLongVersionCode());
23253        } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23254            if (after.baseRevisionCode < before.baseRevisionCode) {
23255                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23256                        "Update base revision code " + after.baseRevisionCode
23257                        + " is older than current " + before.baseRevisionCode);
23258            }
23259
23260            if (!ArrayUtils.isEmpty(after.splitNames)) {
23261                for (int i = 0; i < after.splitNames.length; i++) {
23262                    final String splitName = after.splitNames[i];
23263                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23264                    if (j != -1) {
23265                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23266                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23267                                    "Update split " + splitName + " revision code "
23268                                    + after.splitRevisionCodes[i] + " is older than current "
23269                                    + before.splitRevisionCodes[j]);
23270                        }
23271                    }
23272                }
23273            }
23274        }
23275    }
23276
23277    private static class MoveCallbacks extends Handler {
23278        private static final int MSG_CREATED = 1;
23279        private static final int MSG_STATUS_CHANGED = 2;
23280
23281        private final RemoteCallbackList<IPackageMoveObserver>
23282                mCallbacks = new RemoteCallbackList<>();
23283
23284        private final SparseIntArray mLastStatus = new SparseIntArray();
23285
23286        public MoveCallbacks(Looper looper) {
23287            super(looper);
23288        }
23289
23290        public void register(IPackageMoveObserver callback) {
23291            mCallbacks.register(callback);
23292        }
23293
23294        public void unregister(IPackageMoveObserver callback) {
23295            mCallbacks.unregister(callback);
23296        }
23297
23298        @Override
23299        public void handleMessage(Message msg) {
23300            final SomeArgs args = (SomeArgs) msg.obj;
23301            final int n = mCallbacks.beginBroadcast();
23302            for (int i = 0; i < n; i++) {
23303                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23304                try {
23305                    invokeCallback(callback, msg.what, args);
23306                } catch (RemoteException ignored) {
23307                }
23308            }
23309            mCallbacks.finishBroadcast();
23310            args.recycle();
23311        }
23312
23313        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23314                throws RemoteException {
23315            switch (what) {
23316                case MSG_CREATED: {
23317                    callback.onCreated(args.argi1, (Bundle) args.arg2);
23318                    break;
23319                }
23320                case MSG_STATUS_CHANGED: {
23321                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23322                    break;
23323                }
23324            }
23325        }
23326
23327        private void notifyCreated(int moveId, Bundle extras) {
23328            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23329
23330            final SomeArgs args = SomeArgs.obtain();
23331            args.argi1 = moveId;
23332            args.arg2 = extras;
23333            obtainMessage(MSG_CREATED, args).sendToTarget();
23334        }
23335
23336        private void notifyStatusChanged(int moveId, int status) {
23337            notifyStatusChanged(moveId, status, -1);
23338        }
23339
23340        private void notifyStatusChanged(int moveId, int status, long estMillis) {
23341            Slog.v(TAG, "Move " + moveId + " status " + status);
23342
23343            final SomeArgs args = SomeArgs.obtain();
23344            args.argi1 = moveId;
23345            args.argi2 = status;
23346            args.arg3 = estMillis;
23347            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
23348
23349            synchronized (mLastStatus) {
23350                mLastStatus.put(moveId, status);
23351            }
23352        }
23353    }
23354
23355    private final static class OnPermissionChangeListeners extends Handler {
23356        private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
23357
23358        private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
23359                new RemoteCallbackList<>();
23360
23361        public OnPermissionChangeListeners(Looper looper) {
23362            super(looper);
23363        }
23364
23365        @Override
23366        public void handleMessage(Message msg) {
23367            switch (msg.what) {
23368                case MSG_ON_PERMISSIONS_CHANGED: {
23369                    final int uid = msg.arg1;
23370                    handleOnPermissionsChanged(uid);
23371                } break;
23372            }
23373        }
23374
23375        public void addListenerLocked(IOnPermissionsChangeListener listener) {
23376            mPermissionListeners.register(listener);
23377
23378        }
23379
23380        public void removeListenerLocked(IOnPermissionsChangeListener listener) {
23381            mPermissionListeners.unregister(listener);
23382        }
23383
23384        public void onPermissionsChanged(int uid) {
23385            if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
23386                obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
23387            }
23388        }
23389
23390        private void handleOnPermissionsChanged(int uid) {
23391            final int count = mPermissionListeners.beginBroadcast();
23392            try {
23393                for (int i = 0; i < count; i++) {
23394                    IOnPermissionsChangeListener callback = mPermissionListeners
23395                            .getBroadcastItem(i);
23396                    try {
23397                        callback.onPermissionsChanged(uid);
23398                    } catch (RemoteException e) {
23399                        Log.e(TAG, "Permission listener is dead", e);
23400                    }
23401                }
23402            } finally {
23403                mPermissionListeners.finishBroadcast();
23404            }
23405        }
23406    }
23407
23408    private class PackageManagerNative extends IPackageManagerNative.Stub {
23409        @Override
23410        public String[] getNamesForUids(int[] uids) throws RemoteException {
23411            final String[] results = PackageManagerService.this.getNamesForUids(uids);
23412            // massage results so they can be parsed by the native binder
23413            for (int i = results.length - 1; i >= 0; --i) {
23414                if (results[i] == null) {
23415                    results[i] = "";
23416                }
23417            }
23418            return results;
23419        }
23420
23421        // NB: this differentiates between preloads and sideloads
23422        @Override
23423        public String getInstallerForPackage(String packageName) throws RemoteException {
23424            final String installerName = getInstallerPackageName(packageName);
23425            if (!TextUtils.isEmpty(installerName)) {
23426                return installerName;
23427            }
23428            // differentiate between preload and sideload
23429            int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23430            ApplicationInfo appInfo = getApplicationInfo(packageName,
23431                                    /*flags*/ 0,
23432                                    /*userId*/ callingUser);
23433            if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23434                return "preload";
23435            }
23436            return "";
23437        }
23438
23439        @Override
23440        public long getVersionCodeForPackage(String packageName) throws RemoteException {
23441            try {
23442                int callingUser = UserHandle.getUserId(Binder.getCallingUid());
23443                PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
23444                if (pInfo != null) {
23445                    return pInfo.getLongVersionCode();
23446                }
23447            } catch (Exception e) {
23448            }
23449            return 0;
23450        }
23451    }
23452
23453    private class PackageManagerInternalImpl extends PackageManagerInternal {
23454        @Override
23455        public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
23456                int flagValues, int userId) {
23457            PackageManagerService.this.updatePermissionFlags(
23458                    permName, packageName, flagMask, flagValues, userId);
23459        }
23460
23461        @Override
23462        public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
23463            return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
23464        }
23465
23466        @Override
23467        public boolean isInstantApp(String packageName, int userId) {
23468            return PackageManagerService.this.isInstantApp(packageName, userId);
23469        }
23470
23471        @Override
23472        public String getInstantAppPackageName(int uid) {
23473            return PackageManagerService.this.getInstantAppPackageName(uid);
23474        }
23475
23476        @Override
23477        public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
23478            synchronized (mPackages) {
23479                return PackageManagerService.this.filterAppAccessLPr(
23480                        (PackageSetting) pkg.mExtras, callingUid, userId);
23481            }
23482        }
23483
23484        @Override
23485        public PackageParser.Package getPackage(String packageName) {
23486            synchronized (mPackages) {
23487                packageName = resolveInternalPackageNameLPr(
23488                        packageName, PackageManager.VERSION_CODE_HIGHEST);
23489                return mPackages.get(packageName);
23490            }
23491        }
23492
23493        @Override
23494        public PackageList getPackageList(PackageListObserver observer) {
23495            synchronized (mPackages) {
23496                final int N = mPackages.size();
23497                final ArrayList<String> list = new ArrayList<>(N);
23498                for (int i = 0; i < N; i++) {
23499                    list.add(mPackages.keyAt(i));
23500                }
23501                final PackageList packageList = new PackageList(list, observer);
23502                if (observer != null) {
23503                    mPackageListObservers.add(packageList);
23504                }
23505                return packageList;
23506            }
23507        }
23508
23509        @Override
23510        public void removePackageListObserver(PackageListObserver observer) {
23511            synchronized (mPackages) {
23512                mPackageListObservers.remove(observer);
23513            }
23514        }
23515
23516        @Override
23517        public PackageParser.Package getDisabledPackage(String packageName) {
23518            synchronized (mPackages) {
23519                final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
23520                return (ps != null) ? ps.pkg : null;
23521            }
23522        }
23523
23524        @Override
23525        public String getKnownPackageName(int knownPackage, int userId) {
23526            switch(knownPackage) {
23527                case PackageManagerInternal.PACKAGE_BROWSER:
23528                    return getDefaultBrowserPackageName(userId);
23529                case PackageManagerInternal.PACKAGE_INSTALLER:
23530                    return mRequiredInstallerPackage;
23531                case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
23532                    return mSetupWizardPackage;
23533                case PackageManagerInternal.PACKAGE_SYSTEM:
23534                    return "android";
23535                case PackageManagerInternal.PACKAGE_VERIFIER:
23536                    return mRequiredVerifierPackage;
23537                case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
23538                    return mSystemTextClassifierPackage;
23539            }
23540            return null;
23541        }
23542
23543        @Override
23544        public boolean isResolveActivityComponent(ComponentInfo component) {
23545            return mResolveActivity.packageName.equals(component.packageName)
23546                    && mResolveActivity.name.equals(component.name);
23547        }
23548
23549        @Override
23550        public void setLocationPackagesProvider(PackagesProvider provider) {
23551            mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
23552        }
23553
23554        @Override
23555        public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
23556            mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
23557        }
23558
23559        @Override
23560        public void setSmsAppPackagesProvider(PackagesProvider provider) {
23561            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
23562        }
23563
23564        @Override
23565        public void setDialerAppPackagesProvider(PackagesProvider provider) {
23566            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
23567        }
23568
23569        @Override
23570        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
23571            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
23572        }
23573
23574        @Override
23575        public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
23576            mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
23577        }
23578
23579        @Override
23580        public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
23581            mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
23582        }
23583
23584        @Override
23585        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
23586            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
23587        }
23588
23589        @Override
23590        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
23591            synchronized (mPackages) {
23592                mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
23593            }
23594            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
23595        }
23596
23597        @Override
23598        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
23599            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
23600                    packageName, userId);
23601        }
23602
23603        @Override
23604        public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
23605            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
23606                    packageName, userId);
23607        }
23608
23609        @Override
23610        public void setKeepUninstalledPackages(final List<String> packageList) {
23611            Preconditions.checkNotNull(packageList);
23612            List<String> removedFromList = null;
23613            synchronized (mPackages) {
23614                if (mKeepUninstalledPackages != null) {
23615                    final int packagesCount = mKeepUninstalledPackages.size();
23616                    for (int i = 0; i < packagesCount; i++) {
23617                        String oldPackage = mKeepUninstalledPackages.get(i);
23618                        if (packageList != null && packageList.contains(oldPackage)) {
23619                            continue;
23620                        }
23621                        if (removedFromList == null) {
23622                            removedFromList = new ArrayList<>();
23623                        }
23624                        removedFromList.add(oldPackage);
23625                    }
23626                }
23627                mKeepUninstalledPackages = new ArrayList<>(packageList);
23628                if (removedFromList != null) {
23629                    final int removedCount = removedFromList.size();
23630                    for (int i = 0; i < removedCount; i++) {
23631                        deletePackageIfUnusedLPr(removedFromList.get(i));
23632                    }
23633                }
23634            }
23635        }
23636
23637        @Override
23638        public boolean isPermissionsReviewRequired(String packageName, int userId) {
23639            synchronized (mPackages) {
23640                return mPermissionManager.isPermissionsReviewRequired(
23641                        mPackages.get(packageName), userId);
23642            }
23643        }
23644
23645        @Override
23646        public PackageInfo getPackageInfo(
23647                String packageName, int flags, int filterCallingUid, int userId) {
23648            return PackageManagerService.this
23649                    .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
23650                            flags, filterCallingUid, userId);
23651        }
23652
23653        @Override
23654        public int getPackageUid(String packageName, int flags, int userId) {
23655            return PackageManagerService.this
23656                    .getPackageUid(packageName, flags, userId);
23657        }
23658
23659        @Override
23660        public ApplicationInfo getApplicationInfo(
23661                String packageName, int flags, int filterCallingUid, int userId) {
23662            return PackageManagerService.this
23663                    .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
23664        }
23665
23666        @Override
23667        public ActivityInfo getActivityInfo(
23668                ComponentName component, int flags, int filterCallingUid, int userId) {
23669            return PackageManagerService.this
23670                    .getActivityInfoInternal(component, flags, filterCallingUid, userId);
23671        }
23672
23673        @Override
23674        public List<ResolveInfo> queryIntentActivities(
23675                Intent intent, int flags, int filterCallingUid, int userId) {
23676            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23677            return PackageManagerService.this
23678                    .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
23679                            userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
23680        }
23681
23682        @Override
23683        public List<ResolveInfo> queryIntentServices(
23684                Intent intent, int flags, int callingUid, int userId) {
23685            final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
23686            return PackageManagerService.this
23687                    .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
23688                            false);
23689        }
23690
23691        @Override
23692        public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
23693                int userId) {
23694            return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
23695        }
23696
23697        @Override
23698        public ComponentName getDefaultHomeActivity(int userId) {
23699            return PackageManagerService.this.getDefaultHomeActivity(userId);
23700        }
23701
23702        @Override
23703        public void setDeviceAndProfileOwnerPackages(
23704                int deviceOwnerUserId, String deviceOwnerPackage,
23705                SparseArray<String> profileOwnerPackages) {
23706            mProtectedPackages.setDeviceAndProfileOwnerPackages(
23707                    deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
23708        }
23709
23710        @Override
23711        public boolean isPackageDataProtected(int userId, String packageName) {
23712            return mProtectedPackages.isPackageDataProtected(userId, packageName);
23713        }
23714
23715        @Override
23716        public boolean isPackageEphemeral(int userId, String packageName) {
23717            synchronized (mPackages) {
23718                final PackageSetting ps = mSettings.mPackages.get(packageName);
23719                return ps != null ? ps.getInstantApp(userId) : false;
23720            }
23721        }
23722
23723        @Override
23724        public boolean wasPackageEverLaunched(String packageName, int userId) {
23725            synchronized (mPackages) {
23726                return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
23727            }
23728        }
23729
23730        @Override
23731        public void grantRuntimePermission(String packageName, String permName, int userId,
23732                boolean overridePolicy) {
23733            PackageManagerService.this.mPermissionManager.grantRuntimePermission(
23734                    permName, packageName, overridePolicy, getCallingUid(), userId,
23735                    mPermissionCallback);
23736        }
23737
23738        @Override
23739        public void revokeRuntimePermission(String packageName, String permName, int userId,
23740                boolean overridePolicy) {
23741            mPermissionManager.revokeRuntimePermission(
23742                    permName, packageName, overridePolicy, getCallingUid(), userId,
23743                    mPermissionCallback);
23744        }
23745
23746        @Override
23747        public String getNameForUid(int uid) {
23748            return PackageManagerService.this.getNameForUid(uid);
23749        }
23750
23751        @Override
23752        public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
23753                Intent origIntent, String resolvedType, String callingPackage,
23754                Bundle verificationBundle, int userId) {
23755            PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
23756                    responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
23757                    userId);
23758        }
23759
23760        @Override
23761        public void grantEphemeralAccess(int userId, Intent intent,
23762                int targetAppId, int ephemeralAppId) {
23763            synchronized (mPackages) {
23764                mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
23765                        targetAppId, ephemeralAppId);
23766            }
23767        }
23768
23769        @Override
23770        public boolean isInstantAppInstallerComponent(ComponentName component) {
23771            synchronized (mPackages) {
23772                return mInstantAppInstallerActivity != null
23773                        && mInstantAppInstallerActivity.getComponentName().equals(component);
23774            }
23775        }
23776
23777        @Override
23778        public void pruneInstantApps() {
23779            mInstantAppRegistry.pruneInstantApps();
23780        }
23781
23782        @Override
23783        public String getSetupWizardPackageName() {
23784            return mSetupWizardPackage;
23785        }
23786
23787        public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
23788            if (policy != null) {
23789                mExternalSourcesPolicy = policy;
23790            }
23791        }
23792
23793        @Override
23794        public boolean isPackagePersistent(String packageName) {
23795            synchronized (mPackages) {
23796                PackageParser.Package pkg = mPackages.get(packageName);
23797                return pkg != null
23798                        ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
23799                                        | ApplicationInfo.FLAG_PERSISTENT)) ==
23800                                (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
23801                        : false;
23802            }
23803        }
23804
23805        @Override
23806        public boolean isLegacySystemApp(Package pkg) {
23807            synchronized (mPackages) {
23808                final PackageSetting ps = (PackageSetting) pkg.mExtras;
23809                return mPromoteSystemApps
23810                        && ps.isSystem()
23811                        && mExistingSystemPackages.contains(ps.name);
23812            }
23813        }
23814
23815        @Override
23816        public List<PackageInfo> getOverlayPackages(int userId) {
23817            final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
23818            synchronized (mPackages) {
23819                for (PackageParser.Package p : mPackages.values()) {
23820                    if (p.mOverlayTarget != null) {
23821                        PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
23822                        if (pkg != null) {
23823                            overlayPackages.add(pkg);
23824                        }
23825                    }
23826                }
23827            }
23828            return overlayPackages;
23829        }
23830
23831        @Override
23832        public List<String> getTargetPackageNames(int userId) {
23833            List<String> targetPackages = new ArrayList<>();
23834            synchronized (mPackages) {
23835                for (PackageParser.Package p : mPackages.values()) {
23836                    if (p.mOverlayTarget == null) {
23837                        targetPackages.add(p.packageName);
23838                    }
23839                }
23840            }
23841            return targetPackages;
23842        }
23843
23844        @Override
23845        public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
23846                @Nullable List<String> overlayPackageNames) {
23847            synchronized (mPackages) {
23848                if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
23849                    Slog.e(TAG, "failed to find package " + targetPackageName);
23850                    return false;
23851                }
23852                ArrayList<String> overlayPaths = null;
23853                if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
23854                    final int N = overlayPackageNames.size();
23855                    overlayPaths = new ArrayList<>(N);
23856                    for (int i = 0; i < N; i++) {
23857                        final String packageName = overlayPackageNames.get(i);
23858                        final PackageParser.Package pkg = mPackages.get(packageName);
23859                        if (pkg == null) {
23860                            Slog.e(TAG, "failed to find package " + packageName);
23861                            return false;
23862                        }
23863                        overlayPaths.add(pkg.baseCodePath);
23864                    }
23865                }
23866
23867                final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
23868                ps.setOverlayPaths(overlayPaths, userId);
23869                return true;
23870            }
23871        }
23872
23873        @Override
23874        public ResolveInfo resolveIntent(Intent intent, String resolvedType,
23875                int flags, int userId, boolean resolveForStart) {
23876            return resolveIntentInternal(
23877                    intent, resolvedType, flags, userId, resolveForStart);
23878        }
23879
23880        @Override
23881        public ResolveInfo resolveService(Intent intent, String resolvedType,
23882                int flags, int userId, int callingUid) {
23883            return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
23884        }
23885
23886        @Override
23887        public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
23888            return PackageManagerService.this.resolveContentProviderInternal(
23889                    name, flags, userId);
23890        }
23891
23892        @Override
23893        public void addIsolatedUid(int isolatedUid, int ownerUid) {
23894            synchronized (mPackages) {
23895                mIsolatedOwners.put(isolatedUid, ownerUid);
23896            }
23897        }
23898
23899        @Override
23900        public void removeIsolatedUid(int isolatedUid) {
23901            synchronized (mPackages) {
23902                mIsolatedOwners.delete(isolatedUid);
23903            }
23904        }
23905
23906        @Override
23907        public int getUidTargetSdkVersion(int uid) {
23908            synchronized (mPackages) {
23909                return getUidTargetSdkVersionLockedLPr(uid);
23910            }
23911        }
23912
23913        @Override
23914        public int getPackageTargetSdkVersion(String packageName) {
23915            synchronized (mPackages) {
23916                return getPackageTargetSdkVersionLockedLPr(packageName);
23917            }
23918        }
23919
23920        @Override
23921        public boolean canAccessInstantApps(int callingUid, int userId) {
23922            return PackageManagerService.this.canViewInstantApps(callingUid, userId);
23923        }
23924
23925        @Override
23926        public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
23927            synchronized (mPackages) {
23928                final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
23929                return !PackageManagerService.this.filterAppAccessLPr(
23930                        ps, callingUid, component, TYPE_UNKNOWN, userId);
23931            }
23932        }
23933
23934        @Override
23935        public boolean hasInstantApplicationMetadata(String packageName, int userId) {
23936            synchronized (mPackages) {
23937                return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
23938            }
23939        }
23940
23941        @Override
23942        public void notifyPackageUse(String packageName, int reason) {
23943            synchronized (mPackages) {
23944                PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
23945            }
23946        }
23947    }
23948
23949    @Override
23950    public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
23951        enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
23952        synchronized (mPackages) {
23953            final long identity = Binder.clearCallingIdentity();
23954            try {
23955                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
23956                        packageNames, userId);
23957            } finally {
23958                Binder.restoreCallingIdentity(identity);
23959            }
23960        }
23961    }
23962
23963    @Override
23964    public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
23965        enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
23966        synchronized (mPackages) {
23967            final long identity = Binder.clearCallingIdentity();
23968            try {
23969                mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
23970                        packageNames, userId);
23971            } finally {
23972                Binder.restoreCallingIdentity(identity);
23973            }
23974        }
23975    }
23976
23977    private static void enforceSystemOrPhoneCaller(String tag) {
23978        int callingUid = Binder.getCallingUid();
23979        if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
23980            throw new SecurityException(
23981                    "Cannot call " + tag + " from UID " + callingUid);
23982        }
23983    }
23984
23985    boolean isHistoricalPackageUsageAvailable() {
23986        return mPackageUsage.isHistoricalPackageUsageAvailable();
23987    }
23988
23989    /**
23990     * Return a <b>copy</b> of the collection of packages known to the package manager.
23991     * @return A copy of the values of mPackages.
23992     */
23993    Collection<PackageParser.Package> getPackages() {
23994        synchronized (mPackages) {
23995            return new ArrayList<>(mPackages.values());
23996        }
23997    }
23998
23999    /**
24000     * Logs process start information (including base APK hash) to the security log.
24001     * @hide
24002     */
24003    @Override
24004    public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
24005            String apkFile, int pid) {
24006        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24007            return;
24008        }
24009        if (!SecurityLog.isLoggingEnabled()) {
24010            return;
24011        }
24012        Bundle data = new Bundle();
24013        data.putLong("startTimestamp", System.currentTimeMillis());
24014        data.putString("processName", processName);
24015        data.putInt("uid", uid);
24016        data.putString("seinfo", seinfo);
24017        data.putString("apkFile", apkFile);
24018        data.putInt("pid", pid);
24019        Message msg = mProcessLoggingHandler.obtainMessage(
24020                ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
24021        msg.setData(data);
24022        mProcessLoggingHandler.sendMessage(msg);
24023    }
24024
24025    public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
24026        return mCompilerStats.getPackageStats(pkgName);
24027    }
24028
24029    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
24030        return getOrCreateCompilerPackageStats(pkg.packageName);
24031    }
24032
24033    public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
24034        return mCompilerStats.getOrCreatePackageStats(pkgName);
24035    }
24036
24037    public void deleteCompilerPackageStats(String pkgName) {
24038        mCompilerStats.deletePackageStats(pkgName);
24039    }
24040
24041    @Override
24042    public int getInstallReason(String packageName, int userId) {
24043        final int callingUid = Binder.getCallingUid();
24044        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24045                true /* requireFullPermission */, false /* checkShell */,
24046                "get install reason");
24047        synchronized (mPackages) {
24048            final PackageSetting ps = mSettings.mPackages.get(packageName);
24049            if (filterAppAccessLPr(ps, callingUid, userId)) {
24050                return PackageManager.INSTALL_REASON_UNKNOWN;
24051            }
24052            if (ps != null) {
24053                return ps.getInstallReason(userId);
24054            }
24055        }
24056        return PackageManager.INSTALL_REASON_UNKNOWN;
24057    }
24058
24059    @Override
24060    public boolean canRequestPackageInstalls(String packageName, int userId) {
24061        return canRequestPackageInstallsInternal(packageName, 0, userId,
24062                true /* throwIfPermNotDeclared*/);
24063    }
24064
24065    private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
24066            boolean throwIfPermNotDeclared) {
24067        int callingUid = Binder.getCallingUid();
24068        int uid = getPackageUid(packageName, 0, userId);
24069        if (callingUid != uid && callingUid != Process.ROOT_UID
24070                && callingUid != Process.SYSTEM_UID) {
24071            throw new SecurityException(
24072                    "Caller uid " + callingUid + " does not own package " + packageName);
24073        }
24074        ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
24075        if (info == null) {
24076            return false;
24077        }
24078        if (info.targetSdkVersion < Build.VERSION_CODES.O) {
24079            return false;
24080        }
24081        String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
24082        String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
24083        if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
24084            if (throwIfPermNotDeclared) {
24085                throw new SecurityException("Need to declare " + appOpPermission
24086                        + " to call this api");
24087            } else {
24088                Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
24089                return false;
24090            }
24091        }
24092        if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) {
24093            return false;
24094        }
24095        if (mExternalSourcesPolicy != null) {
24096            int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
24097            if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) {
24098                return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
24099            }
24100        }
24101        return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED;
24102    }
24103
24104    @Override
24105    public ComponentName getInstantAppResolverSettingsComponent() {
24106        return mInstantAppResolverSettingsComponent;
24107    }
24108
24109    @Override
24110    public ComponentName getInstantAppInstallerComponent() {
24111        if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
24112            return null;
24113        }
24114        return mInstantAppInstallerActivity == null
24115                ? null : mInstantAppInstallerActivity.getComponentName();
24116    }
24117
24118    @Override
24119    public String getInstantAppAndroidId(String packageName, int userId) {
24120        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
24121                "getInstantAppAndroidId");
24122        mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
24123                true /* requireFullPermission */, false /* checkShell */,
24124                "getInstantAppAndroidId");
24125        // Make sure the target is an Instant App.
24126        if (!isInstantApp(packageName, userId)) {
24127            return null;
24128        }
24129        synchronized (mPackages) {
24130            return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
24131        }
24132    }
24133
24134    boolean canHaveOatDir(String packageName) {
24135        synchronized (mPackages) {
24136            PackageParser.Package p = mPackages.get(packageName);
24137            if (p == null) {
24138                return false;
24139            }
24140            return p.canHaveOatDir();
24141        }
24142    }
24143
24144    private String getOatDir(PackageParser.Package pkg) {
24145        if (!pkg.canHaveOatDir()) {
24146            return null;
24147        }
24148        File codePath = new File(pkg.codePath);
24149        if (codePath.isDirectory()) {
24150            return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
24151        }
24152        return null;
24153    }
24154
24155    void deleteOatArtifactsOfPackage(String packageName) {
24156        final String[] instructionSets;
24157        final List<String> codePaths;
24158        final String oatDir;
24159        final PackageParser.Package pkg;
24160        synchronized (mPackages) {
24161            pkg = mPackages.get(packageName);
24162        }
24163        instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
24164        codePaths = pkg.getAllCodePaths();
24165        oatDir = getOatDir(pkg);
24166
24167        for (String codePath : codePaths) {
24168            for (String isa : instructionSets) {
24169                try {
24170                    mInstaller.deleteOdex(codePath, isa, oatDir);
24171                } catch (InstallerException e) {
24172                    Log.e(TAG, "Failed deleting oat files for " + codePath, e);
24173                }
24174            }
24175        }
24176    }
24177
24178    Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
24179        Set<String> unusedPackages = new HashSet<>();
24180        long currentTimeInMillis = System.currentTimeMillis();
24181        synchronized (mPackages) {
24182            for (PackageParser.Package pkg : mPackages.values()) {
24183                PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
24184                if (ps == null) {
24185                    continue;
24186                }
24187                PackageDexUsage.PackageUseInfo packageUseInfo =
24188                      getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
24189                if (PackageManagerServiceUtils
24190                        .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
24191                                downgradeTimeThresholdMillis, packageUseInfo,
24192                                pkg.getLatestPackageUseTimeInMills(),
24193                                pkg.getLatestForegroundPackageUseTimeInMills())) {
24194                    unusedPackages.add(pkg.packageName);
24195                }
24196            }
24197        }
24198        return unusedPackages;
24199    }
24200
24201    @Override
24202    public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
24203            int userId) {
24204        final int callingUid = Binder.getCallingUid();
24205        final int callingAppId = UserHandle.getAppId(callingUid);
24206
24207        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24208                true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
24209
24210        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24211                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24212            throw new SecurityException("Caller must have the "
24213                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24214        }
24215
24216        synchronized(mPackages) {
24217            mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
24218            scheduleWritePackageRestrictionsLocked(userId);
24219        }
24220    }
24221
24222    @Nullable
24223    @Override
24224    public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
24225        final int callingUid = Binder.getCallingUid();
24226        final int callingAppId = UserHandle.getAppId(callingUid);
24227
24228        mPermissionManager.enforceCrossUserPermission(callingUid, userId,
24229                true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
24230
24231        if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
24232                checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
24233            throw new SecurityException("Caller must have the "
24234                    + SET_HARMFUL_APP_WARNINGS + " permission.");
24235        }
24236
24237        synchronized(mPackages) {
24238            return mSettings.getHarmfulAppWarningLPr(packageName, userId);
24239        }
24240    }
24241}
24242
24243interface PackageSender {
24244    /**
24245     * @param userIds User IDs where the action occurred on a full application
24246     * @param instantUserIds User IDs where the action occurred on an instant application
24247     */
24248    void sendPackageBroadcast(final String action, final String pkg,
24249        final Bundle extras, final int flags, final String targetPkg,
24250        final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
24251    void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
24252        boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
24253    void notifyPackageAdded(String packageName);
24254    void notifyPackageRemoved(String packageName);
24255}
24256