• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *      http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 package com.android.server.pm;
17 
18 import static android.Manifest.permission.MANAGE_DEVICE_ADMINS;
19 import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
20 import static android.app.AppOpsManager.MODE_IGNORED;
21 import static android.app.admin.flags.Flags.crossUserSuspensionEnabledRo;
22 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
28 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
29 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
30 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
31 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
32 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
33 import static android.content.pm.PackageManager.USER_MIN_ASPECT_RATIO_UNSET;
34 import static android.crashrecovery.flags.Flags.refactorCrashrecovery;
35 import static android.os.Process.INVALID_UID;
36 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
37 import static android.os.UserHandle.USER_ALL;
38 import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
39 import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
40 import static android.os.storage.StorageManager.FLAG_STORAGE_EXTERNAL;
41 import static android.provider.DeviceConfig.NAMESPACE_PACKAGE_MANAGER_SERVICE;
42 
43 import static com.android.internal.annotations.VisibleForTesting.Visibility;
44 import static com.android.internal.util.FrameworkStatsLog.BOOT_TIME_EVENT_DURATION__EVENT__OTA_PACKAGE_MANAGER_INIT_TIME;
45 import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
46 import static com.android.server.pm.PackageManagerServiceUtils.isInstalledByAdb;
47 import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
48 
49 import android.Manifest;
50 import android.annotation.AppIdInt;
51 import android.annotation.IntDef;
52 import android.annotation.NonNull;
53 import android.annotation.Nullable;
54 import android.annotation.SpecialUsers.CanBeALL;
55 import android.annotation.StringRes;
56 import android.annotation.UserIdInt;
57 import android.annotation.WorkerThread;
58 import android.app.ActivityManager;
59 import android.app.ActivityManagerInternal;
60 import android.app.AppOpsManager;
61 import android.app.AppOpsManagerInternal;
62 import android.app.ApplicationExitInfo;
63 import android.app.ApplicationPackageManager;
64 import android.app.BroadcastOptions;
65 import android.app.IActivityManager;
66 import android.app.admin.DevicePolicyManagerInternal;
67 import android.app.admin.IDevicePolicyManager;
68 import android.app.admin.SecurityLog;
69 import android.app.backup.IBackupManager;
70 import android.app.role.RoleManager;
71 import android.companion.virtual.VirtualDeviceManager;
72 import android.compat.annotation.ChangeId;
73 import android.compat.annotation.EnabledAfter;
74 import android.content.BroadcastReceiver;
75 import android.content.ComponentName;
76 import android.content.ContentResolver;
77 import android.content.Context;
78 import android.content.Intent;
79 import android.content.IntentFilter;
80 import android.content.IntentSender;
81 import android.content.IntentSender.SendIntentException;
82 import android.content.pm.ActivityInfo;
83 import android.content.pm.ApplicationInfo;
84 import android.content.pm.ArchivedPackageParcel;
85 import android.content.pm.AuxiliaryResolveInfo;
86 import android.content.pm.ChangedPackages;
87 import android.content.pm.Checksum;
88 import android.content.pm.ComponentInfo;
89 import android.content.pm.DataLoaderType;
90 import android.content.pm.FallbackCategoryProvider;
91 import android.content.pm.FeatureInfo;
92 import android.content.pm.Flags;
93 import android.content.pm.IDexModuleRegisterCallback;
94 import android.content.pm.IOnChecksumsReadyListener;
95 import android.content.pm.IPackageDataObserver;
96 import android.content.pm.IPackageDeleteObserver2;
97 import android.content.pm.IPackageLoadingProgressCallback;
98 import android.content.pm.IPackageMoveObserver;
99 import android.content.pm.IncrementalStatesInfo;
100 import android.content.pm.InstallSourceInfo;
101 import android.content.pm.InstantAppInfo;
102 import android.content.pm.InstantAppRequest;
103 import android.content.pm.ModuleInfo;
104 import android.content.pm.PackageInfo;
105 import android.content.pm.PackageInfoLite;
106 import android.content.pm.PackageInstaller;
107 import android.content.pm.PackageManager;
108 import android.content.pm.PackageManager.ComponentEnabledSetting;
109 import android.content.pm.PackageManagerInternal;
110 import android.content.pm.PackagePartitions;
111 import android.content.pm.ParceledListSlice;
112 import android.content.pm.PermissionGroupInfo;
113 import android.content.pm.ProviderInfo;
114 import android.content.pm.ResolveInfo;
115 import android.content.pm.SharedLibraryInfo;
116 import android.content.pm.Signature;
117 import android.content.pm.SigningDetails;
118 import android.content.pm.SuspendDialogInfo;
119 import android.content.pm.TestUtilityService;
120 import android.content.pm.UserInfo;
121 import android.content.pm.UserPackage;
122 import android.content.pm.VerifierDeviceIdentity;
123 import android.content.pm.VerifierInfo;
124 import android.content.pm.VersionedPackage;
125 import android.content.pm.overlay.OverlayPaths;
126 import android.content.pm.parsing.PackageLite;
127 import android.content.res.Resources;
128 import android.database.ContentObserver;
129 import android.graphics.Bitmap;
130 import android.hardware.display.DisplayManager;
131 import android.net.Uri;
132 import android.os.Binder;
133 import android.os.Build;
134 import android.os.Bundle;
135 import android.os.Environment;
136 import android.os.FileUtils;
137 import android.os.Handler;
138 import android.os.HandlerThread;
139 import android.os.IBinder;
140 import android.os.IRemoteCallback;
141 import android.os.Message;
142 import android.os.Parcel;
143 import android.os.ParcelFileDescriptor;
144 import android.os.ParcelableException;
145 import android.os.PersistableBundle;
146 import android.os.Process;
147 import android.os.ReconcileSdkDataArgs;
148 import android.os.RemoteException;
149 import android.os.ResultReceiver;
150 import android.os.ServiceManager;
151 import android.os.ShellCallback;
152 import android.os.SystemClock;
153 import android.os.SystemProperties;
154 import android.os.Trace;
155 import android.os.UserHandle;
156 import android.os.UserManager;
157 import android.os.incremental.IncrementalManager;
158 import android.os.incremental.PerUidReadTimeouts;
159 import android.os.storage.StorageManager;
160 import android.os.storage.StorageManagerInternal;
161 import android.os.storage.VolumeRecord;
162 import android.permission.PermissionManager;
163 import android.provider.DeviceConfig;
164 import android.provider.Settings.Global;
165 import android.provider.Settings.Secure;
166 import android.text.TextUtils;
167 import android.util.ArrayMap;
168 import android.util.ArraySet;
169 import android.util.DisplayMetrics;
170 import android.util.EventLog;
171 import android.util.ExceptionUtils;
172 import android.util.Log;
173 import android.util.Pair;
174 import android.util.Slog;
175 import android.util.SparseArray;
176 import android.util.SparseBooleanArray;
177 import android.util.Xml;
178 import android.view.Display;
179 
180 import com.android.internal.R;
181 import com.android.internal.annotations.GuardedBy;
182 import com.android.internal.annotations.VisibleForTesting;
183 import com.android.internal.app.ResolverActivity;
184 import com.android.internal.content.F2fsUtils;
185 import com.android.internal.content.InstallLocationUtils;
186 import com.android.internal.content.om.OverlayConfig;
187 import com.android.internal.pm.parsing.PackageParser2;
188 import com.android.internal.pm.parsing.pkg.AndroidPackageInternal;
189 import com.android.internal.pm.parsing.pkg.ParsedPackage;
190 import com.android.internal.pm.pkg.component.ParsedInstrumentation;
191 import com.android.internal.pm.pkg.component.ParsedMainComponent;
192 import com.android.internal.pm.pkg.parsing.ParsingPackageUtils;
193 import com.android.internal.telephony.CarrierAppUtils;
194 import com.android.internal.util.ArrayUtils;
195 import com.android.internal.util.CollectionUtils;
196 import com.android.internal.util.ConcurrentUtils;
197 import com.android.internal.util.DumpUtils;
198 import com.android.internal.util.FrameworkStatsLog;
199 import com.android.internal.util.FunctionalUtils;
200 import com.android.internal.util.Preconditions;
201 import com.android.modules.utils.TypedXmlPullParser;
202 import com.android.modules.utils.TypedXmlSerializer;
203 import com.android.permission.persistence.RuntimePermissionsPersistence;
204 import com.android.permission.persistence.RuntimePermissionsState;
205 import com.android.server.EventLogTags;
206 import com.android.server.FgThread;
207 import com.android.server.LocalManagerRegistry;
208 import com.android.server.LocalServices;
209 import com.android.server.LockGuard;
210 import com.android.server.ServiceThread;
211 import com.android.server.SystemConfig;
212 import com.android.server.ThreadPriorityBooster;
213 import com.android.server.Watchdog;
214 import com.android.server.apphibernation.AppHibernationManagerInternal;
215 import com.android.server.art.DexUseManagerLocal;
216 import com.android.server.art.model.DeleteResult;
217 import com.android.server.compat.CompatChange;
218 import com.android.server.compat.PlatformCompat;
219 import com.android.server.crashrecovery.CrashRecoveryAdaptor;
220 import com.android.server.pm.Installer.InstallerException;
221 import com.android.server.pm.Settings.VersionInfo;
222 import com.android.server.pm.dex.ArtManagerService;
223 import com.android.server.pm.dex.DexManager;
224 import com.android.server.pm.dex.DynamicCodeLogger;
225 import com.android.server.pm.local.PackageManagerLocalImpl;
226 import com.android.server.pm.parsing.PackageCacher;
227 import com.android.server.pm.parsing.PackageInfoUtils;
228 import com.android.server.pm.parsing.pkg.AndroidPackageUtils;
229 import com.android.server.pm.permission.LegacyPermissionManagerInternal;
230 import com.android.server.pm.permission.LegacyPermissionManagerService;
231 import com.android.server.pm.permission.LegacyPermissionSettings;
232 import com.android.server.pm.permission.PermissionManagerService;
233 import com.android.server.pm.permission.PermissionManagerServiceInternal;
234 import com.android.server.pm.pkg.AndroidPackage;
235 import com.android.server.pm.pkg.ArchiveState;
236 import com.android.server.pm.pkg.PackageState;
237 import com.android.server.pm.pkg.PackageStateInternal;
238 import com.android.server.pm.pkg.PackageUserState;
239 import com.android.server.pm.pkg.PackageUserStateInternal;
240 import com.android.server.pm.pkg.SharedUserApi;
241 import com.android.server.pm.pkg.mutate.PackageStateMutator;
242 import com.android.server.pm.pkg.mutate.PackageStateWrite;
243 import com.android.server.pm.pkg.mutate.PackageUserStateWrite;
244 import com.android.server.pm.resolution.ComponentResolver;
245 import com.android.server.pm.resolution.ComponentResolverApi;
246 import com.android.server.pm.verify.domain.DomainVerificationManagerInternal;
247 import com.android.server.pm.verify.domain.DomainVerificationService;
248 import com.android.server.pm.verify.domain.proxy.DomainVerificationProxy;
249 import com.android.server.sdksandbox.SdkSandboxManagerLocal;
250 import com.android.server.storage.DeviceStorageMonitorInternal;
251 import com.android.server.utils.SnapshotCache;
252 import com.android.server.utils.TimingsTraceAndSlog;
253 import com.android.server.utils.Watchable;
254 import com.android.server.utils.Watched;
255 import com.android.server.utils.WatchedArrayMap;
256 import com.android.server.utils.WatchedSparseBooleanArray;
257 import com.android.server.utils.WatchedSparseIntArray;
258 import com.android.server.utils.Watcher;
259 
260 import dalvik.system.VMRuntime;
261 
262 import libcore.util.EmptyArray;
263 import libcore.util.HexEncoding;
264 
265 import java.io.ByteArrayInputStream;
266 import java.io.ByteArrayOutputStream;
267 import java.io.File;
268 import java.io.FileDescriptor;
269 import java.io.FileNotFoundException;
270 import java.io.IOException;
271 import java.io.InputStream;
272 import java.io.PrintWriter;
273 import java.lang.annotation.Retention;
274 import java.lang.annotation.RetentionPolicy;
275 import java.security.MessageDigest;
276 import java.security.NoSuchAlgorithmException;
277 import java.security.cert.Certificate;
278 import java.security.cert.CertificateException;
279 import java.security.cert.CertificateFactory;
280 import java.security.cert.X509Certificate;
281 import java.util.ArrayList;
282 import java.util.Arrays;
283 import java.util.Collections;
284 import java.util.HashMap;
285 import java.util.Iterator;
286 import java.util.List;
287 import java.util.Map;
288 import java.util.Objects;
289 import java.util.Set;
290 import java.util.concurrent.CountDownLatch;
291 import java.util.concurrent.Executor;
292 import java.util.concurrent.Future;
293 import java.util.concurrent.TimeUnit;
294 import java.util.concurrent.atomic.AtomicInteger;
295 import java.util.concurrent.atomic.AtomicReference;
296 import java.util.function.Consumer;
297 import java.util.function.Predicate;
298 
299 /**
300  * Keep track of all those APKs everywhere.
301  * <p>
302  * Internally there are three important locks:
303  * <ul>
304  * <li>{@link #mLock} is used to guard all in-memory parsed package details
305  * and other related state. It is a fine-grained lock that should only be held
306  * momentarily, as it's one of the most contended locks in the system.
307  * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
308  * operations typically involve heavy lifting of application data on disk. Since
309  * {@code installd} is single-threaded, and it's operations can often be slow,
310  * this lock should never be acquired while already holding {@link #mLock}.
311  * Conversely, it's safe to acquire {@link #mLock} momentarily while already
312  * holding {@link #mInstallLock}.
313  * <li>{@link #mSnapshotLock} is used to guard access to two snapshot fields: the snapshot
314  * itself and the snapshot invalidation flag.  This lock should never be acquired while
315  * already holding {@link #mLock}. Conversely, it's safe to acquire {@link #mLock}
316  * momentarily while already holding {@link #mSnapshotLock}.
317  * </ul>
318  * Many internal methods rely on the caller to hold the appropriate locks, and
319  * this contract is expressed through method name suffixes:
320  * <ul>
321  * <li>fooLI(): the caller must hold {@link #mInstallLock}
322  * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
323  * being modified must be frozen
324  * <li>fooLPr(): the caller must hold {@link #mLock} for reading
325  * <li>fooLPw(): the caller must hold {@link #mLock} for writing
326  * </ul>
327  * {@link #mSnapshotLock} is taken in exactly one place - {@code snapshotComputer()}.  It
328  * should not be taken anywhere else or used for any other purpose.
329  * <p>
330  * Because this class is very central to the platform's security; please run all
331  * CTS and unit tests whenever making modifications:
332  *
333  * <pre>
334  * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
335  * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
336  * </pre>
337  */
338 public class PackageManagerService implements PackageSender, TestUtilityService {
339 
340     static final String TAG = "PackageManager";
341     public static final boolean DEBUG_SETTINGS = false;
342     static final boolean DEBUG_PREFERRED = false;
343     static final boolean DEBUG_UPGRADE = false;
344     static final boolean DEBUG_DOMAIN_VERIFICATION = false;
345     static final boolean DEBUG_BACKUP = false;
346     public static final boolean DEBUG_INSTALL = false;
347     public static final boolean DEBUG_REMOVE = false;
348     static final boolean DEBUG_PACKAGE_INFO = false;
349     static final boolean DEBUG_INTENT_MATCHING = false;
350     public static final boolean DEBUG_PACKAGE_SCANNING = false;
351     static final boolean DEBUG_VERIFY = false;
352     public static final boolean DEBUG_PERMISSIONS = false;
353     public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
354     public static final boolean TRACE_SNAPSHOTS = false;
355     private static final boolean DEBUG_PER_UID_READ_TIMEOUTS = false;
356 
357     // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
358     // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
359     // user, but by default initialize to this.
360     public static final boolean DEBUG_DEXOPT = false;
361 
362     static final boolean DEBUG_ABI_SELECTION = false;
363     public static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
364 
365     static final String SHELL_PACKAGE_NAME = "com.android.shell";
366 
367     static final boolean HIDE_EPHEMERAL_APIS = false;
368 
369     static final String PRECOMPILE_LAYOUTS = "pm.precompile_layouts";
370 
371     private static final int RADIO_UID = Process.PHONE_UID;
372     private static final int LOG_UID = Process.LOG_UID;
373     private static final int NFC_UID = Process.NFC_UID;
374     private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
375     private static final int SHELL_UID = Process.SHELL_UID;
376     private static final int SE_UID = Process.SE_UID;
377     private static final int NETWORKSTACK_UID = Process.NETWORK_STACK_UID;
378     private static final int UWB_UID = Process.UWB_UID;
379 
380     static final int SCAN_NO_DEX = 1 << 0;
381     static final int SCAN_UPDATE_SIGNATURE = 1 << 1;
382     static final int SCAN_NEW_INSTALL = 1 << 2;
383     static final int SCAN_UPDATE_TIME = 1 << 3;
384     static final int SCAN_BOOTING = 1 << 4;
385     static final int SCAN_REQUIRE_KNOWN = 1 << 7;
386     static final int SCAN_MOVE = 1 << 8;
387     static final int SCAN_INITIAL = 1 << 9;
388     static final int SCAN_DONT_KILL_APP = 1 << 10;
389     static final int SCAN_IGNORE_FROZEN = 1 << 11;
390     static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1 << 12;
391     static final int SCAN_AS_INSTANT_APP = 1 << 13;
392     static final int SCAN_AS_FULL_APP = 1 << 14;
393     static final int SCAN_AS_VIRTUAL_PRELOAD = 1 << 15;
394     static final int SCAN_AS_SYSTEM = 1 << 16;
395     static final int SCAN_AS_PRIVILEGED = 1 << 17;
396     static final int SCAN_AS_OEM = 1 << 18;
397     static final int SCAN_AS_VENDOR = 1 << 19;
398     static final int SCAN_AS_PRODUCT = 1 << 20;
399     static final int SCAN_AS_SYSTEM_EXT = 1 << 21;
400     static final int SCAN_AS_ODM = 1 << 22;
401     static final int SCAN_AS_APK_IN_APEX = 1 << 23;
402     static final int SCAN_DROP_CACHE = 1 << 24;
403     static final int SCAN_AS_FACTORY = 1 << 25;
404     static final int SCAN_AS_APEX = 1 << 26;
405     static final int SCAN_AS_STOPPED_SYSTEM_APP = 1 << 27;
406 
407     @IntDef(flag = true, prefix = { "SCAN_" }, value = {
408             SCAN_NO_DEX,
409             SCAN_UPDATE_SIGNATURE,
410             SCAN_NEW_INSTALL,
411             SCAN_UPDATE_TIME,
412             SCAN_BOOTING,
413             SCAN_REQUIRE_KNOWN,
414             SCAN_MOVE,
415             SCAN_INITIAL,
416             SCAN_DONT_KILL_APP,
417             SCAN_IGNORE_FROZEN,
418             SCAN_FIRST_BOOT_OR_UPGRADE,
419             SCAN_AS_INSTANT_APP,
420             SCAN_AS_FULL_APP,
421             SCAN_AS_VIRTUAL_PRELOAD,
422             SCAN_AS_STOPPED_SYSTEM_APP,
423     })
424     @Retention(RetentionPolicy.SOURCE)
425     public @interface ScanFlags {}
426 
427     /**
428      * Used as the result code of the {@link Computer#getPackageStartability(boolean, String, int,
429      * int)}.
430      */
431     @IntDef(value = {
432         PACKAGE_STARTABILITY_OK,
433         PACKAGE_STARTABILITY_NOT_FOUND,
434         PACKAGE_STARTABILITY_NOT_SYSTEM,
435         PACKAGE_STARTABILITY_FROZEN,
436         PACKAGE_STARTABILITY_DIRECT_BOOT_UNSUPPORTED,
437     })
438     @Retention(RetentionPolicy.SOURCE)
439     public @interface PackageStartability {}
440 
441     /**
442      * Used as the result code of the {@link Computer#getPackageStartability(boolean, String, int,
443      * int)} to indicate the given package is allowed to start.
444      */
445     public static final int PACKAGE_STARTABILITY_OK = 0;
446 
447     /**
448      * Used as the result code of the {@link Computer#getPackageStartability(boolean, String, int,
449      * int)} to indicate the given package is <b>not</b> allowed to start because it's not found
450      * (could be due to that package is invisible to the given user).
451      */
452     public static final int PACKAGE_STARTABILITY_NOT_FOUND = 1;
453 
454     /**
455      * Used as the result code of the {@link Computer#getPackageStartability(boolean, String, int,
456      * int)} to indicate the given package is <b>not</b> allowed to start because it's not a system
457      * app and the system is running in safe mode.
458      */
459     public static final int PACKAGE_STARTABILITY_NOT_SYSTEM = 2;
460 
461     /**
462      * Used as the result code of the {@link Computer#getPackageStartability(boolean, String, int,
463      * int)} to indicate the given package is <b>not</b> allowed to start because it's currently
464      * frozen.
465      */
466     public static final int PACKAGE_STARTABILITY_FROZEN = 3;
467 
468     /**
469      * Used as the result code of the {@link Computer#getPackageStartability(boolean, String, int,
470      * int)} to indicate the given package is <b>not</b> allowed to start because it doesn't support
471      * direct boot.
472      */
473     public static final int PACKAGE_STARTABILITY_DIRECT_BOOT_UNSUPPORTED = 4;
474 
475     private static final String STATIC_SHARED_LIB_DELIMITER = "_";
476     /**
477      * Extension of the compressed packages
478      */
479     public final static String COMPRESSED_EXTENSION = ".gz";
480     /** Suffix of stub packages on the system partition */
481     public final static String STUB_SUFFIX = "-Stub";
482 
483     static final int[] EMPTY_INT_ARRAY = new int[0];
484 
485     /**
486      * Timeout (in milliseconds) after which the watchdog should declare that
487      * our handler thread is wedged.  The usual default for such things is one
488      * minute but we sometimes do very lengthy I/O operations on this thread,
489      * such as installing multi-gigabyte applications, so ours needs to be longer.
490      */
491     static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
492 
493     /**
494      * Default IncFs timeouts. Maximum values in IncFs is 1hr.
495      *
496      * <p>If flag value is empty, the default value will be assigned.
497      *
498      * Flag type: {@code String}
499      * Namespace: NAMESPACE_PACKAGE_MANAGER_SERVICE
500      */
501     private static final String PROPERTY_INCFS_DEFAULT_TIMEOUTS = "incfs_default_timeouts";
502 
503     /**
504      * Known digesters with optional timeouts.
505      *
506      * Flag type: {@code String}
507      * Namespace: NAMESPACE_PACKAGE_MANAGER_SERVICE
508      */
509     private static final String PROPERTY_KNOWN_DIGESTERS_LIST = "known_digesters_list";
510 
511     /**
512      * Whether or not requesting the approval before committing sessions is available.
513      *
514      * Flag type: {@code boolean}
515      * Namespace: NAMESPACE_PACKAGE_MANAGER_SERVICE
516      */
517     private static final String PROPERTY_IS_PRE_APPROVAL_REQUEST_AVAILABLE =
518             "is_preapproval_available";
519 
520     /**
521      * Whether or not the update ownership enforcement is available.
522      *
523      * Flag type: {@code boolean}
524      * Namespace: NAMESPACE_PACKAGE_MANAGER_SERVICE
525      */
526     private static final String PROPERTY_IS_UPDATE_OWNERSHIP_ENFORCEMENT_AVAILABLE =
527             "is_update_ownership_enforcement_available";
528 
529     private static final String PROPERTY_DEFERRED_NO_KILL_POST_DELETE_DELAY_MS_EXTENDED =
530             "deferred_no_kill_post_delete_delay_ms_extended";
531 
532     /**
533      * The default response for package verification timeout.
534      *
535      * This can be either PackageManager.VERIFICATION_ALLOW or
536      * PackageManager.VERIFICATION_REJECT.
537      */
538     static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
539 
540     /**
541      * Adding an installer package name to a package that does not have one set requires the
542      * INSTALL_PACKAGES permission.
543      *
544      * If the caller targets R, this will throw a SecurityException. Otherwise the request will
545      * fail silently. In both cases, and regardless of whether this change is enabled, the
546      * installer package will remain unchanged.
547      */
548     @ChangeId
549     @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q)
550     private static final long THROW_EXCEPTION_ON_REQUIRE_INSTALL_PACKAGES_TO_ADD_INSTALLER_PACKAGE =
551             150857253;
552 
553     public static final String PLATFORM_PACKAGE_NAME = "android";
554 
555     static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
556 
557     static final String PACKAGE_SCHEME = "package";
558 
559     private static final String COMPANION_PACKAGE_NAME = "com.android.companiondevicemanager";
560 
561     // How many required verifiers can be on the system.
562     private static final int REQUIRED_VERIFIERS_MAX_COUNT = 2;
563 
564     /**
565      * Specifies the minimum target SDK version an apk must specify in order to be installed
566      * on the system. This improves security and privacy by blocking low
567      * target sdk apps as malware can target older sdk versions to avoid
568      * the enforcement of new API behavior.
569      */
570     public static final int MIN_INSTALLABLE_TARGET_SDK =
571             Flags.minTargetSdk24() ? Build.VERSION_CODES.N : Build.VERSION_CODES.M;
572 
573     // Compilation reasons.
574     // TODO(b/260124949): Clean this up with the legacy dexopt code.
575     public static final int REASON_FIRST_BOOT = 0;
576     public static final int REASON_BOOT_AFTER_OTA = 1;
577     public static final int REASON_POST_BOOT = 2;
578     public static final int REASON_INSTALL = 3;
579     public static final int REASON_INSTALL_FAST = 4;
580     public static final int REASON_INSTALL_BULK = 5;
581     public static final int REASON_INSTALL_BULK_SECONDARY = 6;
582     public static final int REASON_INSTALL_BULK_DOWNGRADED = 7;
583     public static final int REASON_INSTALL_BULK_SECONDARY_DOWNGRADED = 8;
584     public static final int REASON_BACKGROUND_DEXOPT = 9;
585     public static final int REASON_AB_OTA = 10;
586     public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 11;
587     public static final int REASON_CMDLINE = 12;
588     public static final int REASON_BOOT_AFTER_MAINLINE_UPDATE = 13;
589     public static final int REASON_SHARED = 14;
590 
591     public static final int REASON_LAST = REASON_SHARED;
592 
593     static final String RANDOM_DIR_PREFIX = "~~";
594     static final char RANDOM_CODEPATH_PREFIX = '-';
595 
596     public static final String APP_METADATA_FILE_NAME = "app.metadata";
597 
598     static final int DEFAULT_FILE_ACCESS_MODE = 0644;
599 
600     static final int DEFAULT_NATIVE_LIBRARY_FILE_ACCESS_MODE = 0755;
601 
602     final Handler mHandler;
603     final Handler mBackgroundHandler;
604 
605     final ProcessLoggingHandler mProcessLoggingHandler;
606 
607     private final int mSdkVersion;
608     final Context mContext;
609     final boolean mFactoryTest;
610     final DisplayMetrics mMetrics;
611     private final int mDefParseFlags;
612     private final String[] mSeparateProcesses;
613     private final boolean mIsUpgrade;
614     private final boolean mIsPreNMR1Upgrade;
615     private final boolean mIsPreQUpgrade;
616     // If mIsUpgrade == true, contains the prior SDK version, else -1.
617     private final int mPriorSdkVersion;
618 
619     // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
620     // LOCK HELD.  Can be called with mInstallLock held.
621     @GuardedBy("mInstallLock")
622     final Installer mInstaller;
623 
624     /** Directory where installed applications are stored */
625     private final File mAppInstallDir;
626 
627     // ----------------------------------------------------------------
628 
629     // Lock for state used when installing and doing other long running
630     // operations.  Methods that must be called with this lock held have
631     // the suffix "LI".
632     final PackageManagerTracedLock mInstallLock;
633 
634     // ----------------------------------------------------------------
635 
636     // Lock for global state used when modifying package state or settings.
637     // Methods that must be called with this lock held have
638     // the suffix "Locked". Some methods may use the legacy suffix "LP"
639     final PackageManagerTracedLock mLock;
640 
641     // Ensures order of overlay updates until data storage can be moved to overlay code
642     private final PackageManagerTracedLock mOverlayPathsLock = new PackageManagerTracedLock();
643 
644     // Lock alias for doing package state mutation
645     private final PackageManagerTracedLock mPackageStateWriteLock;
646 
647     private final PackageStateMutator mPackageStateMutator = new PackageStateMutator(
648             this::getPackageSettingForMutation,
649             this::getDisabledPackageSettingForMutation);
650 
651     // Keys are String (package name), values are Package.
652     @Watched
653     @GuardedBy("mLock")
654     final WatchedArrayMap<String, AndroidPackage> mPackages = new WatchedArrayMap<>();
655     private final SnapshotCache<WatchedArrayMap<String, AndroidPackage>> mPackagesSnapshot =
656             new SnapshotCache.Auto(mPackages, mPackages, "PackageManagerService.mPackages");
657 
658     // Keys are isolated uids and values are the uid of the application
659     // that created the isolated process.
660     @Watched
661     @GuardedBy("mLock")
662     final WatchedSparseIntArray mIsolatedOwners = new WatchedSparseIntArray();
663     private final SnapshotCache<WatchedSparseIntArray> mIsolatedOwnersSnapshot =
664             new SnapshotCache.Auto(mIsolatedOwners, mIsolatedOwners,
665                                    "PackageManagerService.mIsolatedOwners");
666 
667     /**
668      * Tracks existing packages prior to receiving an OTA. Keys are package name.
669      * Only non-null during an OTA, and even then it is nulled again once systemReady().
670      */
671     private @Nullable ArraySet<String> mExistingPackages = null;
672 
673     /**
674      * List of code paths that need to be released when the system becomes ready.
675      * <p>
676      * NOTE: We have to delay releasing cblocks for no other reason than we cannot
677      * retrieve the setting {@link Secure#RELEASE_COMPRESS_BLOCKS_ON_INSTALL}. When
678      * we no longer need to read that setting, cblock release can occur in the
679      * constructor.
680      *
681      * @see Secure#RELEASE_COMPRESS_BLOCKS_ON_INSTALL
682      * @see #systemReady()
683      */
684     @Nullable List<File> mReleaseOnSystemReady;
685 
686     /**
687      * Whether or not system app permissions should be promoted from install to runtime.
688      */
689     boolean mPromoteSystemApps;
690 
691     private final TestUtilityService mTestUtilityService;
692 
693     @Watched
694     @GuardedBy("mLock")
695     final Settings mSettings;
696 
697     /**
698      * Map of package names to frozen counts that are currently "frozen",
699      * which means active surgery is being done on the code/data for that
700      * package. The platform will refuse to launch frozen packages to avoid
701      * race conditions.
702      *
703      * @see PackageFreezer
704      */
705     @GuardedBy("mLock")
706     final WatchedArrayMap<String, Integer> mFrozenPackages = new WatchedArrayMap<>();
707     private final SnapshotCache<WatchedArrayMap<String, Integer>> mFrozenPackagesSnapshot =
708             new SnapshotCache.Auto(mFrozenPackages, mFrozenPackages,
709                     "PackageManagerService.mFrozenPackages");
710 
711     final ProtectedPackages mProtectedPackages;
712 
713     private boolean mFirstBoot;
714 
715     final boolean mIsEngBuild;
716     private final boolean mIsUserDebugBuild;
717     private final String mIncrementalVersion;
718 
719     PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
720 
721     private final ArrayMap<String, FeatureInfo> mAvailableFeatures;
722 
723     @Watched
724     final InstantAppRegistry mInstantAppRegistry;
725 
726     @NonNull
727     final ChangedPackagesTracker mChangedPackagesTracker;
728 
729     @NonNull
730     private final PackageObserverHelper mPackageObserverHelper = new PackageObserverHelper();
731 
732     @NonNull
733     private final PackageMonitorCallbackHelper mPackageMonitorCallbackHelper;
734 
735     private final ModuleInfoProvider mModuleInfoProvider;
736 
737     final ApexManager mApexManager;
738 
739     final PackageManagerServiceInjector mInjector;
740 
741     /**
742      * The list of all system partitions that may contain packages in ascending order of
743      * specificity (the more generic, the earlier in the list a partition appears).
744      */
745     @VisibleForTesting(visibility = Visibility.PACKAGE)
746     public static final List<ScanPartition> SYSTEM_PARTITIONS = Collections.unmodifiableList(
747             PackagePartitions.getOrderedPartitions(ScanPartition::new));
748 
749     private @NonNull final OverlayConfig mOverlayConfig;
750 
751     // Cached parsed flag value. Invalidated on each flag change.
752     PerUidReadTimeouts[] mPerUidReadTimeoutsCache;
753 
754     private static final PerUidReadTimeouts[] EMPTY_PER_UID_READ_TIMEOUTS_ARRAY = {};
755 
756     private static class DefaultSystemWrapper implements
757             PackageManagerServiceInjector.SystemWrapper {
758 
759         @Override
disablePackageCaches()760         public void disablePackageCaches() {
761             // disable all package caches that shouldn't apply within system server
762             PackageManager.disableApplicationInfoCache();
763             PackageManager.disablePackageInfoCache();
764             ApplicationPackageManager.invalidateGetPackagesForUidCache();
765             ApplicationPackageManager.disableGetPackagesForUidCache();
766             ApplicationPackageManager.invalidateHasSystemFeatureCache();
767             PackageManager.corkPackageInfoCache();
768         }
769 
770         @Override
enablePackageCaches()771         public void enablePackageCaches() {
772             PackageManager.uncorkPackageInfoCache();
773         }
774     }
775 
776     @Watched
777     final AppsFilterImpl mAppsFilter;
778 
779     final PackageParser2.Callback mPackageParserCallback;
780 
781     // Currently known shared libraries.
782     @Watched
783     private final SharedLibrariesImpl mSharedLibraries;
784 
785     // Mapping from instrumentation class names to info about them.
786     @Watched
787     private final WatchedArrayMap<ComponentName, ParsedInstrumentation> mInstrumentation =
788             new WatchedArrayMap<>();
789     private final SnapshotCache<WatchedArrayMap<ComponentName, ParsedInstrumentation>>
790             mInstrumentationSnapshot =
791             new SnapshotCache.Auto<>(mInstrumentation, mInstrumentation,
792                                      "PackageManagerService.mInstrumentation");
793 
794     // Packages whose data we have transfered into another package, thus
795     // should no longer exist.
796     final ArraySet<String> mTransferredPackages = new ArraySet<>();
797 
798     // Broadcast actions that are only available to the system.
799     @GuardedBy("mProtectedBroadcasts")
800     final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
801 
802     /**
803      * List of packages waiting for verification.
804      * Handler thread only!
805      */
806     final SparseArray<PackageVerificationState> mPendingVerification = new SparseArray<>();
807 
808     /**
809      * List of packages waiting for rollback to be enabled.
810      * Handler thread only!
811      */
812     final SparseArray<VerifyingSession> mPendingEnableRollback = new SparseArray<>();
813 
814     final PackageInstallerService mInstallerService;
815     final ArtManagerService mArtManagerService;
816 
817     // TODO(b/260124949): Remove these.
818     final PackageDexOptimizer mPackageDexOptimizer;
819     // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
820     // is used by other apps).
821     private final DexManager mDexManager;
822     private final DynamicCodeLogger mDynamicCodeLogger;
823 
824     private final AtomicInteger mNextMoveId = new AtomicInteger();
825     final MovePackageHelper.MoveCallbacks mMoveCallbacks;
826 
827     /**
828      * Token for keys in mPendingVerification.
829      * Handler thread only!
830      */
831     int mPendingVerificationToken = 0;
832 
833     /**
834      * Token for keys in mPendingEnableRollback.
835      * Handler thread only!
836      */
837     int mPendingEnableRollbackToken = 0;
838 
839     @Watched(manual = true)
840     private volatile boolean mSystemReady;
841     @Watched(manual = true)
842     private volatile boolean mSafeMode;
843     @Watched
844     private final WatchedSparseBooleanArray mWebInstantAppsDisabled =
845             new WatchedSparseBooleanArray();
846 
847     @Watched(manual = true)
848     private ApplicationInfo mAndroidApplication;
849     @Watched(manual = true)
850     private final ActivityInfo mResolveActivity = new ActivityInfo();
851     private final ResolveInfo mResolveInfo = new ResolveInfo();
852     @Watched(manual = true)
853     ComponentName mResolveComponentName;
854     private AndroidPackage mPlatformPackage;
855     ComponentName mCustomResolverComponentName;
856 
857     // Recorded overlay paths configuration for the Android app info.
858     private String[] mPlatformPackageOverlayPaths = null;
859     private String[] mPlatformPackageOverlayResourceDirs = null;
860     // And the same paths for the replaced resolver activity package
861     private String[] mReplacedResolverPackageOverlayPaths = null;
862     private String[] mReplacedResolverPackageOverlayResourceDirs = null;
863 
864     private boolean mResolverReplaced = false;
865 
866     @NonNull
867     final DomainVerificationManagerInternal mDomainVerificationManager;
868 
869     /** The service connection to the ephemeral resolver */
870     final InstantAppResolverConnection mInstantAppResolverConnection;
871     /** Component used to show resolver settings for Instant Apps */
872     final ComponentName mInstantAppResolverSettingsComponent;
873 
874     /** Activity used to install instant applications */
875     @Watched(manual = true)
876     ActivityInfo mInstantAppInstallerActivity;
877     @Watched(manual = true)
878     private final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
879 
880     private final Map<String, InstallRequest>
881             mNoKillInstallObservers = Collections.synchronizedMap(new HashMap<>());
882 
883     private final Map<String, InstallRequest>
884             mPendingKillInstallObservers = Collections.synchronizedMap(new HashMap<>());
885 
886     // Internal interface for permission manager
887     final PermissionManagerServiceInternal mPermissionManager;
888 
889     @Watched
890     final ComponentResolver mComponentResolver;
891 
892     // Set of packages names to keep cached, even if they are uninstalled for all users
893     @GuardedBy("mKeepUninstalledPackages")
894     @NonNull
895     private final ArraySet<String> mKeepUninstalledPackages = new ArraySet<>();
896 
897     // Cached reference to IDevicePolicyManager.
898     private IDevicePolicyManager mDevicePolicyManager = null;
899 
900     private File mCacheDir;
901 
902     private Future<?> mPrepareAppDataFuture;
903 
904     final IncrementalManager mIncrementalManager;
905 
906     private final DefaultAppProvider mDefaultAppProvider;
907 
908     private final LegacyPermissionManagerInternal mLegacyPermissionManager;
909 
910     private final PackageProperty mPackageProperty = new PackageProperty();
911 
912     final PendingPackageBroadcasts mPendingBroadcasts;
913 
914     static final int SEND_PENDING_BROADCAST = 1;
915     // public static final int UNUSED = 5;
916     static final int POST_INSTALL = 9;
917     static final int WRITE_SETTINGS = 13;
918     static final int WRITE_DIRTY_PACKAGE_RESTRICTIONS = 14;
919     static final int PACKAGE_VERIFIED = 15;
920     static final int CHECK_PENDING_VERIFICATION = 16;
921     // public static final int UNUSED = 17;
922     // public static final int UNUSED = 18;
923     static final int WRITE_PACKAGE_LIST = 19;
924     static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
925     static final int ENABLE_ROLLBACK_STATUS = 21;
926     static final int ENABLE_ROLLBACK_TIMEOUT = 22;
927     static final int DEFERRED_NO_KILL_POST_DELETE = 23;
928     static final int DEFERRED_NO_KILL_INSTALL_OBSERVER = 24;
929     // static final int UNUSED = 25;
930     // static final int UNUSED = 26;
931     static final int DOMAIN_VERIFICATION = 27;
932     static final int PRUNE_UNUSED_STATIC_SHARED_LIBRARIES = 28;
933     static final int DEFERRED_PENDING_KILL_INSTALL_OBSERVER = 29;
934 
935     static final int WRITE_USER_PACKAGE_RESTRICTIONS = 30;
936 
937     private static final int DEFERRED_NO_KILL_POST_DELETE_DELAY_MS = 3 * 1000;
938 
939     private static final long DEFERRED_NO_KILL_POST_DELETE_DELAY_MS_EXTENDED =
940             TimeUnit.DAYS.toMillis(1);
941 
942     private static final int DEFERRED_NO_KILL_INSTALL_OBSERVER_DELAY_MS = 500;
943     private static final int DEFERRED_PENDING_KILL_INSTALL_OBSERVER_DELAY_MS = 1000;
944 
945     static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
946 
947     private static final long BROADCAST_DELAY_DURING_STARTUP = 10 * 1000L; // 10 seconds (in millis)
948     private static final long BROADCAST_DELAY = 1 * 1000L; // 1 second (in millis)
949 
950     private static final long PRUNE_UNUSED_SHARED_LIBRARIES_DELAY =
951             TimeUnit.MINUTES.toMillis(3); // 3 minutes
952 
953     // When the service constructor finished plus a delay (used for broadcast delay computation)
954     private long mServiceStartWithDelay;
955 
956     static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
957             TimeUnit.DAYS.toMillis(7); /* 7 days */
958 
959     final UserManagerService mUserManager;
960 
961     final UserNeedsBadgingCache mUserNeedsBadging;
962 
963     // Stores a list of users whose package restrictions file needs to be updated
964     final ArraySet<Integer> mDirtyUsers = new ArraySet<>();
965 
966     @GuardedBy("mRunningInstalls")
967     final SparseArray<InstallRequest> mRunningInstalls = new SparseArray<>();
968     int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
969 
970     final @NonNull String[] mRequiredVerifierPackages;
971     final @NonNull String mRequiredInstallerPackage;
972     final @NonNull String mRequiredUninstallerPackage;
973     final @NonNull String mRequiredPermissionControllerPackage;
974     final @Nullable String mSetupWizardPackage;
975     final @Nullable String mStorageManagerPackage;
976     final @Nullable String mDefaultTextClassifierPackage;
977     final @Nullable String mSystemTextClassifierPackageName;
978     final @Nullable String mConfiguratorPackage;
979     final @Nullable String mAppPredictionServicePackage;
980     final @Nullable String mIncidentReportApproverPackage;
981     final @Nullable String mServicesExtensionPackageName;
982     final @Nullable String mSharedSystemSharedLibraryPackageName;
983     final @Nullable String mRetailDemoPackage;
984     final @Nullable String mOverlayConfigSignaturePackage;
985     final @Nullable String mRecentsPackage;
986     final @Nullable String mAmbientContextDetectionPackage;
987     final @Nullable String mWearableSensingPackage;
988     final @NonNull Set<String> mInitialNonStoppedSystemPackages;
989     final boolean mShouldStopSystemPackagesByDefault;
990     private final @NonNull String mRequiredSdkSandboxPackage;
991 
992     @GuardedBy("mLock")
993     private final PackageUsage mPackageUsage = new PackageUsage();
994     final CompilerStats mCompilerStats = new CompilerStats();
995 
996     private final DomainVerificationConnection mDomainVerificationConnection;
997 
998     private final BroadcastHelper mBroadcastHelper;
999     private final RemovePackageHelper mRemovePackageHelper;
1000     private final DeletePackageHelper mDeletePackageHelper;
1001     private final InitAppsHelper mInitAppsHelper;
1002     private final AppDataHelper mAppDataHelper;
1003     @NonNull private final InstallPackageHelper mInstallPackageHelper;
1004     private final PreferredActivityHelper mPreferredActivityHelper;
1005     private final ResolveIntentHelper mResolveIntentHelper;
1006     private final DexOptHelper mDexOptHelper;
1007     private final SuspendPackageHelper mSuspendPackageHelper;
1008     private final DistractingPackageHelper mDistractingPackageHelper;
1009     private final StorageEventHelper mStorageEventHelper;
1010     private final FreeStorageHelper mFreeStorageHelper;
1011 
1012 
1013     private static final boolean ENABLE_BOOST = false;
1014 
1015     private static ThreadPriorityBooster sThreadPriorityBooster = new ThreadPriorityBooster(
1016             Process.THREAD_PRIORITY_FOREGROUND, LockGuard.INDEX_PACKAGES);
1017 
1018     /**
1019      * Boost the priority of the thread before holding PM traced lock.
1020      * @hide
1021      */
boostPriorityForPackageManagerTracedLockedSection()1022     public static void boostPriorityForPackageManagerTracedLockedSection() {
1023         if (ENABLE_BOOST) {
1024             sThreadPriorityBooster.boost();
1025         }
1026     }
1027 
1028 
1029     /**
1030      * Restore the priority of the thread after release the PM traced lock.
1031      * @hide
1032      */
resetPriorityAfterPackageManagerTracedLockedSection()1033     public static void resetPriorityAfterPackageManagerTracedLockedSection() {
1034         if (ENABLE_BOOST) {
1035             sThreadPriorityBooster.reset();
1036         }
1037     }
1038 
1039     /**
1040      * Invalidate the package info cache, which includes updating the cached computer.
1041      * @hide
1042      */
invalidatePackageInfoCache()1043     public static void invalidatePackageInfoCache() {
1044         PackageManager.invalidatePackageInfoCache();
1045         onChanged();
1046     }
1047 
1048     private final Watcher mWatcher = new Watcher() {
1049             @Override
1050                        public void onChange(@Nullable Watchable what) {
1051                 PackageManagerService.onChange(what);
1052             }
1053         };
1054 
1055     /**
1056      * A Snapshot is a subset of PackageManagerService state.  A snapshot is either live
1057      * or snapped.  Live snapshots directly reference PackageManagerService attributes.
1058      * Snapped snapshots contain deep copies of the attributes.
1059      */
1060     class Snapshot {
1061         public static final int LIVE = 1;
1062         public static final int SNAPPED = 2;
1063 
1064         public final Settings settings;
1065         public final WatchedSparseIntArray isolatedOwners;
1066         public final WatchedArrayMap<String, AndroidPackage> packages;
1067         public final WatchedArrayMap<ComponentName, ParsedInstrumentation> instrumentation;
1068         public final WatchedSparseBooleanArray webInstantAppsDisabled;
1069         public final ComponentName resolveComponentName;
1070         public final ActivityInfo resolveActivity;
1071         public final ActivityInfo instantAppInstallerActivity;
1072         public final ResolveInfo instantAppInstallerInfo;
1073         public final InstantAppRegistry instantAppRegistry;
1074         public final ApplicationInfo androidApplication;
1075         public final String appPredictionServicePackage;
1076         public final AppsFilterSnapshot appsFilter;
1077         public final ComponentResolverApi componentResolver;
1078         public final PackageManagerService service;
1079         public final WatchedArrayMap<String, Integer> frozenPackages;
1080         public final SharedLibrariesRead sharedLibraries;
1081 
Snapshot(int type)1082         Snapshot(int type) {
1083             if (type == Snapshot.SNAPPED) {
1084                 settings = mSettings.snapshot();
1085                 isolatedOwners = mIsolatedOwnersSnapshot.snapshot();
1086                 packages = mPackagesSnapshot.snapshot();
1087                 instrumentation = mInstrumentationSnapshot.snapshot();
1088                 resolveComponentName = mResolveComponentName == null
1089                         ? null : mResolveComponentName.clone();
1090                 resolveActivity = new ActivityInfo(mResolveActivity);
1091                 instantAppInstallerActivity =
1092                         (mInstantAppInstallerActivity == null)
1093                         ? null
1094                         : new ActivityInfo(mInstantAppInstallerActivity);
1095                 instantAppInstallerInfo = new ResolveInfo(mInstantAppInstallerInfo);
1096                 webInstantAppsDisabled = mWebInstantAppsDisabled.snapshot();
1097                 instantAppRegistry = mInstantAppRegistry.snapshot();
1098                 androidApplication =
1099                         (mAndroidApplication == null)
1100                         ? null
1101                         : new ApplicationInfo(mAndroidApplication);
1102                 appPredictionServicePackage = mAppPredictionServicePackage;
1103                 appsFilter = mAppsFilter.snapshot();
1104                 componentResolver = mComponentResolver.snapshot();
1105                 frozenPackages = mFrozenPackagesSnapshot.snapshot();
1106                 sharedLibraries = mSharedLibraries.snapshot();
1107             } else if (type == Snapshot.LIVE) {
1108                 settings = mSettings;
1109                 isolatedOwners = mIsolatedOwners;
1110                 packages = mPackages;
1111                 instrumentation = mInstrumentation;
1112                 resolveComponentName = mResolveComponentName;
1113                 resolveActivity = mResolveActivity;
1114                 instantAppInstallerActivity = mInstantAppInstallerActivity;
1115                 instantAppInstallerInfo = mInstantAppInstallerInfo;
1116                 webInstantAppsDisabled = mWebInstantAppsDisabled;
1117                 instantAppRegistry = mInstantAppRegistry;
1118                 androidApplication = mAndroidApplication;
1119                 appPredictionServicePackage = mAppPredictionServicePackage;
1120                 appsFilter = mAppsFilter;
1121                 componentResolver = mComponentResolver;
1122                 frozenPackages = mFrozenPackages;
1123                 sharedLibraries = mSharedLibraries;
1124             } else {
1125                 throw new IllegalArgumentException();
1126             }
1127             service = PackageManagerService.this;
1128         }
1129     }
1130 
1131     // Compute read-only functions, based on live data.  This attribute may be modified multiple
1132     // times during the PackageManagerService constructor but it should not be modified thereafter.
1133     private ComputerLocked mLiveComputer;
1134 
1135     private static final AtomicReference<Computer> sSnapshot = new AtomicReference<>();
1136 
1137     // If this differs from Computer#getVersion, the snapshot is invalid (stale).
1138     private static final AtomicInteger sSnapshotPendingVersion = new AtomicInteger(1);
1139 
1140     /**
1141      * This lock is used to make reads from {@link #sSnapshotPendingVersion} and
1142      * {@link #sSnapshot} atomic inside {@code snapshotComputer()} when the versions mismatch.
1143      * This lock is not meant to be used outside that method. This lock must be taken before
1144      * {@link #mLock} is taken.
1145      */
1146     private final Object mSnapshotLock = new Object();
1147 
1148     /**
1149      * The snapshot statistics.  These are collected to track performance and to identify
1150      * situations in which the snapshots are misbehaving.
1151      */
1152     @Nullable
1153     private final SnapshotStatistics mSnapshotStatistics;
1154 
1155     /**
1156      * Return the cached computer.  The method will rebuild the cached computer if necessary.
1157      * The live computer will be returned if snapshots are disabled.
1158      */
1159     @VisibleForTesting(visibility = Visibility.PACKAGE)
1160     @NonNull
snapshotComputer()1161     public Computer snapshotComputer() {
1162         return snapshotComputer(true /*allowLiveComputer*/);
1163     }
1164 
1165     /**
1166      * This method should only ever be called from {@link PackageManagerLocal#snapshot()}.
1167      *
1168      * @param allowLiveComputer Whether to allow a live computer instance based on caller {@link
1169      *                          #mLock} hold state. In certain cases, like for {@link
1170      *                          PackageManagerLocal} API, it must be enforced that the caller gets
1171      *                          a snapshot at time, and never the live variant.
1172      * @deprecated Use {@link #snapshotComputer()}
1173      */
1174     @Deprecated
1175     @NonNull
snapshotComputer(boolean allowLiveComputer)1176     public Computer snapshotComputer(boolean allowLiveComputer) {
1177         var isHoldingPackageLock = Thread.holdsLock(mLock);
1178         if (allowLiveComputer) {
1179             if (isHoldingPackageLock) {
1180                 // If the current thread holds mLock then it may have modified state but not
1181                 // yet invalidated the snapshot.  Always give the thread the live computer.
1182                 return mLiveComputer;
1183             }
1184         }
1185 
1186         var oldSnapshot = sSnapshot.get();
1187         var pendingVersion = sSnapshotPendingVersion.get();
1188 
1189         if (oldSnapshot != null && oldSnapshot.getVersion() == pendingVersion) {
1190             return oldSnapshot.use();
1191         }
1192 
1193         if (isHoldingPackageLock) {
1194             // If the current thread holds mLock then it already has exclusive write access to the
1195             // two snapshot fields, and we can just go ahead and rebuild the snapshot.
1196             @SuppressWarnings("GuardedBy")
1197             var newSnapshot = rebuildSnapshot(oldSnapshot, pendingVersion);
1198             sSnapshot.set(newSnapshot);
1199             return newSnapshot.use();
1200         }
1201 
1202         synchronized (mSnapshotLock) {
1203             // Re-capture pending version in case a new invalidation occurred since last check
1204             var rebuildSnapshot = sSnapshot.get();
1205             var rebuildVersion = sSnapshotPendingVersion.get();
1206 
1207             // Check the versions again while the lock is held, in case the rebuild time caused
1208             // multiple threads to wait on the snapshot lock. When the first thread finishes
1209             // a rebuild, the snapshot is now valid and the other waiting threads can use it
1210             // without kicking off their own rebuilds.
1211             if (rebuildSnapshot != null && rebuildSnapshot.getVersion() == rebuildVersion) {
1212                 return rebuildSnapshot.use();
1213             }
1214 
1215             synchronized (mLock) {
1216                 // Fetch version one last time to ensure that the rebuilt snapshot matches
1217                 // the latest invalidation, which could have come in between entering the
1218                 // SnapshotLock and mLock sync blocks.
1219                 rebuildSnapshot = sSnapshot.get();
1220                 rebuildVersion = sSnapshotPendingVersion.get();
1221                 if (rebuildSnapshot != null && rebuildSnapshot.getVersion() == rebuildVersion) {
1222                     return rebuildSnapshot.use();
1223                 }
1224 
1225                 // Build the snapshot for this version
1226                 var newSnapshot = rebuildSnapshot(rebuildSnapshot, rebuildVersion);
1227                 sSnapshot.set(newSnapshot);
1228                 return newSnapshot.use();
1229             }
1230         }
1231     }
1232 
1233     @GuardedBy("mLock")
rebuildSnapshot(@ullable Computer oldSnapshot, int newVersion)1234     private Computer rebuildSnapshot(@Nullable Computer oldSnapshot, int newVersion) {
1235         var now = SystemClock.currentTimeMicro();
1236         var hits = oldSnapshot == null ? -1 : oldSnapshot.getUsed();
1237         var args = new Snapshot(Snapshot.SNAPPED);
1238         var newSnapshot = new ComputerEngine(args, newVersion);
1239         var done = SystemClock.currentTimeMicro();
1240 
1241         if (mSnapshotStatistics != null) {
1242             mSnapshotStatistics.rebuild(now, done, hits, newSnapshot.getPackageStates().size());
1243         }
1244         return newSnapshot;
1245     }
1246 
1247     /**
1248      * Create a live computer
1249      */
createLiveComputer()1250     private ComputerLocked createLiveComputer() {
1251         return new ComputerLocked(new Snapshot(Snapshot.LIVE));
1252     }
1253 
1254     /**
1255      * This method is called when the state of PackageManagerService changes so as to
1256      * invalidate the current snapshot.
1257      * @param what The {@link Watchable} that reported the change
1258      * @hide
1259      */
onChange(@ullable Watchable what)1260     public static void onChange(@Nullable Watchable what) {
1261         if (TRACE_SNAPSHOTS) {
1262             Log.i(TAG, "snapshot: onChange(" + what + ")");
1263         }
1264         sSnapshotPendingVersion.incrementAndGet();
1265     }
1266 
1267     /**
1268      * Report a locally-detected change to observers.  The <what> parameter is left null,
1269      * but it signifies that the change was detected by PackageManagerService itself.
1270      */
onChanged()1271     static void onChanged() {
1272         onChange(null);
1273     }
1274 
notifyInstallObserver(String packageName, boolean killApp)1275     void notifyInstallObserver(String packageName, boolean killApp) {
1276         final InstallRequest installRequest =
1277                 killApp ? mPendingKillInstallObservers.remove(packageName)
1278                         : mNoKillInstallObservers.remove(packageName);
1279 
1280         if (installRequest != null) {
1281             notifyInstallObserver(installRequest);
1282         }
1283     }
1284 
notifyInstallObserver(InstallRequest request)1285     void notifyInstallObserver(InstallRequest request) {
1286         if (request.getObserver() != null) {
1287             try {
1288                 Bundle extras = extrasForInstallResult(request);
1289                 request.getObserver().onPackageInstalled(request.getName(),
1290                         request.getReturnCode(), request.getReturnMsg(), extras);
1291             } catch (RemoteException e) {
1292                 Slog.i(TAG, "Observer no longer exists.");
1293             }
1294         }
1295     }
1296 
scheduleDeferredNoKillInstallObserver(InstallRequest request)1297     void scheduleDeferredNoKillInstallObserver(InstallRequest request) {
1298         String packageName = request.getPkg().getPackageName();
1299         mNoKillInstallObservers.put(packageName, request);
1300         Message message = mHandler.obtainMessage(DEFERRED_NO_KILL_INSTALL_OBSERVER, packageName);
1301         mHandler.sendMessageDelayed(message, DEFERRED_NO_KILL_INSTALL_OBSERVER_DELAY_MS);
1302     }
1303 
scheduleDeferredNoKillPostDelete(CleanUpArgs args)1304     void scheduleDeferredNoKillPostDelete(CleanUpArgs args) {
1305         Message message = mHandler.obtainMessage(DEFERRED_NO_KILL_POST_DELETE, args);
1306         // If the feature flag is on, retain the old files for a day. Otherwise, delete the old
1307         // files after a few seconds.
1308         long deleteDelayMillis = DEFERRED_NO_KILL_POST_DELETE_DELAY_MS;
1309         if (Flags.improveInstallDontKill()) {
1310             deleteDelayMillis = Binder.withCleanCallingIdentity(() -> {
1311                 return DeviceConfig.getLong(NAMESPACE_PACKAGE_MANAGER_SERVICE,
1312                         /* name= */ PROPERTY_DEFERRED_NO_KILL_POST_DELETE_DELAY_MS_EXTENDED,
1313                         /* defaultValue= */ DEFERRED_NO_KILL_POST_DELETE_DELAY_MS_EXTENDED);
1314             });
1315             Slog.w(TAG, "Delaying the deletion of <" + args.getCodePath() + "> by "
1316                     + deleteDelayMillis + "ms or till the next reboot");
1317         }
1318         mHandler.sendMessageDelayed(message, deleteDelayMillis);
1319     }
1320 
schedulePruneUnusedStaticSharedLibraries(boolean delay)1321     void schedulePruneUnusedStaticSharedLibraries(boolean delay) {
1322         mHandler.removeMessages(PRUNE_UNUSED_STATIC_SHARED_LIBRARIES);
1323         mHandler.sendEmptyMessageDelayed(PRUNE_UNUSED_STATIC_SHARED_LIBRARIES,
1324                 delay ? getPruneUnusedSharedLibrariesDelay() : 0);
1325     }
1326 
scheduleDeferredPendingKillInstallObserver(InstallRequest request)1327     void scheduleDeferredPendingKillInstallObserver(InstallRequest request) {
1328         final String packageName = request.getPkg().getPackageName();
1329         mPendingKillInstallObservers.put(packageName, request);
1330         final Message message = mHandler.obtainMessage(DEFERRED_PENDING_KILL_INSTALL_OBSERVER,
1331                 packageName);
1332         mHandler.sendMessageDelayed(message, DEFERRED_PENDING_KILL_INSTALL_OBSERVER_DELAY_MS);
1333     }
1334 
getPruneUnusedSharedLibrariesDelay()1335     private static long getPruneUnusedSharedLibrariesDelay() {
1336         return SystemProperties.getLong("debug.pm.prune_unused_shared_libraries_delay",
1337                 PRUNE_UNUSED_SHARED_LIBRARIES_DELAY);
1338     }
1339 
1340     /**
1341      * Requests checksums for the APK file.
1342      * See {@link PackageInstaller.Session#requestChecksums} for details.
1343      */
requestFileChecksums(@onNull File file, @NonNull String installerPackageName, @Checksum.TypeMask int optional, @Checksum.TypeMask int required, @Nullable List trustedInstallers, @NonNull IOnChecksumsReadyListener onChecksumsReadyListener)1344     public void requestFileChecksums(@NonNull File file,
1345             @NonNull String installerPackageName, @Checksum.TypeMask int optional,
1346             @Checksum.TypeMask int required, @Nullable List trustedInstallers,
1347             @NonNull IOnChecksumsReadyListener onChecksumsReadyListener)
1348             throws FileNotFoundException {
1349         if (!file.exists()) {
1350             throw new FileNotFoundException(file.getAbsolutePath());
1351         }
1352 
1353         final Executor executor = mInjector.getBackgroundExecutor();
1354         final Handler handler = mInjector.getBackgroundHandler();
1355         final Certificate[] trustedCerts = (trustedInstallers != null) ? decodeCertificates(
1356                 trustedInstallers) : null;
1357 
1358         final List<Pair<String, File>> filesToChecksum = new ArrayList<>(1);
1359         filesToChecksum.add(Pair.create(null, file));
1360 
1361         executor.execute(() -> {
1362             ApkChecksums.Injector injector = new ApkChecksums.Injector(
1363                     () -> mContext,
1364                     () -> handler,
1365                     mInjector::getIncrementalManager,
1366                     () -> mInjector.getLocalService(PackageManagerInternal.class));
1367             ApkChecksums.getChecksums(filesToChecksum, optional, required, installerPackageName,
1368                     trustedCerts, onChecksumsReadyListener, injector);
1369         });
1370     }
1371 
requestChecksumsInternal(@onNull Computer snapshot, @NonNull String packageName, boolean includeSplits, @Checksum.TypeMask int optional, @Checksum.TypeMask int required, @Nullable List trustedInstallers, @NonNull IOnChecksumsReadyListener onChecksumsReadyListener, int userId, @NonNull Executor executor, @NonNull Handler handler)1372     void requestChecksumsInternal(@NonNull Computer snapshot, @NonNull String packageName,
1373             boolean includeSplits, @Checksum.TypeMask int optional, @Checksum.TypeMask int required,
1374             @Nullable List trustedInstallers,
1375             @NonNull IOnChecksumsReadyListener onChecksumsReadyListener, int userId,
1376             @NonNull Executor executor, @NonNull Handler handler) {
1377         Objects.requireNonNull(packageName);
1378         Objects.requireNonNull(onChecksumsReadyListener);
1379         Objects.requireNonNull(executor);
1380         Objects.requireNonNull(handler);
1381 
1382         final ApplicationInfo applicationInfo = snapshot.getApplicationInfoInternal(packageName, 0,
1383                 Binder.getCallingUid(), userId);
1384         if (applicationInfo == null) {
1385             throw new ParcelableException(new PackageManager.NameNotFoundException(packageName));
1386         }
1387 
1388         final InstallSourceInfo installSourceInfo = snapshot.getInstallSourceInfo(packageName,
1389                 userId);
1390         final String installerPackageName;
1391         if (installSourceInfo != null) {
1392             final String initiatingPackageName = installSourceInfo.getInitiatingPackageName();
1393             if (!isInstalledByAdb(initiatingPackageName)) {
1394                 installerPackageName = initiatingPackageName;
1395             } else {
1396                 installerPackageName = installSourceInfo.getInstallingPackageName();
1397             }
1398         } else {
1399             installerPackageName = null;
1400         }
1401 
1402         List<Pair<String, File>> filesToChecksum = new ArrayList<>();
1403 
1404         // Adding base split.
1405         filesToChecksum.add(Pair.create(null, new File(applicationInfo.sourceDir)));
1406 
1407         // Adding other splits.
1408         if (includeSplits && applicationInfo.splitNames != null) {
1409             for (int i = 0, size = applicationInfo.splitNames.length; i < size; ++i) {
1410                 filesToChecksum.add(Pair.create(applicationInfo.splitNames[i],
1411                         new File(applicationInfo.splitSourceDirs[i])));
1412             }
1413         }
1414 
1415         final Certificate[] trustedCerts = (trustedInstallers != null) ? decodeCertificates(
1416                 trustedInstallers) : null;
1417 
1418         executor.execute(() -> {
1419             ApkChecksums.Injector injector = new ApkChecksums.Injector(
1420                     () -> mContext,
1421                     () -> handler,
1422                     mInjector::getIncrementalManager,
1423                     () -> mInjector.getLocalService(PackageManagerInternal.class));
1424             ApkChecksums.getChecksums(filesToChecksum, optional, required, installerPackageName,
1425                     trustedCerts, onChecksumsReadyListener, injector);
1426         });
1427     }
1428 
decodeCertificates(@onNull List certs)1429     private static @NonNull Certificate[] decodeCertificates(@NonNull List certs) {
1430         try {
1431             final CertificateFactory cf = CertificateFactory.getInstance("X.509");
1432             final Certificate[] result = new Certificate[certs.size()];
1433             for (int i = 0, size = certs.size(); i < size; ++i) {
1434                 final InputStream is = new ByteArrayInputStream((byte[]) certs.get(i));
1435                 final X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
1436                 result[i] = cert;
1437             }
1438             return result;
1439         } catch (CertificateException e) {
1440             throw ExceptionUtils.propagate(e);
1441         }
1442     }
1443 
extrasForInstallResult(InstallRequest request)1444     private static Bundle extrasForInstallResult(InstallRequest request) {
1445         Bundle extras = null;
1446         switch (request.getReturnCode()) {
1447             case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1448                 extras = new Bundle();
1449                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1450                         request.getOrigPermission());
1451                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1452                         request.getOrigPackage());
1453                 break;
1454             }
1455             case PackageManager.INSTALL_SUCCEEDED: {
1456                 extras = new Bundle();
1457                 extras.putBoolean(Intent.EXTRA_REPLACING,
1458                         request.getRemovedInfo() != null
1459                                 && request.getRemovedInfo().mRemovedPackage != null);
1460                 break;
1461             }
1462         }
1463         if (!request.getWarnings().isEmpty()) {
1464             extras.putStringArrayList(PackageInstaller.EXTRA_WARNINGS, request.getWarnings());
1465         }
1466         return extras;
1467     }
1468 
getArchivedPackageInternal(@onNull String packageName, int userId)1469     ArchivedPackageParcel getArchivedPackageInternal(@NonNull String packageName, int userId) {
1470         Objects.requireNonNull(packageName);
1471         int binderUid = Binder.getCallingUid();
1472 
1473         Computer snapshot = snapshotComputer();
1474         snapshot.enforceCrossUserPermission(binderUid, userId, true, true,
1475                 "getArchivedPackage");
1476 
1477         ArchivedPackageParcel archPkg = new ArchivedPackageParcel();
1478         archPkg.packageName = packageName;
1479 
1480         ArchiveState archiveState;
1481         synchronized (mLock) {
1482             PackageSetting ps = mSettings.getPackageLPr(packageName);
1483             if (ps == null || snapshot.shouldFilterApplication(ps, binderUid, userId)) {
1484                 return null;
1485             }
1486             var psi = ps.getUserStateOrDefault(userId);
1487             archiveState = psi.getArchiveState();
1488             if (archiveState == null && !psi.isInstalled()) {
1489                 return null;
1490             }
1491 
1492             archPkg.signingDetails = ps.getSigningDetails();
1493 
1494             long longVersionCode = ps.getVersionCode();
1495             archPkg.versionCodeMajor = (int) (longVersionCode >> 32);
1496             archPkg.versionCode = (int) longVersionCode;
1497 
1498             archPkg.targetSdkVersion = ps.getTargetSdkVersion();
1499 
1500             // These get translated in flags important for user data management.
1501             archPkg.defaultToDeviceProtectedStorage = String.valueOf(
1502                     ps.isDefaultToDeviceProtectedStorage());
1503             archPkg.requestLegacyExternalStorage = String.valueOf(
1504                     ps.isRequestLegacyExternalStorage());
1505             archPkg.userDataFragile = String.valueOf(ps.isUserDataFragile());
1506         }
1507 
1508         try {
1509             if (archiveState != null) {
1510                 archPkg.archivedActivities = PackageArchiver.createArchivedActivities(
1511                         archiveState);
1512             } else {
1513                 final int iconSize = mContext.getSystemService(
1514                         ActivityManager.class).getLauncherLargeIconSize();
1515 
1516                 var mainActivities =
1517                         mInstallerService.mPackageArchiver.getLauncherActivityInfos(packageName,
1518                                 userId);
1519                 archPkg.archivedActivities = PackageArchiver.createArchivedActivities(
1520                         mainActivities, iconSize);
1521             }
1522         } catch (Exception e) {
1523             throw new IllegalArgumentException("Package does not have a main activity", e);
1524         }
1525 
1526         return archPkg;
1527     }
1528 
markPackageAsArchivedIfNeeded(PackageSetting pkgSetting, ArchivedPackageParcel archivePackage, SparseArray<String> responsibleInstallerTitles, int[] userIds)1529     void markPackageAsArchivedIfNeeded(PackageSetting pkgSetting,
1530             ArchivedPackageParcel archivePackage, SparseArray<String> responsibleInstallerTitles,
1531             int[] userIds) {
1532         if (pkgSetting == null || archivePackage == null
1533                 || archivePackage.archivedActivities == null
1534                 || responsibleInstallerTitles == null
1535                 || userIds == null || userIds.length == 0) {
1536             return;
1537         }
1538 
1539         // Initialize all necessary settings for archival installation.
1540         pkgSetting
1541                 // No package.
1542                 .setPkg(null)
1543                 // Mark for later restore.
1544                 .setPendingRestore(true);
1545         for (int userId : userIds) {
1546             // Unmark "installed" for all users.
1547             pkgSetting
1548                     .modifyUserState(userId)
1549                     .setInstalled(false);
1550         }
1551 
1552         String responsibleInstallerPackage = PackageArchiver.getResponsibleInstallerPackage(
1553                 pkgSetting);
1554         // TODO(b/278553670) Check if responsibleInstallerPackage supports unarchival.
1555         if (TextUtils.isEmpty(responsibleInstallerPackage)) {
1556             Slog.e(TAG, "Can't create archive state: responsible installer is empty");
1557             return;
1558         }
1559         for (int userId : userIds) {
1560             var archiveState = mInstallerService.mPackageArchiver.createArchiveState(
1561                     archivePackage, userId, responsibleInstallerPackage,
1562                     responsibleInstallerTitles.get(userId));
1563             if (archiveState != null) {
1564                 pkgSetting
1565                     .modifyUserState(userId)
1566                     .setArchiveState(archiveState);
1567             }
1568         }
1569     }
1570 
1571 
scheduleWriteSettings()1572     void scheduleWriteSettings() {
1573         // We normally invalidate when we write settings, but in cases where we delay and
1574         // coalesce settings writes, this strategy would have us invalidate the cache too late.
1575         // Invalidating on schedule addresses this problem.
1576         invalidatePackageInfoCache();
1577         if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1578             mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1579         }
1580     }
1581 
scheduleWritePackageListLocked(int userId)1582     void scheduleWritePackageListLocked(int userId) {
1583         invalidatePackageInfoCache();
1584         if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
1585             Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
1586             msg.arg1 = userId;
1587             mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
1588         }
1589     }
1590 
scheduleWritePackageRestrictions(UserHandle user)1591     void scheduleWritePackageRestrictions(UserHandle user) {
1592         final int userId = user == null ? USER_ALL : user.getIdentifier();
1593         scheduleWritePackageRestrictions(userId);
1594     }
1595 
scheduleWritePackageRestrictions(@anBeALL @serIdInt int userId)1596     void scheduleWritePackageRestrictions(@CanBeALL @UserIdInt int userId) {
1597         invalidatePackageInfoCache();
1598         if (userId == USER_ALL) {
1599             synchronized (mDirtyUsers) {
1600                 for (int aUserId : mUserManager.getUserIds()) {
1601                     mDirtyUsers.add(aUserId);
1602                 }
1603             }
1604         } else {
1605             if (!mUserManager.exists(userId)) {
1606                 return;
1607             }
1608             synchronized (mDirtyUsers) {
1609                 mDirtyUsers.add(userId);
1610             }
1611         }
1612         if (!mBackgroundHandler.hasMessages(WRITE_DIRTY_PACKAGE_RESTRICTIONS)) {
1613             mBackgroundHandler.sendMessageDelayed(
1614                     mBackgroundHandler.obtainMessage(WRITE_DIRTY_PACKAGE_RESTRICTIONS, this),
1615                     WRITE_SETTINGS_DELAY);
1616         }
1617     }
1618 
writePendingRestrictions()1619     void writePendingRestrictions() {
1620         final Integer[] dirtyUsers;
1621         synchronized (mLock) {
1622             mBackgroundHandler.removeMessages(WRITE_DIRTY_PACKAGE_RESTRICTIONS);
1623             synchronized (mDirtyUsers) {
1624                 if (mDirtyUsers.isEmpty()) {
1625                     return;
1626                 }
1627                 dirtyUsers = mDirtyUsers.toArray(Integer[]::new);
1628                 mDirtyUsers.clear();
1629             }
1630         }
1631         mSettings.writePackageRestrictions(dirtyUsers);
1632     }
1633 
writeSettings(boolean sync)1634     void writeSettings(boolean sync) {
1635         synchronized (mLock) {
1636             mHandler.removeMessages(WRITE_SETTINGS);
1637             mBackgroundHandler.removeMessages(WRITE_DIRTY_PACKAGE_RESTRICTIONS);
1638             writeSettingsLPrTEMP(sync);
1639             synchronized (mDirtyUsers) {
1640                 mDirtyUsers.clear();
1641             }
1642         }
1643     }
1644 
writePackageList(int userId)1645     void writePackageList(int userId) {
1646         synchronized (mLock) {
1647             mHandler.removeMessages(WRITE_PACKAGE_LIST);
1648             mSettings.writePackageListLPr(userId);
1649         }
1650     }
1651 
1652     private static final Handler.Callback BACKGROUND_HANDLER_CALLBACK = new Handler.Callback() {
1653         @Override
1654         public boolean handleMessage(@NonNull Message msg) {
1655             switch (msg.what) {
1656                 case WRITE_DIRTY_PACKAGE_RESTRICTIONS: {
1657                     PackageManagerService pm = (PackageManagerService) msg.obj;
1658                     pm.writePendingRestrictions();
1659                     return true;
1660                 }
1661                 case WRITE_USER_PACKAGE_RESTRICTIONS: {
1662                     final Runnable r = (Runnable) msg.obj;
1663                     r.run();
1664                     return true;
1665                 }
1666             }
1667             return false;
1668         }
1669     };
1670 
1671     /** Starts PackageManagerService. */
main(Context context, Installer installer, @NonNull DomainVerificationService domainVerificationService, boolean factoryTest)1672     public static PackageManagerService main(Context context,
1673             Installer installer, @NonNull DomainVerificationService domainVerificationService,
1674             boolean factoryTest) {
1675         // Self-check for initial settings.
1676         PackageManagerServiceCompilerMapping.checkProperties();
1677         final TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing",
1678                 Trace.TRACE_TAG_PACKAGE_MANAGER);
1679         t.traceBegin("create package manager");
1680         final PackageManagerTracedLock lock = new PackageManagerTracedLock("mLock");
1681         final PackageManagerTracedLock installLock = new PackageManagerTracedLock("mInstallLock");
1682 
1683         HandlerThread backgroundThread = new ServiceThread("PackageManagerBg",
1684                 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1685         backgroundThread.start();
1686         Handler backgroundHandler = new Handler(backgroundThread.getLooper(),
1687                 BACKGROUND_HANDLER_CALLBACK);
1688 
1689         PackageManagerServiceInjector injector = new PackageManagerServiceInjector(
1690                 context, lock, installer, installLock, new PackageAbiHelperImpl(),
1691                 backgroundHandler,
1692                 SYSTEM_PARTITIONS,
1693                 (i, pm) -> new ComponentResolver(i.getUserManagerService(), pm.mUserNeedsBadging),
1694                 (i, pm) -> PermissionManagerService.create(context,
1695                         i.getSystemConfig().getAvailableFeatures()),
1696                 (i, pm) -> LocalServices.getService(AppOpsManagerInternal.class),
1697                 (i, pm) -> new UserManagerService(context, pm,
1698                         new UserDataPreparer(installer, installLock, context), lock),
1699                 (i, pm) -> new Settings(Environment.getDataDirectory(),
1700                         RuntimePermissionsPersistence.createInstance(),
1701                         i.getPermissionManagerServiceInternal(),
1702                         domainVerificationService, backgroundHandler,
1703                         lock),
1704                 (i, pm) -> AppsFilterImpl.create(i,
1705                         i.getLocalService(PackageManagerInternal.class)),
1706                 (i, pm) -> (PlatformCompat) ServiceManager.getService("platform_compat"),
1707                 (i, pm) -> SystemConfig.getInstance(),
1708                 (i, pm) -> new PackageDexOptimizer(i.getInstaller(), i.getInstallLock(),
1709                         i.getContext(), "*dexopt*"),
1710                 (i, pm) -> new DexManager(i.getContext(), i.getPackageDexOptimizer(),
1711                         i.getDynamicCodeLogger()),
1712                 (i, pm) -> new DynamicCodeLogger(i.getInstaller()),
1713                 (i, pm) -> new ArtManagerService(i.getContext(), i.getInstaller(),
1714                         i.getInstallLock()),
1715                 (i, pm) -> ApexManager.getInstance(),
1716                 (i, pm) -> (IncrementalManager)
1717                         i.getContext().getSystemService(Context.INCREMENTAL_SERVICE),
1718                 (i, pm) -> new DefaultAppProvider(() -> context.getSystemService(RoleManager.class),
1719                         () -> LocalServices.getService(UserManagerInternal.class)),
1720                 (i, pm) -> new DisplayMetrics(),
1721                 (i, pm) -> new PackageParser2(pm.mSeparateProcesses, i.getDisplayMetrics(),
1722                         new PackageCacher(pm.mCacheDir, pm.mPackageParserCallback),
1723                         pm.mPackageParserCallback) /* scanningCachingPackageParserProducer */,
1724                 (i, pm) -> new PackageParser2(pm.mSeparateProcesses, i.getDisplayMetrics(), null,
1725                         pm.mPackageParserCallback) /* scanningPackageParserProducer */,
1726                 (i, pm) -> new PackageParser2(pm.mSeparateProcesses, i.getDisplayMetrics(), null,
1727                         pm.mPackageParserCallback) /* preparingPackageParserProducer */,
1728                 // Prepare a supplier of package parser for the staging manager to parse apex file
1729                 // during the staging installation.
1730                 (i, pm) -> new PackageInstallerService(
1731                         i.getContext(), pm, i::getScanningPackageParser),
1732                 (i, pm, cn) -> new InstantAppResolverConnection(
1733                         i.getContext(), cn, Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE),
1734                 (i, pm) -> new ModuleInfoProvider(i.getContext()),
1735                 (i, pm) -> LegacyPermissionManagerService.create(i.getContext()),
1736                 (i, pm) -> domainVerificationService,
1737                 (i, pm) -> {
1738                     HandlerThread thread = new ServiceThread(TAG,
1739                             Process.THREAD_PRIORITY_DEFAULT, true /*allowIo*/);
1740                     thread.start();
1741                     return new PackageHandler(thread.getLooper(), pm);
1742                 },
1743                 new DefaultSystemWrapper(),
1744                 LocalServices::getService,
1745                 context::getSystemService,
1746                 (i, pm) -> IBackupManager.Stub.asInterface(ServiceManager.getService(
1747                         Context.BACKUP_SERVICE)),
1748                 (i, pm) -> new SharedLibrariesImpl(pm, i),
1749                 (i, pm) -> new CrossProfileIntentFilterHelper(i.getSettings(),
1750                         i.getUserManagerService(), i.getLock(), i.getUserManagerInternal(),
1751                         context),
1752                 (i, pm) -> new UpdateOwnershipHelper(),
1753                 (i, pm) -> new PackageMonitorCallbackHelper());
1754 
1755         if (Build.VERSION.SDK_INT <= 0) {
1756             Slog.w(TAG, "**** ro.build.version.sdk not set!");
1757         }
1758 
1759         PackageManagerService m = new PackageManagerService(injector, factoryTest,
1760                 PackagePartitions.FINGERPRINT, Build.IS_ENG, Build.IS_USERDEBUG,
1761                 Build.VERSION.SDK_INT, Build.VERSION.INCREMENTAL);
1762         t.traceEnd(); // "create package manager"
1763 
1764         final CompatChange.ChangeListener selinuxChangeListener = packageName -> {
1765             synchronized (m.mInstallLock) {
1766                 final Computer snapshot = m.snapshotComputer();
1767                 final PackageStateInternal packageState =
1768                         snapshot.getPackageStateInternal(packageName);
1769                 if (packageState == null) {
1770                     Slog.e(TAG, "Failed to find package setting " + packageName);
1771                     return;
1772                 }
1773                 AndroidPackage pkg = packageState.getPkg();
1774                 SharedUserApi sharedUser = snapshot.getSharedUser(
1775                         packageState.getSharedUserAppId());
1776                 String oldSeInfo = packageState.getSeInfo();
1777 
1778                 if (pkg == null) {
1779                     Slog.e(TAG, "Failed to find package " + packageName);
1780                     return;
1781                 }
1782                 final String newSeInfo = SELinuxMMAC.getSeInfo(packageState, pkg, sharedUser,
1783                         m.mInjector.getCompatibility());
1784 
1785                 if (!newSeInfo.equals(oldSeInfo)) {
1786                     Slog.i(TAG, "Updating seInfo for package " + packageName + " from: "
1787                             + oldSeInfo + " to: " + newSeInfo);
1788                     m.commitPackageStateMutation(null, packageName,
1789                             state -> state.setOverrideSeInfo(newSeInfo));
1790                     m.mAppDataHelper.prepareAppDataAfterInstallLIF(pkg);
1791                 }
1792             }
1793         };
1794 
1795         injector.getCompatibility().registerListener(SELinuxMMAC.SELINUX_LATEST_CHANGES,
1796                 selinuxChangeListener);
1797         injector.getCompatibility().registerListener(SELinuxMMAC.SELINUX_R_CHANGES,
1798                 selinuxChangeListener);
1799 
1800         m.installAllowlistedSystemPackages();
1801         IPackageManagerImpl iPackageManager = m.new IPackageManagerImpl();
1802         ServiceManager.addService("package", iPackageManager);
1803         final PackageManagerNative pmn = new PackageManagerNative(m);
1804         ServiceManager.addService("package_native", pmn);
1805         return m;
1806     }
1807 
1808     /** Install/uninstall system packages for all users based on their user-type, as applicable. */
installAllowlistedSystemPackages()1809     private void installAllowlistedSystemPackages() {
1810         if (mUserManager.installWhitelistedSystemPackages(isFirstBoot(), isDeviceUpgrading(),
1811                 mExistingPackages)) {
1812             scheduleWritePackageRestrictions(USER_ALL);
1813             scheduleWriteSettings();
1814         }
1815     }
1816 
1817     // Link watchables to the class
1818     @SuppressWarnings("GuardedBy")
registerObservers(boolean verify)1819     private void registerObservers(boolean verify) {
1820         // Null check to handle nullable test parameters
1821         if (mPackages != null) {
1822             mPackages.registerObserver(mWatcher);
1823         }
1824         if (mSharedLibraries != null) {
1825             mSharedLibraries.registerObserver(mWatcher);
1826         }
1827         if (mInstrumentation != null) {
1828             mInstrumentation.registerObserver(mWatcher);
1829         }
1830         if (mWebInstantAppsDisabled != null) {
1831             mWebInstantAppsDisabled.registerObserver(mWatcher);
1832         }
1833         if (mAppsFilter != null) {
1834             mAppsFilter.registerObserver(mWatcher);
1835         }
1836         if (mInstantAppRegistry != null) {
1837             mInstantAppRegistry.registerObserver(mWatcher);
1838         }
1839         if (mSettings != null) {
1840             mSettings.registerObserver(mWatcher);
1841         }
1842         if (mIsolatedOwners != null) {
1843             mIsolatedOwners.registerObserver(mWatcher);
1844         }
1845         if (mComponentResolver != null) {
1846             mComponentResolver.registerObserver(mWatcher);
1847         }
1848         if (mFrozenPackages != null) {
1849             mFrozenPackages.registerObserver(mWatcher);
1850         }
1851         if (verify) {
1852             // If neither "build" attribute is true then this may be a mockito test,
1853             // and verification can fail as a false positive.
1854             Watchable.verifyWatchedAttributes(this, mWatcher, !(mIsEngBuild || mIsUserDebugBuild));
1855         }
1856     }
1857 
1858     /**
1859      * An extremely minimal constructor designed to start up a PackageManagerService instance for
1860      * testing.
1861      *
1862      * It is assumed that all methods under test will mock the internal fields and thus
1863      * none of the initialization is needed.
1864      */
1865     @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE)
PackageManagerService(@onNull PackageManagerServiceInjector injector, @NonNull PackageManagerServiceTestParams testParams)1866     public PackageManagerService(@NonNull PackageManagerServiceInjector injector,
1867             @NonNull PackageManagerServiceTestParams testParams) {
1868         mInjector = injector;
1869         mInjector.bootstrap(this);
1870         mAppsFilter = injector.getAppsFilter();
1871         mComponentResolver = injector.getComponentResolver();
1872         mContext = injector.getContext();
1873         mInstaller = injector.getInstaller();
1874         mInstallLock = injector.getInstallLock();
1875         mLock = injector.getLock();
1876         mPackageStateWriteLock = mLock;
1877         mPermissionManager = injector.getPermissionManagerServiceInternal();
1878         mSettings = injector.getSettings();
1879         mUserManager = injector.getUserManagerService();
1880         mUserNeedsBadging = new UserNeedsBadgingCache(mUserManager);
1881         mDomainVerificationManager = injector.getDomainVerificationManagerInternal();
1882         mHandler = injector.getHandler();
1883         mBackgroundHandler = injector.getBackgroundHandler();
1884         mSharedLibraries = injector.getSharedLibrariesImpl();
1885 
1886         mApexManager = testParams.apexManager;
1887         mArtManagerService = testParams.artManagerService;
1888         mAvailableFeatures = testParams.availableFeatures;
1889         mDefParseFlags = testParams.defParseFlags;
1890         mDefaultAppProvider = testParams.defaultAppProvider;
1891         mLegacyPermissionManager = testParams.legacyPermissionManagerInternal;
1892         mDexManager = testParams.dexManager;
1893         mDynamicCodeLogger = testParams.dynamicCodeLogger;
1894         mFactoryTest = testParams.factoryTest;
1895         mIncrementalManager = testParams.incrementalManager;
1896         mInstallerService = testParams.installerService;
1897         mInstantAppRegistry = testParams.instantAppRegistry;
1898         mChangedPackagesTracker = testParams.changedPackagesTracker;
1899         mInstantAppResolverConnection = testParams.instantAppResolverConnection;
1900         mInstantAppResolverSettingsComponent = testParams.instantAppResolverSettingsComponent;
1901         mIsPreNMR1Upgrade = testParams.isPreNmr1Upgrade;
1902         mIsPreQUpgrade = testParams.isPreQupgrade;
1903         mPriorSdkVersion = testParams.priorSdkVersion;
1904         mIsUpgrade = testParams.isUpgrade;
1905         mMetrics = testParams.Metrics;
1906         mModuleInfoProvider = testParams.moduleInfoProvider;
1907         mMoveCallbacks = testParams.moveCallbacks;
1908         mOverlayConfig = testParams.overlayConfig;
1909         mPackageDexOptimizer = testParams.packageDexOptimizer;
1910         mPackageParserCallback = testParams.packageParserCallback;
1911         mPendingBroadcasts = testParams.pendingPackageBroadcasts;
1912         mTestUtilityService = testParams.testUtilityService;
1913         mProcessLoggingHandler = testParams.processLoggingHandler;
1914         mProtectedPackages = testParams.protectedPackages;
1915         mSeparateProcesses = testParams.separateProcesses;
1916         mRequiredVerifierPackages = testParams.requiredVerifierPackages;
1917         mRequiredInstallerPackage = testParams.requiredInstallerPackage;
1918         mRequiredUninstallerPackage = testParams.requiredUninstallerPackage;
1919         mRequiredPermissionControllerPackage = testParams.requiredPermissionControllerPackage;
1920         mSetupWizardPackage = testParams.setupWizardPackage;
1921         mStorageManagerPackage = testParams.storageManagerPackage;
1922         mDefaultTextClassifierPackage = testParams.defaultTextClassifierPackage;
1923         mSystemTextClassifierPackageName = testParams.systemTextClassifierPackage;
1924         mRetailDemoPackage = testParams.retailDemoPackage;
1925         mRecentsPackage = testParams.recentsPackage;
1926         mAmbientContextDetectionPackage = testParams.ambientContextDetectionPackage;
1927         mWearableSensingPackage = testParams.wearableSensingPackage;
1928         mConfiguratorPackage = testParams.configuratorPackage;
1929         mAppPredictionServicePackage = testParams.appPredictionServicePackage;
1930         mIncidentReportApproverPackage = testParams.incidentReportApproverPackage;
1931         mServicesExtensionPackageName = testParams.servicesExtensionPackageName;
1932         mSharedSystemSharedLibraryPackageName = testParams.sharedSystemSharedLibraryPackageName;
1933         mOverlayConfigSignaturePackage = testParams.overlayConfigSignaturePackage;
1934         mResolveComponentName = testParams.resolveComponentName;
1935         mRequiredSdkSandboxPackage = testParams.requiredSdkSandboxPackage;
1936         mInitialNonStoppedSystemPackages = testParams.initialNonStoppedSystemPackages;
1937         mShouldStopSystemPackagesByDefault = testParams.shouldStopSystemPackagesByDefault;
1938 
1939         mLiveComputer = createLiveComputer();
1940         mSnapshotStatistics = null;
1941 
1942         mPackages.putAll(testParams.packages);
1943         mFreeStorageHelper = testParams.freeStorageHelper;
1944         mSdkVersion = testParams.sdkVersion;
1945         mAppInstallDir = testParams.appInstallDir;
1946         mIsEngBuild = testParams.isEngBuild;
1947         mIsUserDebugBuild = testParams.isUserDebugBuild;
1948         mIncrementalVersion = testParams.incrementalVersion;
1949         mDomainVerificationConnection = new DomainVerificationConnection(this);
1950 
1951         mBroadcastHelper = testParams.broadcastHelper;
1952         mAppDataHelper = testParams.appDataHelper;
1953         mInstallPackageHelper = testParams.installPackageHelper;
1954         mRemovePackageHelper = testParams.removePackageHelper;
1955         mInitAppsHelper = testParams.initAndSystemPackageHelper;
1956         mDeletePackageHelper = testParams.deletePackageHelper;
1957         mPreferredActivityHelper = testParams.preferredActivityHelper;
1958         mResolveIntentHelper = testParams.resolveIntentHelper;
1959         mDexOptHelper = testParams.dexOptHelper;
1960         mSuspendPackageHelper = testParams.suspendPackageHelper;
1961         mDistractingPackageHelper = testParams.distractingPackageHelper;
1962 
1963         mSharedLibraries.setDeletePackageHelper(mDeletePackageHelper);
1964 
1965         mStorageEventHelper = testParams.storageEventHelper;
1966         mPackageMonitorCallbackHelper = testParams.packageMonitorCallbackHelper;
1967 
1968         registerObservers(false);
1969         invalidatePackageInfoCache();
1970     }
1971 
PackageManagerService(PackageManagerServiceInjector injector, boolean factoryTest, final String partitionsFingerprint, final boolean isEngBuild, final boolean isUserDebugBuild, final int sdkVersion, final String incrementalVersion)1972     public PackageManagerService(PackageManagerServiceInjector injector, boolean factoryTest,
1973             final String partitionsFingerprint, final boolean isEngBuild,
1974             final boolean isUserDebugBuild, final int sdkVersion, final String incrementalVersion) {
1975         mIsEngBuild = isEngBuild;
1976         mIsUserDebugBuild = isUserDebugBuild;
1977         mSdkVersion = sdkVersion;
1978         mIncrementalVersion = incrementalVersion;
1979         mInjector = injector;
1980         mInjector.getSystemWrapper().disablePackageCaches();
1981 
1982         final TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing",
1983                 Trace.TRACE_TAG_PACKAGE_MANAGER);
1984         mPendingBroadcasts = new PendingPackageBroadcasts();
1985 
1986         mInjector.bootstrap(this);
1987         mLock = injector.getLock();
1988         mPackageStateWriteLock = mLock;
1989         mInstallLock = injector.getInstallLock();
1990         LockGuard.installLock(mLock, LockGuard.INDEX_PACKAGES);
1991         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1992                 SystemClock.uptimeMillis());
1993 
1994         mContext = injector.getContext();
1995         mFactoryTest = factoryTest;
1996         mMetrics = injector.getDisplayMetrics();
1997         mInstaller = injector.getInstaller();
1998         mFreeStorageHelper = new FreeStorageHelper(this);
1999 
2000         // Create sub-components that provide services / data. Order here is important.
2001         t.traceBegin("createSubComponents");
2002 
2003         // Expose private service for system components to use.
2004         LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl());
2005         LocalManagerRegistry.addManager(PackageManagerLocal.class,
2006                 new PackageManagerLocalImpl(this));
2007         LocalServices.addService(TestUtilityService.class, this);
2008         mTestUtilityService = LocalServices.getService(TestUtilityService.class);
2009         mUserManager = injector.getUserManagerService();
2010         mUserNeedsBadging = new UserNeedsBadgingCache(mUserManager);
2011         mComponentResolver = injector.getComponentResolver();
2012         mPermissionManager = injector.getPermissionManagerServiceInternal();
2013         mSettings = injector.getSettings();
2014         mIncrementalManager = mInjector.getIncrementalManager();
2015         mDefaultAppProvider = mInjector.getDefaultAppProvider();
2016         mLegacyPermissionManager = mInjector.getLegacyPermissionManagerInternal();
2017         PlatformCompat platformCompat = mInjector.getCompatibility();
2018         mPackageParserCallback = new PackageParser2.Callback() {
2019             @Override
2020             public boolean isChangeEnabled(long changeId, @NonNull ApplicationInfo appInfo) {
2021                 return platformCompat.isChangeEnabled(changeId, appInfo);
2022             }
2023 
2024             @Override
2025             public boolean hasFeature(String feature) {
2026                 return PackageManagerService.this.hasSystemFeature(feature, 0);
2027             }
2028 
2029             @Override
2030             public Set<String> getHiddenApiWhitelistedApps() {
2031                 return SystemConfig.getInstance().getHiddenApiWhitelistedApps();
2032             }
2033 
2034             @Override
2035             public Set<String> getInstallConstraintsAllowlist() {
2036                 return SystemConfig.getInstance().getInstallConstraintsAllowlist();
2037             }
2038         };
2039 
2040         // CHECKSTYLE:ON IndentationCheck
2041         t.traceEnd();
2042 
2043         t.traceBegin("get system config");
2044         SystemConfig systemConfig = injector.getSystemConfig();
2045         t.traceEnd();
2046 
2047         t.traceBegin("addSharedUsers");
2048         mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2049                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2050         mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2051                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2052         mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2053                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2054         mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2055                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2056         mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2057                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2058         mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2059                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2060         mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2061                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2062         mSettings.addSharedUserLPw("android.uid.networkstack", NETWORKSTACK_UID,
2063                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2064         mSettings.addSharedUserLPw("android.uid.uwb", UWB_UID,
2065                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2066         final ArrayMap<String, Integer> oemDefinedUids = systemConfig.getOemDefinedUids();
2067         final int numOemDefinedUids = oemDefinedUids.size();
2068         for (int i = 0; i < numOemDefinedUids; i++) {
2069             mSettings.addOemSharedUserLPw(oemDefinedUids.keyAt(i), oemDefinedUids.valueAt(i),
2070                     ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2071         }
2072 
2073         t.traceEnd();
2074 
2075         String separateProcesses = SystemProperties.get("debug.separate_processes");
2076 
2077         if (separateProcesses != null && separateProcesses.length() > 0) {
2078             if ("*".equals(separateProcesses)) {
2079                 mDefParseFlags = ParsingPackageUtils.PARSE_IGNORE_PROCESSES;
2080                 mSeparateProcesses = null;
2081                 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2082             } else {
2083                 mDefParseFlags = 0;
2084                 mSeparateProcesses = separateProcesses.split(",");
2085                 Slog.w(TAG, "Running with debug.separate_processes: "
2086                         + separateProcesses);
2087             }
2088         } else {
2089             mDefParseFlags = 0;
2090             mSeparateProcesses = null;
2091         }
2092 
2093         mPackageDexOptimizer = injector.getPackageDexOptimizer();
2094         mDexManager = injector.getDexManager();
2095         mDynamicCodeLogger = injector.getDynamicCodeLogger();
2096         mArtManagerService = injector.getArtManagerService();
2097         mMoveCallbacks = new MovePackageHelper.MoveCallbacks(FgThread.get().getLooper());
2098         mSharedLibraries = mInjector.getSharedLibrariesImpl();
2099         mBackgroundHandler = injector.getBackgroundHandler();
2100 
2101         mContext.getSystemService(DisplayManager.class)
2102                 .getDisplay(Display.DEFAULT_DISPLAY).getMetrics(mMetrics);
2103 
2104         mAvailableFeatures = systemConfig.getAvailableFeatures();
2105 
2106         mProtectedPackages = new ProtectedPackages(mContext);
2107 
2108         mApexManager = injector.getApexManager();
2109         mAppsFilter = mInjector.getAppsFilter();
2110 
2111         mChangedPackagesTracker = new ChangedPackagesTracker();
2112 
2113         mAppInstallDir = new File(Environment.getDataDirectory(), "app");
2114 
2115         mDomainVerificationConnection = new DomainVerificationConnection(this);
2116         mDomainVerificationManager = injector.getDomainVerificationManagerInternal();
2117         mDomainVerificationManager.setConnection(mDomainVerificationConnection);
2118 
2119         mBroadcastHelper = new BroadcastHelper(mInjector);
2120         mPackageMonitorCallbackHelper = injector.getPackageMonitorCallbackHelper();
2121         mAppDataHelper = new AppDataHelper(this);
2122         mRemovePackageHelper = new RemovePackageHelper(this, mAppDataHelper, mBroadcastHelper);
2123         mDeletePackageHelper = new DeletePackageHelper(this, mRemovePackageHelper,
2124                 mBroadcastHelper);
2125         mInstallPackageHelper = new InstallPackageHelper(this, mAppDataHelper, mRemovePackageHelper,
2126                 mDeletePackageHelper, mBroadcastHelper);
2127 
2128         mInstantAppRegistry = new InstantAppRegistry(mContext, mPermissionManager,
2129                 mInjector.getUserManagerInternal(), mDeletePackageHelper);
2130 
2131         mSharedLibraries.setDeletePackageHelper(mDeletePackageHelper);
2132         mPreferredActivityHelper = new PreferredActivityHelper(this, mBroadcastHelper);
2133         mResolveIntentHelper = new ResolveIntentHelper(mContext, mPreferredActivityHelper,
2134                 injector.getCompatibility(), mUserManager, mDomainVerificationManager,
2135                 mUserNeedsBadging, () -> mResolveInfo, () -> mInstantAppInstallerActivity);
2136         mDexOptHelper = new DexOptHelper(this);
2137         mSuspendPackageHelper = new SuspendPackageHelper(this, mInjector, mBroadcastHelper,
2138                 mProtectedPackages);
2139         mDistractingPackageHelper = new DistractingPackageHelper(this, mBroadcastHelper,
2140                 mSuspendPackageHelper);
2141         mStorageEventHelper = new StorageEventHelper(this, mDeletePackageHelper,
2142                 mRemovePackageHelper);
2143 
2144         synchronized (mLock) {
2145             // Create the computer as soon as the state objects have been installed.  The
2146             // cached computer is the same as the live computer until the end of the
2147             // constructor, at which time the invalidation method updates it.
2148             mSnapshotStatistics = new SnapshotStatistics();
2149             sSnapshotPendingVersion.incrementAndGet();
2150             mLiveComputer = createLiveComputer();
2151             registerObservers(true);
2152         }
2153 
2154         Computer computer = mLiveComputer;
2155         // CHECKSTYLE:OFF IndentationCheck
2156         try (PackageManagerTracedLock installLock = mInstallLock.acquireLock()) {
2157         // writer
2158         synchronized (mLock) {
2159             mHandler = injector.getHandler();
2160             mProcessLoggingHandler = new ProcessLoggingHandler();
2161             Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2162 
2163             ArrayMap<String, SystemConfig.SharedLibraryEntry> libConfig
2164                     = systemConfig.getSharedLibraries();
2165             final int builtInLibCount = libConfig.size();
2166             for (int i = 0; i < builtInLibCount; i++) {
2167                 mSharedLibraries.addBuiltInSharedLibraryLPw(libConfig.valueAt(i));
2168             }
2169 
2170             // Now that we have added all the libraries, iterate again to add dependency
2171             // information IFF their dependencies are added.
2172             long undefinedVersion = SharedLibraryInfo.VERSION_UNDEFINED;
2173             for (int i = 0; i < builtInLibCount; i++) {
2174                 String name = libConfig.keyAt(i);
2175                 SystemConfig.SharedLibraryEntry entry = libConfig.valueAt(i);
2176                 final int dependencyCount = entry.dependencies.length;
2177                 for (int j = 0; j < dependencyCount; j++) {
2178                     final SharedLibraryInfo dependency =
2179                         computer.getSharedLibraryInfo(entry.dependencies[j], undefinedVersion);
2180                     if (dependency != null) {
2181                         computer.getSharedLibraryInfo(name, undefinedVersion)
2182                                 .addDependency(dependency);
2183                     }
2184                 }
2185             }
2186 
2187             SELinuxMMAC.readInstallPolicy();
2188 
2189             t.traceBegin("loadFallbacks");
2190             FallbackCategoryProvider.loadFallbacks();
2191             t.traceEnd();
2192 
2193             t.traceBegin("read user settings");
2194             mFirstBoot = !mSettings.readLPw(computer,
2195                     mInjector.getUserManagerInternal().getUsers(
2196                     /* excludePartial= */ true,
2197                     /* excludeDying= */ false,
2198                     /* excludePreCreated= */ false));
2199             t.traceEnd();
2200 
2201             if (mFirstBoot) {
2202                 t.traceBegin("setFirstBoot: ");
2203                 try {
2204                     mInstaller.setFirstBoot();
2205                 } catch (InstallerException e) {
2206                     Slog.w(TAG, "Could not set First Boot: ", e);
2207                 }
2208                 t.traceEnd();
2209             }
2210 
2211             mPermissionManager.readLegacyPermissionsTEMP(mSettings.mPermissions);
2212             mPermissionManager.readLegacyPermissionStateTEMP();
2213 
2214             if (mFirstBoot) {
2215                 DexOptHelper.requestCopyPreoptedFiles();
2216             }
2217 
2218             String customResolverActivityName = Resources.getSystem().getString(
2219                     R.string.config_customResolverActivity);
2220             if (!TextUtils.isEmpty(customResolverActivityName)) {
2221                 mCustomResolverComponentName = ComponentName.unflattenFromString(
2222                         customResolverActivityName);
2223             }
2224 
2225             long startTime = SystemClock.uptimeMillis();
2226 
2227             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2228                     startTime);
2229 
2230             final String bootClassPath = System.getenv("BOOTCLASSPATH");
2231             final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2232 
2233             if (bootClassPath == null) {
2234                 Slog.w(TAG, "No BOOTCLASSPATH found!");
2235             }
2236 
2237             if (systemServerClassPath == null) {
2238                 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2239             }
2240 
2241             final VersionInfo ver = mSettings.getInternalVersion();
2242             mIsUpgrade =
2243                     !partitionsFingerprint.equals(ver.fingerprint);
2244             if (mIsUpgrade) {
2245                 PackageManagerServiceUtils.logCriticalInfo(Log.INFO,
2246                         "Upgrading from " + ver.fingerprint + " (" + ver.buildFingerprint + ") to "
2247                                 + PackagePartitions.FINGERPRINT + " (" + Build.FINGERPRINT + ")");
2248             }
2249             mPriorSdkVersion = mIsUpgrade ? ver.sdkVersion : -1;
2250             mInitAppsHelper = new InitAppsHelper(this, mApexManager, mInstallPackageHelper,
2251                     mInjector.getSystemPartitions());
2252 
2253             // when upgrading from pre-M, promote system app permissions from install to runtime
2254             mPromoteSystemApps =
2255                     mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2256 
2257             mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2258             mIsPreQUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.Q;
2259 
2260             final WatchedArrayMap<String, PackageSetting> packageSettings =
2261                 mSettings.getPackagesLocked();
2262 
2263             if (isDeviceUpgrading()) {
2264                 // Save the names of pre-existing packages prior to scanning, so we can determine
2265                 // which system packages are completely new due to an upgrade.
2266                 mExistingPackages = new ArraySet<>(packageSettings.size());
2267                 for (int i = 0; i < packageSettings.size(); i++) {
2268                     mExistingPackages.add(packageSettings.valueAt(i).getPackageName());
2269                 }
2270 
2271                 // Triggering {@link com.android.server.pm.crossprofile.
2272                 // CrossProfileIntentFilterHelper.updateDefaultCrossProfileIntentFilter} to update
2273                 // {@link  CrossProfileIntentFilter}s between eligible users and their parent
2274                 t.traceBegin("cross profile intent filter update");
2275                 mInjector.getCrossProfileIntentFilterHelper()
2276                         .updateDefaultCrossProfileIntentFilter();
2277                 t.traceEnd();
2278             }
2279 
2280             mCacheDir = PackageManagerServiceUtils.preparePackageParserCache(
2281                     mIsEngBuild, mIsUserDebugBuild, mIncrementalVersion);
2282 
2283             mInitialNonStoppedSystemPackages = mInjector.getSystemConfig()
2284                     .getInitialNonStoppedSystemPackages();
2285             mShouldStopSystemPackagesByDefault = mContext.getResources()
2286                     .getBoolean(R.bool.config_stopSystemPackagesByDefault);
2287 
2288             final int[] userIds = mUserManager.getUserIds();
2289             PackageParser2 packageParser = mInjector.getScanningCachingPackageParser();
2290             mOverlayConfig = mInitAppsHelper.initSystemApps(packageParser, packageSettings, userIds,
2291                     startTime);
2292             mInitAppsHelper.initNonSystemApps(packageParser, userIds, startTime);
2293             packageParser.close();
2294 
2295             mRequiredVerifierPackages = getRequiredButNotReallyRequiredVerifiersLPr(computer);
2296             mRequiredInstallerPackage = getRequiredInstallerLPr(computer);
2297             mRequiredUninstallerPackage = getRequiredUninstallerLPr(computer);
2298 
2299             // PermissionController hosts default permission granting and role management, so it's a
2300             // critical part of the core system.
2301             mRequiredPermissionControllerPackage = getRequiredPermissionControllerLPr(computer);
2302 
2303             // Resolve the storage manager.
2304             mStorageManagerPackage = getStorageManagerPackageName(computer);
2305 
2306             // Resolve protected action filters. Only the setup wizard is allowed to
2307             // have a high priority filter for these actions.
2308             mSetupWizardPackage = getSetupWizardPackageNameImpl(computer);
2309             mComponentResolver.fixProtectedFilterPriorities(mSetupWizardPackage);
2310 
2311             mDefaultTextClassifierPackage = ensureSystemPackageName(computer,
2312                     mContext.getString(R.string.config_servicesExtensionPackage));
2313             mSystemTextClassifierPackageName = ensureSystemPackageName(computer,
2314                     mContext.getString(R.string.config_defaultTextClassifierPackage));
2315             mConfiguratorPackage = ensureSystemPackageName(computer,
2316                     mContext.getString(R.string.config_deviceConfiguratorPackageName));
2317             mAppPredictionServicePackage = ensureSystemPackageName(computer,
2318                     getPackageFromComponentString(R.string.config_defaultAppPredictionService));
2319             mIncidentReportApproverPackage = ensureSystemPackageName(computer,
2320                     mContext.getString(R.string.config_incidentReportApproverPackage));
2321             mRetailDemoPackage = getRetailDemoPackageName();
2322             mOverlayConfigSignaturePackage = ensureSystemPackageName(computer,
2323                     mInjector.getSystemConfig().getOverlayConfigSignaturePackage());
2324             mRecentsPackage = ensureSystemPackageName(computer,
2325                     getPackageFromComponentString(R.string.config_recentsComponentName));
2326             mAmbientContextDetectionPackage = ensureSystemPackageName(computer,
2327                     getPackageFromComponentString(
2328                             R.string.config_defaultAmbientContextDetectionService));
2329             mWearableSensingPackage = ensureSystemPackageName(computer,
2330                     getPackageFromComponentString(
2331                             R.string.config_defaultWearableSensingService));
2332 
2333             // Now that we know all of the shared libraries, update all clients to have
2334             // the correct library paths.
2335             mSharedLibraries.updateAllSharedLibrariesLPw(
2336                     null, null, Collections.unmodifiableMap(mPackages));
2337 
2338             for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2339                 // NOTE: We ignore potential failures here during a system scan (like
2340                 // the rest of the commands above) because there's precious little we
2341                 // can do about it. A settings error is reported, though.
2342                 final List<String> changedAbiCodePath =
2343                         ScanPackageUtils.applyAdjustedAbiToSharedUser(setting,
2344                                 null /*scannedPackage*/,
2345                                 mInjector.getAbiHelper().getAdjustedAbiForSharedUser(
2346                                         setting.getPackageStates(), null /*scannedPackage*/));
2347                 // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
2348                 // SELinux domain.
2349                 setting.fixSeInfoLocked();
2350                 setting.updateProcesses();
2351             }
2352 
2353             // Now that we know all the packages we are keeping,
2354             // read and update their last usage times.
2355             mPackageUsage.read(packageSettings);
2356             mCompilerStats.read();
2357 
2358             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2359                     SystemClock.uptimeMillis());
2360             Slog.i(TAG, "Time to scan packages: "
2361                     + ((SystemClock.uptimeMillis() - startTime) / 1000f)
2362                     + " seconds");
2363 
2364             // If the partitions fingerprint has changed since the last time we booted,
2365             // we need to re-grant app permission to catch any new ones that
2366             // appear.  This is really a hack, and means that apps can in some
2367             // cases get permissions that the user didn't initially explicitly
2368             // allow...  it would be nice to have some better way to handle
2369             // this situation.
2370             if (mIsUpgrade) {
2371                 Slog.i(TAG, "Partitions fingerprint changed from " + ver.fingerprint + " to "
2372                         + PackagePartitions.FINGERPRINT
2373                         + "; regranting permissions for internal storage");
2374             }
2375             mPermissionManager.onStorageVolumeMounted(
2376                     StorageManager.UUID_PRIVATE_INTERNAL, mIsUpgrade);
2377             ver.sdkVersion = mSdkVersion;
2378 
2379             // If this is the first boot or an update from pre-M, then we need to initialize the
2380             // default preferred apps across all defined users.
2381             if (mPromoteSystemApps || mFirstBoot) {
2382                 final List<UserInfo> users = mInjector.getUserManagerInternal().getUsers(true);
2383                 for (int i = 0; i < users.size(); i++) {
2384                     mSettings.applyDefaultPreferredAppsLPw(users.get(i).id);
2385 
2386                 }
2387             }
2388 
2389             // If this is first boot after an OTA, then we need to clear code cache directories.
2390             // Note that we do *not* clear the application profiles. These remain valid
2391             // across OTAs and are used to drive profile verification (post OTA) and
2392             // profile compilation (without waiting to collect a fresh set of profiles).
2393             if (mIsUpgrade) {
2394                 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2395                 for (int i = 0; i < packageSettings.size(); i++) {
2396                     final PackageSetting ps = packageSettings.valueAt(i);
2397                     if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.getVolumeUuid())) {
2398                         // No apps are running this early, so no need to freeze
2399                         mAppDataHelper.clearAppDataLIF(ps.getPkg(), USER_ALL,
2400                                 FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL
2401                                         | Installer.FLAG_CLEAR_CODE_CACHE_ONLY
2402                                         | Installer.FLAG_CLEAR_APP_DATA_KEEP_ART_PROFILES);
2403                     }
2404                 }
2405                 ver.buildFingerprint = Build.FINGERPRINT;
2406                 ver.fingerprint = PackagePartitions.FINGERPRINT;
2407             }
2408 
2409             // Defer the app data fixup until we are done with app data clearing above.
2410             mPrepareAppDataFuture = mAppDataHelper.fixAppsDataOnBoot();
2411 
2412             // Legacy existing (installed before Q) non-system apps to hide
2413             // their icons in launcher.
2414             if (mIsPreQUpgrade) {
2415                 Slog.i(TAG, "Allowlisting all existing apps to hide their icons");
2416                 int size = packageSettings.size();
2417                 for (int i = 0; i < size; i++) {
2418                     final PackageSetting ps = packageSettings.valueAt(i);
2419                     if ((ps.getFlags() & ApplicationInfo.FLAG_SYSTEM) != 0) {
2420                         continue;
2421                     }
2422                     ps.disableComponentLPw(PackageManager.APP_DETAILS_ACTIVITY_CLASS_NAME,
2423                             UserHandle.USER_SYSTEM);
2424                 }
2425             }
2426 
2427             // clear only after permissions and other defaults have been updated
2428             mPromoteSystemApps = false;
2429 
2430             // All the changes are done during package scanning.
2431             ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
2432 
2433             // can downgrade to reader
2434             t.traceBegin("write settings");
2435             writeSettingsLPrTEMP();
2436             t.traceEnd();
2437             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2438                     SystemClock.uptimeMillis());
2439 
2440             ComponentName intentFilterVerifierComponent =
2441                     getIntentFilterVerifierComponentNameLPr(computer);
2442             ComponentName domainVerificationAgent =
2443                     getDomainVerificationAgentComponentNameLPr(computer, UserHandle.USER_SYSTEM);
2444 
2445             DomainVerificationProxy domainVerificationProxy = DomainVerificationProxy.makeProxy(
2446                     intentFilterVerifierComponent, domainVerificationAgent, mContext,
2447                     mDomainVerificationManager, mDomainVerificationManager.getCollector(),
2448                     mDomainVerificationConnection);
2449 
2450             mDomainVerificationManager.setProxy(domainVerificationProxy);
2451 
2452             mServicesExtensionPackageName = getRequiredServicesExtensionPackageLPr(computer);
2453             mSharedSystemSharedLibraryPackageName = getRequiredSharedLibrary(computer,
2454                     PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
2455                     SharedLibraryInfo.VERSION_UNDEFINED);
2456 
2457             mSettings.setPermissionControllerVersion(
2458                     computer.getPackageInfo(mRequiredPermissionControllerPackage, 0,
2459                             UserHandle.USER_SYSTEM).getLongVersionCode());
2460 
2461             // Resolve the sdk sandbox package
2462             mRequiredSdkSandboxPackage = getRequiredSdkSandboxPackageName(computer);
2463 
2464             // Initialize InstantAppRegistry's Instant App list for all users.
2465             forEachPackageState(computer, packageState -> {
2466                 var pkg = packageState.getAndroidPackage();
2467                 if (pkg == null || packageState.isSystem()) {
2468                     return;
2469                 }
2470                 for (int userId : userIds) {
2471                     if (!packageState.getUserStateOrDefault(userId).isInstantApp()
2472                             || !packageState.getUserStateOrDefault(userId).isInstalled()) {
2473                         continue;
2474                     }
2475                     mInstantAppRegistry.addInstantApp(userId, packageState.getAppId());
2476                 }
2477             });
2478 
2479             mInstallerService = mInjector.getPackageInstallerService();
2480             final ComponentName instantAppResolverComponent = getInstantAppResolver(computer);
2481             if (instantAppResolverComponent != null) {
2482                 if (DEBUG_INSTANT) {
2483                     Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
2484                 }
2485                 mInstantAppResolverConnection =
2486                         mInjector.getInstantAppResolverConnection(instantAppResolverComponent);
2487                 mInstantAppResolverSettingsComponent =
2488                         getInstantAppResolverSettingsLPr(computer,
2489                                 instantAppResolverComponent);
2490             } else {
2491                 mInstantAppResolverConnection = null;
2492                 mInstantAppResolverSettingsComponent = null;
2493             }
2494             updateInstantAppInstallerLocked(null);
2495 
2496             // Read and update the usage of dex files.
2497             // Do this at the end of PM init so that all the packages have their
2498             // data directory reconciled.
2499             // At this point we know the code paths of the packages, so we can validate
2500             // the disk file and build the internal cache.
2501             // The usage file is expected to be small so loading and verifying it
2502             // should take a fairly small time compare to the other activities (e.g. package
2503             // scanning).
2504             final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
2505             for (int userId : userIds) {
2506                 userPackages.put(userId, computer.getInstalledPackages(/*flags*/ 0, userId)
2507                         .getList());
2508             }
2509             mDexManager.load(userPackages);
2510             mDynamicCodeLogger.load(userPackages);
2511             if (mIsUpgrade) {
2512                 FrameworkStatsLog.write(
2513                         FrameworkStatsLog.BOOT_TIME_EVENT_DURATION_REPORTED,
2514                         BOOT_TIME_EVENT_DURATION__EVENT__OTA_PACKAGE_MANAGER_INIT_TIME,
2515                         SystemClock.uptimeMillis() - startTime);
2516             }
2517 
2518             // If this is first boot or first boot after OTA then set the file path to the app
2519             // metadata files for preloaded packages.
2520             if (mFirstBoot || isDeviceUpgrading()) {
2521                 ArrayMap<String, String> paths = systemConfig.getAppMetadataFilePaths();
2522                 for (Map.Entry<String, String> entry : paths.entrySet()) {
2523                     String pkgName = entry.getKey();
2524                     String path = entry.getValue();
2525                     File file = new File(path);
2526                     if (!file.exists()) {
2527                         path = null;
2528                     }
2529                     PackageSetting disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(pkgName);
2530                     if (disabledPkgSetting == null) {
2531                         PackageSetting pkgSetting = mSettings.getPackageLPr(pkgName);
2532                         if (pkgSetting != null) {
2533                             pkgSetting.setAppMetadataFilePath(path);
2534                             if (Flags.aslInApkAppMetadataSource()) {
2535                                 pkgSetting.setAppMetadataSource(
2536                                         PackageManager.APP_METADATA_SOURCE_SYSTEM_IMAGE);
2537                             }
2538                         } else {
2539                             Slog.w(TAG, "Cannot set app metadata file for nonexistent package "
2540                                     + pkgName);
2541                         }
2542                     } else {
2543                         disabledPkgSetting.setAppMetadataFilePath(path);
2544                         if (Flags.aslInApkAppMetadataSource()) {
2545                             disabledPkgSetting.setAppMetadataSource(
2546                                     PackageManager.APP_METADATA_SOURCE_SYSTEM_IMAGE);
2547                         }
2548                     }
2549                 }
2550             }
2551 
2552             // Rebuild the live computer since some attributes have been rebuilt.
2553             mLiveComputer = createLiveComputer();
2554 
2555         } // synchronized (mLock)
2556         } // synchronized (mInstallLock)
2557         // CHECKSTYLE:ON IndentationCheck
2558 
2559         mModuleInfoProvider = mInjector.getModuleInfoProvider();
2560 
2561         mInjector.getSystemWrapper().enablePackageCaches();
2562 
2563         // The initial scanning above does many calls into installd while
2564         // holding the mPackages lock, but we're mostly interested in yelling
2565         // once we have a booted system.
2566         mInstaller.setWarnIfHeld(mLock);
2567 
2568         ParsingPackageUtils.readConfigUseRoundIcon(mContext.getResources());
2569 
2570         mServiceStartWithDelay = SystemClock.uptimeMillis() + (60 * 1000L);
2571 
2572         Slog.i(TAG, "Fix for b/169414761 is applied");
2573     }
2574 
2575     @GuardedBy("mLock")
2576     void updateInstantAppInstallerLocked(String modifiedPackage) {
2577         // we're only interested in updating the installer application when 1) it's not
2578         // already set or 2) the modified package is the installer
2579         if (mInstantAppInstallerActivity != null
2580                 && !mInstantAppInstallerActivity.getComponentName().getPackageName()
2581                         .equals(modifiedPackage)) {
2582             return;
2583         }
2584         setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
2585     }
2586 
2587     public boolean isFirstBoot() {
2588         // allow instant applications
2589         return mFirstBoot;
2590     }
2591 
2592     public boolean isDeviceUpgrading() {
2593         // allow instant applications
2594         // The system property allows testing ota flow when upgraded to the same image.
2595         return mIsUpgrade || SystemProperties.getBoolean(
2596                 "persist.pm.mock-upgrade", false /* default */);
2597     }
2598 
2599     @NonNull
2600     private String[] getRequiredButNotReallyRequiredVerifiersLPr(@NonNull Computer computer) {
2601         final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2602 
2603         final List<ResolveInfo> matches =
2604                 mResolveIntentHelper.queryIntentReceiversInternal(computer, intent,
2605                         PACKAGE_MIME_TYPE,
2606                         MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2607                         UserHandle.USER_SYSTEM, Binder.getCallingUid());
2608         final int size = matches.size();
2609         if (size == 0) {
2610             Log.w(TAG, "There should probably be a verifier, but, none were found");
2611             return EmptyArray.STRING;
2612         } else if (size <= REQUIRED_VERIFIERS_MAX_COUNT) {
2613             String[] verifiers = new String[size];
2614             for (int i = 0; i < size; ++i) {
2615                 verifiers[i] = matches.get(i).getComponentInfo().packageName;
2616                 if (TextUtils.isEmpty(verifiers[i])) {
2617                     throw new RuntimeException("Invalid verifier: " + matches);
2618                 }
2619             }
2620             return verifiers;
2621         }
2622         throw new RuntimeException(
2623                 "There must be no more than " + REQUIRED_VERIFIERS_MAX_COUNT + " verifiers; found "
2624                         + matches);
2625     }
2626 
2627     @NonNull
2628     private String getRequiredSharedLibrary(@NonNull Computer snapshot, @NonNull String name,
2629             int version) {
2630         SharedLibraryInfo libraryInfo = snapshot.getSharedLibraryInfo(name, version);
2631         if (libraryInfo == null) {
2632             throw new IllegalStateException("Missing required shared library:" + name);
2633         }
2634         String packageName = libraryInfo.getPackageName();
2635         if (packageName == null) {
2636             throw new IllegalStateException("Expected a package for shared library " + name);
2637         }
2638         return packageName;
2639     }
2640 
2641     @NonNull
2642     private String getRequiredServicesExtensionPackageLPr(@NonNull Computer computer) {
2643         String configServicesExtensionPackage = mContext.getString(
2644                 R.string.config_servicesExtensionPackage);
2645         if (TextUtils.isEmpty(configServicesExtensionPackage)) {
2646             throw new RuntimeException(
2647                     "Required services extension package failed due to "
2648                             + "config_servicesExtensionPackage is empty.");
2649         }
2650         String servicesExtensionPackage = ensureSystemPackageName(computer,
2651                 configServicesExtensionPackage);
2652         if (TextUtils.isEmpty(servicesExtensionPackage)) {
2653             throw new RuntimeException(
2654                     "Required services extension package is missing, "
2655                             + "config_servicesExtensionPackage had defined with "
2656                             + configServicesExtensionPackage
2657                             + ", but can not find the package info on the system image, check if "
2658                             + "the package has a problem.");
2659         }
2660         return servicesExtensionPackage;
2661     }
2662 
2663     private @NonNull String getRequiredInstallerLPr(@NonNull Computer computer) {
2664         final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
2665         intent.addCategory(Intent.CATEGORY_DEFAULT);
2666         intent.setDataAndType(Uri.parse("content://com.example/foo.apk"), PACKAGE_MIME_TYPE);
2667 
2668         final List<ResolveInfo> matches = computer.queryIntentActivitiesInternal(intent,
2669                 PACKAGE_MIME_TYPE,
2670                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2671                 UserHandle.USER_SYSTEM);
2672         if (matches.size() == 1) {
2673             ResolveInfo resolveInfo = matches.get(0);
2674             if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2675                 throw new RuntimeException("The installer must be a privileged app");
2676             }
2677             return matches.get(0).getComponentInfo().packageName;
2678         } else {
2679             throw new RuntimeException("There must be exactly one installer; found " + matches);
2680         }
2681     }
2682 
2683     private @NonNull String getRequiredUninstallerLPr(@NonNull Computer computer) {
2684         final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
2685         intent.addCategory(Intent.CATEGORY_DEFAULT);
2686         intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
2687 
2688         final ResolveInfo resolveInfo = mResolveIntentHelper.resolveIntentInternal(computer, intent,
2689                 null, MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2690                 0 /*privateResolveFlags*/, UserHandle.USER_SYSTEM, false,
2691                 Binder.getCallingUid(), Binder.getCallingPid());
2692         if (resolveInfo == null ||
2693                 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
2694             throw new RuntimeException("There must be exactly one uninstaller; found "
2695                     + resolveInfo);
2696         }
2697         return resolveInfo.getComponentInfo().packageName;
2698     }
2699 
2700     private @NonNull String getRequiredPermissionControllerLPr(@NonNull Computer computer) {
2701         final Intent intent = new Intent(Intent.ACTION_MANAGE_PERMISSIONS);
2702         intent.addCategory(Intent.CATEGORY_DEFAULT);
2703 
2704         final List<ResolveInfo> matches = computer.queryIntentActivitiesInternal(intent, null,
2705                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2706                 UserHandle.USER_SYSTEM);
2707         if (matches.size() == 1) {
2708             ResolveInfo resolveInfo = matches.get(0);
2709             if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
2710                 throw new RuntimeException("The permissions manager must be a privileged app");
2711             }
2712             return matches.get(0).getComponentInfo().packageName;
2713         } else {
2714             throw new RuntimeException("There must be exactly one permissions manager; found "
2715                     + matches);
2716         }
2717     }
2718 
2719     @NonNull
2720     private ComponentName getIntentFilterVerifierComponentNameLPr(@NonNull Computer computer) {
2721         final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2722 
2723         final List<ResolveInfo> matches =
2724                 mResolveIntentHelper.queryIntentReceiversInternal(computer, intent,
2725                         PACKAGE_MIME_TYPE,
2726                         MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2727                         UserHandle.USER_SYSTEM, Binder.getCallingUid());
2728         ResolveInfo best = null;
2729         final int N = matches.size();
2730         for (int i = 0; i < N; i++) {
2731             final ResolveInfo cur = matches.get(i);
2732             final String packageName = cur.getComponentInfo().packageName;
2733             if (checkPermission(
2734                     android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, packageName,
2735                     UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
2736                 continue;
2737             }
2738 
2739             if (best == null || cur.priority > best.priority) {
2740                 best = cur;
2741             }
2742         }
2743 
2744         if (best != null) {
2745             return best.getComponentInfo().getComponentName();
2746         }
2747         Slog.w(TAG, "Intent filter verifier not found");
2748         return null;
2749     }
2750 
2751     @Nullable
2752     private ComponentName getDomainVerificationAgentComponentNameLPr(@NonNull Computer computer,
2753             int userId) {
2754         Intent intent = new Intent(Intent.ACTION_DOMAINS_NEED_VERIFICATION);
2755         List<ResolveInfo> matches =
2756                 mResolveIntentHelper.queryIntentReceiversInternal(computer, intent, null,
2757                         MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
2758                         userId, Binder.getCallingUid());
2759         ResolveInfo best = null;
2760         final int N = matches.size();
2761         for (int i = 0; i < N; i++) {
2762             final ResolveInfo cur = matches.get(i);
2763             final String packageName = cur.getComponentInfo().packageName;
2764             if (checkPermission(
2765                     android.Manifest.permission.DOMAIN_VERIFICATION_AGENT, packageName,
2766                     userId) != PackageManager.PERMISSION_GRANTED) {
2767                 Slog.w(TAG, "Domain verification agent found but does not hold permission: "
2768                         + packageName);
2769                 continue;
2770             }
2771 
2772             if (best == null || cur.priority > best.priority) {
2773                 if (computer.isComponentEffectivelyEnabled(cur.getComponentInfo(),
2774                         UserHandle.of(userId))) {
2775                     best = cur;
2776                 } else {
2777                     Slog.w(TAG, "Domain verification agent found but not enabled");
2778                 }
2779             }
2780         }
2781 
2782         if (best != null) {
2783             return best.getComponentInfo().getComponentName();
2784         }
2785         Slog.w(TAG, "Domain verification agent not found");
2786         return null;
2787     }
2788 
2789     @Nullable ComponentName getInstantAppResolver(@NonNull Computer snapshot) {
2790         final String[] packageArray =
2791                 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
2792         if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
2793             if (DEBUG_INSTANT) {
2794                 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
2795             }
2796             return null;
2797         }
2798 
2799         final int callingUid = Binder.getCallingUid();
2800         final int resolveFlags =
2801                 MATCH_DIRECT_BOOT_AWARE
2802                 | MATCH_DIRECT_BOOT_UNAWARE
2803                 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
2804         final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE);
2805         List<ResolveInfo> resolvers = snapshot.queryIntentServicesInternal(resolverIntent, null,
2806                 resolveFlags, UserHandle.USER_SYSTEM, callingUid, Process.INVALID_PID,
2807                 /*includeInstantApps*/ false, /*resolveForStart*/ false);
2808         final int N = resolvers.size();
2809         if (N == 0) {
2810             if (DEBUG_INSTANT) {
2811                 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
2812             }
2813             return null;
2814         }
2815 
2816         final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
2817         for (int i = 0; i < N; i++) {
2818             final ResolveInfo info = resolvers.get(i);
2819 
2820             if (info.serviceInfo == null) {
2821                 continue;
2822             }
2823 
2824             final String packageName = info.serviceInfo.packageName;
2825             if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
2826                 if (DEBUG_INSTANT) {
2827                     Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
2828                             + " pkg: " + packageName + ", info:" + info);
2829                 }
2830                 continue;
2831             }
2832 
2833             if (DEBUG_INSTANT) {
2834                 Slog.v(TAG, "Ephemeral resolver found;"
2835                         + " pkg: " + packageName + ", info:" + info);
2836             }
2837             return new ComponentName(packageName, info.serviceInfo.name);
2838         }
2839         if (DEBUG_INSTANT) {
2840             Slog.v(TAG, "Ephemeral resolver NOT found");
2841         }
2842         return null;
2843     }
2844 
2845     @GuardedBy("mLock")
2846     private @Nullable ActivityInfo getInstantAppInstallerLPr() {
2847         String[] orderedActions = mIsEngBuild
2848                 ? new String[]{
2849                         Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
2850                         Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
2851                 : new String[]{
2852                         Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
2853 
2854         final int resolveFlags =
2855                 MATCH_DIRECT_BOOT_AWARE
2856                         | MATCH_DIRECT_BOOT_UNAWARE
2857                         | Intent.FLAG_IGNORE_EPHEMERAL
2858                         | (mIsEngBuild ? 0 : MATCH_SYSTEM_ONLY);
2859         final Computer computer = snapshotComputer();
2860         final Intent intent = new Intent();
2861         intent.addCategory(Intent.CATEGORY_DEFAULT);
2862         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
2863         List<ResolveInfo> matches = null;
2864         for (String action : orderedActions) {
2865             intent.setAction(action);
2866             matches = computer.queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
2867                     resolveFlags, UserHandle.USER_SYSTEM);
2868             if (matches.isEmpty()) {
2869                 if (DEBUG_INSTANT) {
2870                     Slog.d(TAG, "Instant App installer not found with " + action);
2871                 }
2872             } else {
2873                 break;
2874             }
2875         }
2876         Iterator<ResolveInfo> iter = matches.iterator();
2877         while (iter.hasNext()) {
2878             final ResolveInfo rInfo = iter.next();
2879             if (checkPermission(
2880                     Manifest.permission.INSTALL_PACKAGES,
2881                     rInfo.activityInfo.packageName, 0) == PERMISSION_GRANTED || mIsEngBuild) {
2882                 continue;
2883             }
2884             iter.remove();
2885         }
2886         if (matches.size() == 0) {
2887             return null;
2888         } else if (matches.size() == 1) {
2889             return (ActivityInfo) matches.get(0).getComponentInfo();
2890         } else {
2891             throw new RuntimeException(
2892                     "There must be at most one ephemeral installer; found " + matches);
2893         }
2894     }
2895 
2896     private @Nullable ComponentName getInstantAppResolverSettingsLPr(@NonNull Computer computer,
2897             @NonNull ComponentName resolver) {
2898         final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
2899                 .addCategory(Intent.CATEGORY_DEFAULT)
2900                 .setPackage(resolver.getPackageName());
2901         final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
2902         List<ResolveInfo> matches = computer.queryIntentActivitiesInternal(intent, null,
2903                 resolveFlags, UserHandle.USER_SYSTEM);
2904         if (matches.isEmpty()) {
2905             return null;
2906         }
2907         return matches.get(0).getComponentInfo().getComponentName();
2908     }
2909 
2910     public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
2911         // Because this is accessed via the package manager service AIDL,
2912         // go through the permission manager service AIDL
2913         return mContext.getSystemService(PermissionManager.class)
2914                 .getPermissionGroupInfo(groupName, flags);
2915     }
2916 
2917     /**
2918      * Blocking call to clear all cached app data above quota.
2919      */
2920     public void freeAllAppCacheAboveQuota(String volumeUuid) throws IOException {
2921         try (PackageManagerTracedLock installLock = mInstallLock.acquireLock()) {
2922             // To avoid refactoring Installer.freeCache() and InstalldNativeService.freeCache(),
2923             // Long.MAX_VALUE is passed as an argument which is used in neither of two methods
2924             // when FLAG_FREE_CACHE_DEFY_TARGET_FREE_BYTES is set
2925             mInstaller.freeCache(volumeUuid, Long.MAX_VALUE, Installer.FLAG_FREE_CACHE_V2
2926                     | Installer.FLAG_FREE_CACHE_DEFY_TARGET_FREE_BYTES);
2927         } catch (InstallerException ignored) {
2928         }
2929     }
2930 
2931     /**
2932      * Blocking call to clear various types of cached data across the system
2933      * until the requested bytes are available.
2934      */
2935     public void freeStorage(String volumeUuid, long bytes,
2936             @StorageManager.AllocateFlags int flags) throws IOException {
2937         mFreeStorageHelper.freeStorage(volumeUuid, bytes, flags);
2938     }
2939 
2940     int freeCacheForInstallation(int recommendedInstallLocation, PackageLite pkgLite,
2941             String resolvedPath, String mPackageAbiOverride, int installFlags) {
2942         return mFreeStorageHelper.freeCacheForInstallation(recommendedInstallLocation, pkgLite,
2943                 resolvedPath, mPackageAbiOverride, installFlags);
2944     }
2945 
2946     public ModuleInfo getModuleInfo(String packageName, @PackageManager.ModuleInfoFlags int flags) {
2947         return mModuleInfoProvider.getModuleInfo(packageName, flags);
2948     }
2949 
2950     void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
2951         mChangedPackagesTracker.updateSequenceNumber(pkgSetting.getPackageName(), userList);
2952     }
2953 
2954     public boolean hasSystemFeature(String name, int version) {
2955         // allow instant applications
2956         final FeatureInfo feat = mAvailableFeatures.get(name);
2957         if (feat == null) {
2958             return false;
2959         } else {
2960             return feat.version >= version;
2961         }
2962     }
2963 
2964     // NOTE: Can't remove due to unsupported app usage
2965     public int checkPermission(String permName, String pkgName, int userId) {
2966         return mPermissionManager.checkPermission(pkgName, permName,
2967                 VirtualDeviceManager.PERSISTENT_DEVICE_ID_DEFAULT, userId);
2968     }
2969 
2970     public String getSdkSandboxPackageName() {
2971         return mRequiredSdkSandboxPackage;
2972     }
2973 
2974     String getPackageInstallerPackageName() {
2975         return mRequiredInstallerPackage;
2976     }
2977 
2978     void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
2979             Intent origIntent, String resolvedType, String callingPackage,
2980             @Nullable String callingFeatureId, boolean isRequesterInstantApp,
2981             Bundle verificationBundle, int userId) {
2982         final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
2983                 new InstantAppRequest(responseObj, origIntent, resolvedType,
2984                         callingPackage, callingFeatureId, isRequesterInstantApp, userId,
2985                         verificationBundle, false /*resolveForStart*/,
2986                         responseObj.hostDigestPrefixSecure, responseObj.token));
2987         mHandler.sendMessage(msg);
2988     }
2989 
2990     // findPreferredActivityBody returns two items: a "things changed" flag and a
2991     // ResolveInfo, which is the preferred activity itself.
2992     static class FindPreferredActivityBodyResult {
2993         boolean mChanged;
2994         ResolveInfo mPreferredResolveInfo;
2995     }
2996 
2997     public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(@NonNull Computer snapshot,
2998             Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags,
2999             @UserIdInt int userId) {
3000         return new ParceledListSlice<>(mResolveIntentHelper.queryIntentReceiversInternal(
3001                 snapshot, intent, resolvedType, flags, userId, Binder.getCallingUid()));
3002     }
3003 
3004     public static void reportSettingsProblem(int priority, String msg) {
3005         logCriticalInfo(priority, msg);
3006     }
3007 
3008     // TODO:(b/135203078): Move to parsing
3009     static void renameStaticSharedLibraryPackage(ParsedPackage parsedPackage) {
3010         // Derive the new package synthetic package name
3011         parsedPackage.setPackageName(toStaticSharedLibraryPackageName(
3012                 parsedPackage.getPackageName(), parsedPackage.getStaticSharedLibraryVersion()));
3013     }
3014 
3015     private static String toStaticSharedLibraryPackageName(
3016             String packageName, long libraryVersion) {
3017         return packageName + STATIC_SHARED_LIB_DELIMITER + libraryVersion;
3018     }
3019 
3020     public void performFstrimIfNeeded() {
3021         mFreeStorageHelper.performFstrimIfNeeded();
3022     }
3023 
3024     public void updatePackagesIfNeeded() {
3025         mDexOptHelper.performPackageDexOptUpgradeIfNeeded();
3026     }
3027 
3028     public void updateMetricsIfNeeded() {
3029         final DisplayManager displayManager = mContext.getSystemService(DisplayManager.class);
3030         if (displayManager != null) {
3031             final Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
3032             if (display != null) {
3033                 display.getMetrics(mMetrics);
3034             }
3035         }
3036     }
3037 
3038     private void notifyPackageUseInternal(String packageName, int reason) {
3039         long time = System.currentTimeMillis();
3040         synchronized (mLock) {
3041             final PackageSetting pkgSetting = mSettings.getPackageLPr(packageName);
3042             if (pkgSetting == null) {
3043                 return;
3044             }
3045             pkgSetting.getPkgState().setLastPackageUsageTimeInMills(reason, time);
3046         }
3047     }
3048 
3049     /*package*/ DexManager getDexManager() {
3050         return mDexManager;
3051     }
3052 
3053     /*package*/ DexOptHelper getDexOptHelper() {
3054         return mDexOptHelper;
3055     }
3056 
3057     /*package*/ DynamicCodeLogger getDynamicCodeLogger() {
3058         return mDynamicCodeLogger;
3059     }
3060 
3061     public void shutdown() {
3062         mCompilerStats.writeNow();
3063         mDexManager.writePackageDexUsageNow();
3064         mDynamicCodeLogger.writeNow();
3065         if (!refactorCrashrecovery()) {
3066             CrashRecoveryAdaptor.packageWatchdogWriteNow(mContext);
3067         }
3068 
3069         synchronized (mLock) {
3070             mPackageUsage.writeNow(mSettings.getPackagesLocked());
3071 
3072             if (mHandler.hasMessages(WRITE_SETTINGS)
3073                     || mBackgroundHandler.hasMessages(WRITE_DIRTY_PACKAGE_RESTRICTIONS)
3074                     || mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
3075                 writeSettings(/*sync=*/true);
3076             }
3077         }
3078     }
3079 
3080     @NonNull
3081     int[] resolveUserIds(@CanBeALL @UserIdInt int userId) {
3082         return (userId == USER_ALL) ? mUserManager.getUserIds() : new int[]{userId};
3083     }
3084 
3085     private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
3086         if (installerActivity == null) {
3087             if (DEBUG_INSTANT) {
3088                 Slog.d(TAG, "Clear ephemeral installer activity");
3089             }
3090             mInstantAppInstallerActivity = null;
3091             onChanged();
3092             return;
3093         }
3094 
3095         if (DEBUG_INSTANT) {
3096             Slog.d(TAG, "Set ephemeral installer activity: "
3097                     + installerActivity.getComponentName());
3098         }
3099         // Set up information for ephemeral installer activity
3100         mInstantAppInstallerActivity = installerActivity;
3101         mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
3102                 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
3103         mInstantAppInstallerActivity.exported = true;
3104         mInstantAppInstallerActivity.enabled = true;
3105         mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
3106         mInstantAppInstallerInfo.priority = 1;
3107         mInstantAppInstallerInfo.preferredOrder = 1;
3108         mInstantAppInstallerInfo.isDefault = true;
3109         mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
3110                 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
3111         onChanged();
3112     }
3113 
3114     void killApplication(String pkgName, @AppIdInt int appId, String reason, int exitInfoReason) {
3115         killApplication(pkgName, appId, USER_ALL, reason, exitInfoReason);
3116     }
3117 
3118     void killApplication(String pkgName, @AppIdInt int appId,
3119             @CanBeALL @UserIdInt int userId, String reason, int exitInfoReason) {
3120         // Request the ActivityManager to kill the process(only for existing packages)
3121         // so that we do not end up in a confused state while the user is still using the older
3122         // version of the application while the new one gets installed.
3123         final long token = Binder.clearCallingIdentity();
3124         try {
3125             IActivityManager am = ActivityManager.getService();
3126             if (am != null) {
3127                 try {
3128                     am.killApplication(pkgName, appId, userId, reason, exitInfoReason);
3129                 } catch (RemoteException e) {
3130                 }
3131             }
3132         } finally {
3133             Binder.restoreCallingIdentity(token);
3134         }
3135     }
3136 
3137     void killApplicationSync(String pkgName, @AppIdInt int appId,
3138             @CanBeALL @UserIdInt int userId, String reason, int exitInfoReason) {
3139         ActivityManagerInternal mAmi = LocalServices.getService(ActivityManagerInternal.class);
3140         if (Thread.holdsLock(mLock) || mAmi == null) {
3141             // holds PM's lock, go back killApplication to avoid it run into watchdog reset.
3142             Slog.e(TAG, "Holds PM's lock, unable kill application synchronized");
3143             killApplication(pkgName, appId, userId, reason, exitInfoReason);
3144         } else {
3145             KillAppBlocker blocker = new KillAppBlocker();
3146             try {
3147                 blocker.register();
3148                 mAmi.killApplicationSync(pkgName, appId, userId, reason, exitInfoReason);
3149                 blocker.waitAppProcessGone(mAmi, snapshotComputer(), mUserManager, pkgName);
3150             } finally {
3151                 blocker.unregister();
3152             }
3153         }
3154     }
3155 
3156     @Override
3157     public void notifyPackageAdded(String packageName, int uid) {
3158         mPackageObserverHelper.notifyAdded(packageName, uid);
3159     }
3160 
3161     @Override
3162     public void notifyPackageChanged(String packageName, int uid) {
3163         mPackageObserverHelper.notifyChanged(packageName, uid);
3164     }
3165 
3166     @Override
3167     public void notifyPackageRemoved(String packageName, int uid) {
3168         mPackageObserverHelper.notifyRemoved(packageName, uid);
3169         UserPackage.removeFromCache(UserHandle.getUserId(uid), packageName);
3170     }
3171 
3172     boolean isUserRestricted(int userId, String restrictionKey) {
3173         Bundle restrictions = mUserManager.getUserRestrictions(userId);
3174         if (restrictions.getBoolean(restrictionKey, false)) {
3175             Log.w(TAG, "User is restricted: " + restrictionKey);
3176             return true;
3177         }
3178         return false;
3179     }
3180 
3181     private void enforceCanSetPackagesSuspendedAsUser(@NonNull Computer snapshot,
3182             boolean quarantined, UserPackage suspender, int callingUid, int targetUserId,
3183             String callingMethod) {
3184         if (callingUid == Process.ROOT_UID
3185                 // Need to compare app-id to allow system dialogs access on secondary users
3186                 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
3187             return;
3188         }
3189 
3190         final String ownerPackage =
3191                 mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(targetUserId);
3192         if (ownerPackage != null) {
3193             final int ownerUid = snapshot.getPackageUid(ownerPackage, 0, targetUserId);
3194             if (ownerUid == callingUid) {
3195                 return;
3196             }
3197         }
3198 
3199         if (quarantined) {
3200             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.QUARANTINE_APPS,
3201                     callingMethod);
3202         } else {
3203             mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS,
3204                     callingMethod);
3205         }
3206 
3207         if (crossUserSuspensionEnabledRo()) {
3208             final int suspendingPackageUid =
3209                     snapshot.getPackageUid(suspender.packageName, 0, suspender.userId);
3210             if (suspendingPackageUid != callingUid) {
3211                 throw new SecurityException("Suspender package %s doesn't match calling uid %d"
3212                                 .formatted(suspender.packageName, callingUid));
3213             }
3214             if (targetUserId != suspender.userId) {
3215                 mContext.enforceCallingOrSelfPermission(
3216                         Manifest.permission.INTERACT_ACROSS_USERS_FULL, callingMethod);
3217             }
3218         } else {
3219             // Here only SHELL can suspend across users
3220             final int packageUid =
3221                     snapshot.getPackageUid(suspender.packageName, 0, targetUserId);
3222             final boolean allowedPackageUid = packageUid == callingUid;
3223             final boolean allowedShell = callingUid == SHELL_UID
3224                     && UserHandle.isSameApp(packageUid, callingUid);
3225 
3226             if (!allowedShell && !allowedPackageUid) {
3227                 throw new SecurityException("Suspending package " + suspender.packageName
3228                         + " in user " + targetUserId + " does not belong to calling uid "
3229                         + callingUid);
3230             }
3231         }
3232     }
3233 
3234     /**
3235      * @param suspendingUserId The user that has suspended apps using the suspending package.
3236      * @param targetUserId The user whose apps should be unsuspended. Pass {@code USER_ALL} to
3237      *                     unsuspend for all users.
3238      */
3239     void unsuspendForSuspendingPackage(@NonNull Computer computer, String suspendingPackage,
3240             @UserIdInt int suspendingUserId, @CanBeALL @UserIdInt int targetUserId) {
3241         // TODO: This can be replaced by a special parameter to iterate all packages, rather than
3242         //  this weird pre-collect of all packages.
3243         final String[] allPackages = computer.getPackageStates().keySet().toArray(new String[0]);
3244         final Predicate<UserPackage> suspenderPredicate =
3245                 UserPackage.of(suspendingUserId, suspendingPackage)::equals;
3246         if (!crossUserSuspensionEnabledRo() || targetUserId != USER_ALL) {
3247             mSuspendPackageHelper.removeSuspensionsBySuspendingPackage(computer,
3248                     allPackages, suspenderPredicate, targetUserId);
3249         } else {
3250             for (int user : mUserManager.getUserIds()) {
3251                 mSuspendPackageHelper.removeSuspensionsBySuspendingPackage(
3252                         computer, allPackages, suspenderPredicate, user);
3253             }
3254         }
3255     }
3256 
3257     void removeAllDistractingPackageRestrictions(@NonNull Computer snapshot, int userId) {
3258         final String[] allPackages = snapshot.getAllAvailablePackageNames();
3259         mDistractingPackageHelper.removeDistractingPackageRestrictions(snapshot, allPackages,
3260                 userId);
3261     }
3262 
3263     private void enforceCanSetDistractingPackageRestrictionsAsUser(int callingUid, int userId,
3264             String callingMethod) {
3265         mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS,
3266                 callingMethod);
3267 
3268         if (!PackageManagerServiceUtils.isSystemOrRoot(callingUid)
3269                 && UserHandle.getUserId(callingUid) != userId) {
3270             throw new SecurityException("Calling uid " + callingUid + " cannot call for user "
3271                     + userId);
3272         }
3273     }
3274 
3275     void setEnableRollbackCode(int token, int enableRollbackCode) {
3276         final Message msg = mHandler.obtainMessage(ENABLE_ROLLBACK_STATUS);
3277         msg.arg1 = token;
3278         msg.arg2 = enableRollbackCode;
3279         mHandler.sendMessage(msg);
3280     }
3281 
3282     /**
3283      * Callback from PackageSettings whenever an app is first transitioned out of the
3284      * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
3285      * the app was "launched" for a restoreAtInstall operation.  Therefore we check
3286      * here whether the app is the target of an ongoing install, and only send the
3287      * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
3288      * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
3289      * handling.
3290      */
3291     void notifyFirstLaunch(final String packageName, final String installerPackage,
3292             final int userId) {
3293         // Serialize this with the rest of the install-process message chain.  In the
3294         // restore-at-install case, this Runnable will necessarily run before the
3295         // POST_INSTALL message is processed, so the contents of mRunningInstalls
3296         // are coherent.  In the non-restore case, the app has already completed install
3297         // and been launched through some other means, so it is not in a problematic
3298         // state for observers to see the FIRST_LAUNCH signal.
3299         mHandler.post(() -> {
3300             synchronized (mRunningInstalls) {
3301                 for (int i = 0; i < mRunningInstalls.size(); i++) {
3302                     final InstallRequest installRequest = mRunningInstalls.valueAt(i);
3303                     if (installRequest.getReturnCode() != PackageManager.INSTALL_SUCCEEDED) {
3304                         continue;
3305                     }
3306                     final int[] newUsers = installRequest.getNewUsers();
3307                     if (packageName.equals(installRequest.getPkg().getPackageName())) {
3308                         // right package; but is it for the right user?
3309                         for (int uIndex = 0; uIndex < newUsers.length; uIndex++) {
3310                             if (userId == newUsers[uIndex]) {
3311                                 if (DEBUG_BACKUP) {
3312                                     Slog.i(TAG, "Package " + packageName
3313                                             + " being restored so deferring FIRST_LAUNCH");
3314                                 }
3315                                 return;
3316                             }
3317                         }
3318                     }
3319                 }
3320             }
3321             // didn't find it, so not being restored
3322             if (DEBUG_BACKUP) {
3323                 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
3324             }
3325             final boolean isInstantApp = snapshotComputer().isInstantAppInternal(
3326                     packageName, userId, Process.SYSTEM_UID);
3327             final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
3328             final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
3329             mBroadcastHelper.sendFirstLaunchBroadcast(
3330                     packageName, installerPackage, userIds, instantUserIds);
3331         });
3332     }
3333 
3334     @SuppressWarnings("GuardedBy")
3335     VersionInfo getSettingsVersionForPackage(AndroidPackage pkg) {
3336         if (pkg.isExternalStorage()) {
3337             if (TextUtils.isEmpty(pkg.getVolumeUuid())) {
3338                 return mSettings.getExternalVersion();
3339             } else {
3340                 return mSettings.findOrCreateVersion(pkg.getVolumeUuid());
3341             }
3342         } else {
3343             return mSettings.getInternalVersion();
3344         }
3345     }
3346 
3347     public void deleteExistingPackageAsUser(VersionedPackage versionedPackage,
3348             final IPackageDeleteObserver2 observer, final int userId) {
3349         mDeletePackageHelper.deleteExistingPackageAsUser(
3350                 versionedPackage, observer, userId);
3351     }
3352 
3353     public void deletePackageVersioned(VersionedPackage versionedPackage,
3354             final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags,
3355             final int callingUid) {
3356         mDeletePackageHelper.deletePackageVersionedInternal(
3357                 versionedPackage, observer, userId, deleteFlags, callingUid,
3358                 /* allowSilentUninstall= */ false);
3359     }
3360 
3361     public void deletePackageVersioned(VersionedPackage versionedPackage,
3362             final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
3363         mDeletePackageHelper.deletePackageVersionedInternal(
3364                 versionedPackage, observer, userId, deleteFlags, /* allowSilentUninstall= */ false);
3365     }
3366 
3367     boolean isCallerVerifier(@NonNull Computer snapshot, int callingUid) {
3368         final int callingUserId = UserHandle.getUserId(callingUid);
3369         for (String requiredVerifierPackage : mRequiredVerifierPackages) {
3370             if (callingUid == snapshot.getPackageUid(requiredVerifierPackage, 0, callingUserId)) {
3371                 return true;
3372             }
3373         }
3374         return false;
3375     }
3376 
3377     public boolean isPackageDeviceAdminOnAnyUser(@NonNull Computer snapshot, String packageName) {
3378         final int callingUid = Binder.getCallingUid();
3379         if (snapshot.checkUidPermission(android.Manifest.permission.MANAGE_USERS, callingUid)
3380                 != PERMISSION_GRANTED) {
3381             EventLog.writeEvent(0x534e4554, "128599183", -1, "");
3382             throw new SecurityException(android.Manifest.permission.MANAGE_USERS
3383                     + " permission is required to call this API");
3384         }
3385         if (snapshot.getInstantAppPackageName(callingUid) != null
3386                 && !snapshot.isCallerSameApp(packageName, callingUid)) {
3387             return false;
3388         }
3389         return isPackageDeviceAdmin(packageName, USER_ALL);
3390     }
3391 
3392     // TODO(b/261957226): centralise this logic in DPM
3393     boolean isPackageDeviceAdmin(String packageName, @CanBeALL @UserIdInt int userId) {
3394         final IDevicePolicyManager dpm = getDevicePolicyManager();
3395         final DevicePolicyManagerInternal dpmi =
3396                 mInjector.getLocalService(DevicePolicyManagerInternal.class);
3397         try {
3398             if (dpm != null && dpmi != null) {
3399                 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
3400                         /* callingUserOnly =*/ false);
3401                 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
3402                         : deviceOwnerComponentName.getPackageName();
3403                 // Does the package contains the device owner?
3404                 // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
3405                 // this check is probably not needed, since DO should be registered as a device
3406                 // admin on some user too. (Original bug for this: b/17657954)
3407                 if (packageName.equals(deviceOwnerPackageName)) {
3408                     return true;
3409                 }
3410                 // Does it contain a device admin for any user?
3411                 int[] allUsers = mUserManager.getUserIds();
3412                 int[] targetUsers;
3413                 if (userId == USER_ALL) {
3414                     targetUsers = allUsers;
3415                 } else {
3416                     targetUsers = new int[]{userId};
3417                 }
3418 
3419                 for (int i = 0; i < targetUsers.length; ++i) {
3420                     if (dpm.packageHasActiveAdmins(packageName, targetUsers[i])) {
3421                         return true;
3422                     }
3423                 }
3424 
3425                 // If a package is DMRH on a managed user, it should also be treated as an admin on
3426                 // that user. If that package is also a system package, it should also be protected
3427                 // on other users otherwise "uninstall updates" on an unmanaged user may break
3428                 // management on other users because apk version is shared between all users.
3429                 var packageState = snapshotComputer().getPackageStateInternal(packageName);
3430                 if (packageState == null) {
3431                     return false;
3432                 }
3433                 for (int user : packageState.isSystem() ? allUsers : targetUsers) {
3434                     if (isDeviceManagementRoleHolder(packageName, user)
3435                             && dpmi.isUserOrganizationManaged(user)) {
3436                         return true;
3437                     }
3438                 }
3439             }
3440         } catch (RemoteException e) {
3441         }
3442         return false;
3443     }
3444 
3445     private boolean isDeviceManagementRoleHolder(String packageName, int userId) {
3446         return Objects.equals(packageName, getDevicePolicyManagementRoleHolderPackageName(userId));
3447     }
3448 
3449     @Nullable
3450     public String getDevicePolicyManagementRoleHolderPackageName(int userId) {
3451         return Binder.withCleanCallingIdentity(() -> {
3452             RoleManager roleManager = mContext.getSystemService(RoleManager.class);
3453             List<String> roleHolders =
3454                     roleManager.getRoleHoldersAsUser(
3455                             RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT, UserHandle.of(userId));
3456             if (roleHolders.isEmpty()) {
3457                 return null;
3458             }
3459             return roleHolders.get(0);
3460         });
3461     }
3462 
3463     /** Returns the device policy manager interface. */
3464     private IDevicePolicyManager getDevicePolicyManager() {
3465         if (mDevicePolicyManager == null) {
3466             // No need to synchronize; worst-case scenario it will be fetched twice.
3467             mDevicePolicyManager = IDevicePolicyManager.Stub.asInterface(
3468                             ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
3469         }
3470         return mDevicePolicyManager;
3471     }
3472 
3473     private boolean clearApplicationUserDataLIF(@NonNull Computer snapshot, String packageName,
3474             int userId) {
3475         if (packageName == null) {
3476             Slog.w(TAG, "Attempt to delete null packageName.");
3477             return false;
3478         }
3479 
3480         // Try finding details about the requested package
3481         AndroidPackage pkg = snapshot.getPackage(packageName);
3482         if (pkg == null) {
3483             Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
3484             return false;
3485         }
3486         mPermissionManager.resetRuntimePermissions(pkg, userId);
3487 
3488         mAppDataHelper.clearAppDataLIF(pkg, userId,
3489                 FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL);
3490 
3491         final int appId = UserHandle.getAppId(pkg.getUid());
3492         mAppDataHelper.clearKeystoreData(userId, appId);
3493 
3494         UserManagerInternal umInternal = mInjector.getUserManagerInternal();
3495         StorageManagerInternal smInternal = mInjector.getLocalService(StorageManagerInternal.class);
3496         final int flags;
3497         if (StorageManager.isCeStorageUnlocked(userId) && smInternal.isCeStoragePrepared(userId)) {
3498             flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3499         } else if (umInternal.isUserRunning(userId)) {
3500             flags = StorageManager.FLAG_STORAGE_DE;
3501         } else {
3502             flags = 0;
3503         }
3504         mAppDataHelper.prepareAppDataContentsLIF(pkg, snapshot.getPackageStateInternal(packageName),
3505                 userId, flags);
3506 
3507         return true;
3508     }
3509 
3510     /**
3511      * Update component enabled settings to {@link PackageManager#COMPONENT_ENABLED_STATE_DEFAULT}
3512      * if the resetEnabledSettingsOnAppDataCleared is {@code true}.
3513      */
3514     @GuardedBy("mLock")
3515     private void resetComponentEnabledSettingsIfNeededLPw(String packageName, int userId,
3516             int callingUid) {
3517         final AndroidPackage pkg = packageName != null ? mPackages.get(packageName) : null;
3518         if (pkg == null || !pkg.isResetEnabledSettingsOnAppDataCleared()) {
3519             return;
3520         }
3521         final PackageSetting pkgSetting = mSettings.getPackageLPr(packageName);
3522         if (pkgSetting == null) {
3523             return;
3524         }
3525         final ArrayList<String> updatedComponents = new ArrayList<>();
3526         final Consumer<? super ParsedMainComponent> resetSettings = (component) -> {
3527             if (pkgSetting.restoreComponentLPw(component.getClassName(), userId)) {
3528                 updatedComponents.add(component.getClassName());
3529             }
3530         };
3531         for (int i = 0; i < pkg.getActivities().size(); i++) {
3532             resetSettings.accept(pkg.getActivities().get(i));
3533         }
3534         for (int i = 0; i < pkg.getReceivers().size(); i++) {
3535             resetSettings.accept(pkg.getReceivers().get(i));
3536         }
3537         for (int i = 0; i < pkg.getServices().size(); i++) {
3538             resetSettings.accept(pkg.getServices().get(i));
3539         }
3540         for (int i = 0; i < pkg.getProviders().size(); i++) {
3541             resetSettings.accept(pkg.getProviders().get(i));
3542         }
3543         if (ArrayUtils.isEmpty(updatedComponents)) {
3544             // nothing changed
3545             return;
3546         }
3547 
3548         updateSequenceNumberLP(pkgSetting, new int[] { userId });
3549         updateInstantAppInstallerLocked(packageName);
3550         scheduleWritePackageRestrictions(userId);
3551 
3552         mPendingBroadcasts.addComponents(userId, packageName, updatedComponents);
3553         if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
3554             mHandler.sendMessageDelayed(
3555                     mHandler.obtainMessage(SEND_PENDING_BROADCAST, callingUid, 0 /* arg2 */,
3556                             "reset_component_state_changed" /* obj */), BROADCAST_DELAY);
3557         }
3558     }
3559 
3560     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
3561     @GuardedBy("mLock")
3562     void clearPackagePreferredActivitiesLPw(String packageName,
3563             @NonNull SparseBooleanArray outUserChanged, @CanBeALL @UserIdInt int userId) {
3564         mSettings.clearPackagePreferredActivities(packageName, outUserChanged, userId);
3565     }
3566 
3567     void restorePermissionsAndUpdateRolesForNewUserInstall(String packageName,
3568             @UserIdInt int userId) {
3569         // We may also need to apply pending (restored) runtime permission grants
3570         // within these users.
3571         mPermissionManager.restoreDelayedRuntimePermissions(packageName, userId);
3572 
3573         // Restore default browser setting if it is now installed.
3574         String defaultBrowser;
3575         synchronized (mLock) {
3576             defaultBrowser = mSettings.getPendingDefaultBrowserLPr(userId);
3577         }
3578         if (Objects.equals(packageName, defaultBrowser)) {
3579             mDefaultAppProvider.setDefaultBrowser(packageName, userId);
3580             synchronized (mLock) {
3581                 mSettings.removePendingDefaultBrowserLPw(userId);
3582             }
3583         }
3584 
3585         // Persistent preferred activity might have came into effect due to this
3586         // install.
3587         mPreferredActivityHelper.updateDefaultHomeNotLocked(snapshotComputer(), userId);
3588     }
3589 
3590     /**
3591      * Variant that takes a {@link WatchedIntentFilter}
3592      */
3593     public void addCrossProfileIntentFilter(@NonNull Computer snapshot,
3594             WatchedIntentFilter intentFilter, String ownerPackage, int sourceUserId,
3595             int targetUserId, int flags) {
3596         mContext.enforceCallingOrSelfPermission(
3597                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3598         int callingUid = Binder.getCallingUid();
3599         enforceOwnerRights(snapshot, ownerPackage, callingUid);
3600 
3601         // Verifying that current calling uid should be able to add {@link CrossProfileIntentFilter}
3602         // for source and target user
3603         mUserManager.enforceCrossProfileIntentFilterAccess(sourceUserId, targetUserId, callingUid,
3604                 /* addCrossProfileIntentFilter */ true);
3605 
3606         PackageManagerServiceUtils.enforceShellRestriction(mInjector.getUserManagerInternal(),
3607                 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
3608         if (!intentFilter.checkDataPathAndSchemeSpecificParts()) {
3609             EventLog.writeEvent(0x534e4554, "246749936", callingUid);
3610             throw new IllegalArgumentException("Invalid intent data paths or scheme specific parts"
3611                     + " in the filter.");
3612         }
3613         if (intentFilter.countActions() == 0) {
3614             Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
3615             return;
3616         }
3617         synchronized (mLock) {
3618             CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
3619                     ownerPackage, targetUserId, flags, mUserManager
3620                     .getCrossProfileIntentFilterAccessControl(sourceUserId, targetUserId));
3621             CrossProfileIntentResolver resolver =
3622                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
3623             ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
3624             // We have all those whose filter is equal. Now checking if the rest is equal as well.
3625             if (existing != null) {
3626                 int size = existing.size();
3627                 for (int i = 0; i < size; i++) {
3628                     if (newFilter.equalsIgnoreFilter(existing.get(i))) {
3629                         return;
3630                     }
3631                 }
3632             }
3633             resolver.addFilter(snapshotComputer(), newFilter);
3634         }
3635         scheduleWritePackageRestrictions(sourceUserId);
3636     }
3637 
3638 
3639     // Enforcing that callingUid is owning pkg on userId
3640     private void enforceOwnerRights(@NonNull Computer snapshot, String pkg, int callingUid) {
3641         // The system owns everything.
3642         if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
3643             return;
3644         }
3645         final String[] callerPackageNames = snapshot.getPackagesForUid(callingUid);
3646         if (!ArrayUtils.contains(callerPackageNames, pkg)) {
3647             throw new SecurityException("Calling uid " + callingUid
3648                     + " does not own package " + pkg);
3649         }
3650         final int callingUserId = UserHandle.getUserId(callingUid);
3651         PackageInfo pi = snapshot.getPackageInfo(pkg, 0, callingUserId);
3652         if (pi == null) {
3653             throw new IllegalArgumentException("Unknown package " + pkg + " on user "
3654                     + callingUserId);
3655         }
3656     }
3657 
3658     public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
3659         mBroadcastHelper.sendSessionCommitBroadcast(snapshotComputer(), sessionInfo, userId,
3660                 mAppPredictionServicePackage);
3661     }
3662 
3663     private @Nullable String getSetupWizardPackageNameImpl(@NonNull Computer computer) {
3664         final Intent intent = new Intent(Intent.ACTION_MAIN);
3665         intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
3666 
3667         final List<ResolveInfo> matches = computer.queryIntentActivitiesInternal(intent, null,
3668                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
3669                         | MATCH_DISABLED_COMPONENTS,
3670                 UserHandle.myUserId());
3671         if (matches.size() == 1) {
3672             return matches.get(0).getComponentInfo().packageName;
3673         } else {
3674             Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
3675                     + ": matches=" + matches);
3676             return null;
3677         }
3678     }
3679 
3680     private @Nullable String getStorageManagerPackageName(@NonNull Computer computer) {
3681         final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
3682 
3683         final List<ResolveInfo> matches = computer.queryIntentActivitiesInternal(intent, null,
3684                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
3685                         | MATCH_DISABLED_COMPONENTS,
3686                 UserHandle.myUserId());
3687         if (matches.size() == 1) {
3688             return matches.get(0).getComponentInfo().packageName;
3689         } else {
3690             Slog.w(TAG, "There should probably be exactly one storage manager; found "
3691                     + matches.size() + ": matches=" + matches);
3692             return null;
3693         }
3694     }
3695 
3696     @NonNull
3697     private static String getRequiredSdkSandboxPackageName(@NonNull Computer computer) {
3698         final Intent intent = new Intent(SdkSandboxManagerLocal.SERVICE_INTERFACE);
3699 
3700         final List<ResolveInfo> matches = computer.queryIntentServicesInternal(
3701                 intent,
3702                 /* resolvedType= */ null,
3703                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3704                 UserHandle.USER_SYSTEM,
3705                 /* callingUid= */ Process.myUid(),
3706                 Process.INVALID_PID,
3707                 /* includeInstantApps= */ false,
3708                 /* resolveForStart */ false);
3709         if (matches.size() == 1) {
3710             return matches.get(0).getComponentInfo().packageName;
3711         } else {
3712             throw new RuntimeException("There should exactly one sdk sandbox package; found "
3713                     + matches.size() + ": matches=" + matches);
3714         }
3715     }
3716 
3717     @Nullable
3718     private String getRetailDemoPackageName() {
3719         final String predefinedPkgName = mContext.getString(R.string.config_retailDemoPackage);
3720         final String predefinedSignature = mContext.getString(
3721                 R.string.config_retailDemoPackageSignature);
3722 
3723         if (TextUtils.isEmpty(predefinedPkgName) || TextUtils.isEmpty(predefinedSignature)) {
3724             return null;
3725         }
3726 
3727         final AndroidPackage androidPkg = mPackages.get(predefinedPkgName);
3728         if (androidPkg != null) {
3729             final SigningDetails signingDetail = androidPkg.getSigningDetails();
3730             if (signingDetail != null && signingDetail.getSignatures() != null) {
3731                 try {
3732                     final MessageDigest msgDigest = MessageDigest.getInstance("SHA-256");
3733                     for (Signature signature : signingDetail.getSignatures()) {
3734                         if (TextUtils.equals(predefinedSignature,
3735                                 HexEncoding.encodeToString(msgDigest.digest(
3736                                         signature.toByteArray()), false))) {
3737                             return predefinedPkgName;
3738                         }
3739                     }
3740                 } catch (NoSuchAlgorithmException e) {
3741                     Slog.e(
3742                             TAG,
3743                             "Unable to verify signatures as getting the retail demo package name",
3744                             e);
3745                 }
3746             }
3747         }
3748 
3749         return null;
3750     }
3751 
3752     @Nullable
3753     String getPackageFromComponentString(@StringRes int stringResId) {
3754         final String componentString = mContext.getString(stringResId);
3755         if (TextUtils.isEmpty(componentString)) {
3756             return null;
3757         }
3758         final ComponentName component = ComponentName.unflattenFromString(componentString);
3759         if (component == null) {
3760             return null;
3761         }
3762         return component.getPackageName();
3763     }
3764 
3765     @Nullable
3766     String ensureSystemPackageName(@NonNull Computer snapshot,
3767             @Nullable String packageName) {
3768         if (packageName == null) {
3769             return null;
3770         }
3771         final long token = Binder.clearCallingIdentity();
3772         try {
3773             if (snapshot.getPackageInfo(packageName, MATCH_FACTORY_ONLY,
3774                     UserHandle.USER_SYSTEM) == null) {
3775                 PackageInfo packageInfo =
3776                         snapshot.getPackageInfo(packageName, 0, UserHandle.USER_SYSTEM);
3777                 if (packageInfo != null) {
3778                     EventLog.writeEvent(0x534e4554, "145981139", packageInfo.applicationInfo.uid,
3779                             "");
3780                 }
3781                 Log.w(TAG, "Missing required system package: " + packageName + (packageInfo != null
3782                         ? ", but found with extended search." : "."));
3783                 return null;
3784             }
3785         } finally {
3786             Binder.restoreCallingIdentity(token);
3787         }
3788         return packageName;
3789     }
3790 
3791     @VisibleForTesting(visibility = Visibility.PRIVATE)
3792     public void updateComponentLabelIcon(/*@NonNull*/ ComponentName componentName,
3793             @Nullable String nonLocalizedLabel, @Nullable Integer icon, int userId) {
3794         if (componentName == null) {
3795             throw new IllegalArgumentException("Must specify a component");
3796         }
3797 
3798         int callingUid = Binder.getCallingUid();
3799         String componentPkgName = componentName.getPackageName();
3800 
3801         Computer computer = snapshotComputer();
3802 
3803         int componentUid = computer.getPackageUid(componentPkgName, 0, userId);
3804         if (!UserHandle.isSameApp(callingUid, componentUid)) {
3805             throw new SecurityException("The calling UID (" + callingUid + ")"
3806                     + " does not match the target UID");
3807         }
3808 
3809         String allowedCallerPkg =
3810                 mContext.getString(R.string.config_overrideComponentUiPackage);
3811         if (TextUtils.isEmpty(allowedCallerPkg)) {
3812             throw new SecurityException( "There is no package defined as allowed to change a "
3813                     + "component's label or icon");
3814         }
3815 
3816         int allowedCallerUid = computer.getPackageUid(allowedCallerPkg,
3817                 PackageManager.MATCH_SYSTEM_ONLY, userId);
3818         if (allowedCallerUid == -1 || !UserHandle.isSameApp(callingUid, allowedCallerUid)) {
3819             throw new SecurityException("The calling UID (" + callingUid + ")"
3820                     + " is not allowed to change a component's label or icon");
3821         }
3822         PackageStateInternal packageState = computer.getPackageStateInternal(componentPkgName);
3823         if (packageState == null || packageState.getPkg() == null
3824                 || (!packageState.isSystem()
3825                 && !packageState.isUpdatedSystemApp())) {
3826             throw new SecurityException(
3827                     "Changing the label is not allowed for " + componentName);
3828         }
3829 
3830         if (!computer.getComponentResolver().componentExists(componentName)) {
3831             throw new IllegalArgumentException("Component " + componentName + " not found");
3832         }
3833 
3834         Pair<String, Integer> overrideLabelIcon = packageState.getUserStateOrDefault(userId)
3835                 .getOverrideLabelIconForComponent(componentName);
3836 
3837         String existingLabel = overrideLabelIcon == null ? null : overrideLabelIcon.first;
3838         Integer existingIcon = overrideLabelIcon == null ? null : overrideLabelIcon.second;
3839 
3840         if (TextUtils.equals(existingLabel, nonLocalizedLabel)
3841                 && Objects.equals(existingIcon, icon)) {
3842             // Nothing changed
3843             return;
3844         }
3845 
3846         commitPackageStateMutation(null, componentPkgName,
3847                 state -> state.userState(userId)
3848                         .setComponentLabelIcon(componentName, nonLocalizedLabel, icon));
3849 
3850         mPendingBroadcasts.addComponent(userId, componentPkgName, componentName.getClassName());
3851 
3852         if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
3853             mHandler.sendMessageDelayed(
3854                     mHandler.obtainMessage(SEND_PENDING_BROADCAST, callingUid, 0 /* arg2 */,
3855                             "component_label_icon_changed" /* obj */), BROADCAST_DELAY);
3856         }
3857     }
3858 
3859     private void setEnabledSettings(List<ComponentEnabledSetting> settings, int userId,
3860             @NonNull String callingPackage) {
3861         final int callingUid = Binder.getCallingUid();
3862         // TODO: This method is not properly snapshotified beyond this call
3863         final Computer preLockSnapshot = snapshotComputer();
3864         preLockSnapshot.enforceCrossUserPermission(callingUid, userId,
3865                 false /* requireFullPermission */, true /* checkShell */, "set enabled");
3866 
3867         final int targetSize = settings.size();
3868         for (int i = 0; i < targetSize; i++) {
3869             final int newState = settings.get(i).getEnabledState();
3870             if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
3871                     || newState == COMPONENT_ENABLED_STATE_ENABLED
3872                     || newState == COMPONENT_ENABLED_STATE_DISABLED
3873                     || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
3874                     || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
3875                 throw new IllegalArgumentException("Invalid new component state: " + newState);
3876             }
3877         }
3878         if (targetSize > 1) {
3879             final ArraySet<String> checkDuplicatedPackage = new ArraySet<>();
3880             final ArraySet<ComponentName> checkDuplicatedComponent = new ArraySet<>();
3881             final ArrayMap<String, Integer> checkConflictFlag = new ArrayMap<>();
3882             for (int i = 0; i < targetSize; i++) {
3883                 final ComponentEnabledSetting setting = settings.get(i);
3884                 final String packageName = setting.getPackageName();
3885                 if (setting.isComponent()) {
3886                     final ComponentName componentName = setting.getComponentName();
3887                     if (checkDuplicatedComponent.contains(componentName)) {
3888                         throw new IllegalArgumentException("The component " + componentName
3889                                 + " is duplicated");
3890                     }
3891                     checkDuplicatedComponent.add(componentName);
3892 
3893                     // check if there is a conflict of the DONT_KILL_APP flag between components
3894                     // in the package
3895                     final Integer enabledFlags = checkConflictFlag.get(packageName);
3896                     if (enabledFlags == null) {
3897                         checkConflictFlag.put(packageName, setting.getEnabledFlags());
3898                     } else if ((enabledFlags & PackageManager.DONT_KILL_APP)
3899                             != (setting.getEnabledFlags() & PackageManager.DONT_KILL_APP)) {
3900                         throw new IllegalArgumentException("A conflict of the DONT_KILL_APP flag "
3901                                 + "between components in the package " + packageName);
3902                     }
3903                 } else {
3904                     if (checkDuplicatedPackage.contains(packageName)) {
3905                         throw new IllegalArgumentException("The package " + packageName
3906                                 + " is duplicated");
3907                     }
3908                     checkDuplicatedPackage.add(packageName);
3909                 }
3910             }
3911         }
3912 
3913         final boolean allowedByPermission = mContext.checkCallingOrSelfPermission(
3914                 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE) == PERMISSION_GRANTED;
3915         final boolean[] updateAllowed = new boolean[targetSize];
3916         Arrays.fill(updateAllowed, true);
3917 
3918         final Map<String, PackageSetting> pkgSettings = new ArrayMap<>(targetSize);
3919         // reader
3920         synchronized (mLock) {
3921             final Computer snapshot = snapshotComputer();
3922             // Checks for target packages
3923             for (int i = 0; i < targetSize; i++) {
3924                 final ComponentEnabledSetting setting = settings.get(i);
3925                 final String packageName = setting.getPackageName();
3926                 if (pkgSettings.containsKey(packageName)) {
3927                     // this package has verified
3928                     continue;
3929                 }
3930                 final boolean isCallerTargetApp = ArrayUtils.contains(
3931                         snapshot.getPackagesForUid(callingUid), packageName);
3932                 final PackageSetting pkgSetting = mSettings.getPackageLPr(packageName);
3933                 // Limit who can change which apps
3934                 if (!isCallerTargetApp && !allowedByPermission) {
3935                     // Don't allow apps that don't have permission to modify other apps
3936                     throw new SecurityException("Attempt to change component state; "
3937                             + "pid=" + Binder.getCallingPid()
3938                             + ", uid=" + callingUid
3939                             + (!setting.isComponent() ? ", package=" + packageName
3940                             : ", component=" + setting.getComponentName()));
3941                 }
3942                 if (pkgSetting == null || snapshot.shouldFilterApplicationIncludingUninstalled(
3943                         pkgSetting, callingUid, userId)) {
3944                     throw new IllegalArgumentException(setting.isComponent()
3945                             ? "Unknown component: " + setting.getComponentName()
3946                             : "Unknown package: " + packageName);
3947                 }
3948                 // Don't allow changing protected packages.
3949                 if (!isCallerTargetApp
3950                         && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
3951                     throw new SecurityException(
3952                             "Cannot disable a protected package: " + packageName);
3953                 }
3954                 if (callingUid == Process.SHELL_UID
3955                         && (pkgSetting.getFlags() & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
3956                     // Shell can only change whole packages between ENABLED and DISABLED_USER states
3957                     // unless it is a test package.
3958                     final int oldState = pkgSetting.getEnabled(userId);
3959                     final int newState = setting.getEnabledState();
3960                     if (!setting.isComponent()
3961                             &&
3962                             (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
3963                                     || oldState == COMPONENT_ENABLED_STATE_DEFAULT
3964                                     || oldState == COMPONENT_ENABLED_STATE_ENABLED)
3965                             &&
3966                             (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
3967                                     || newState == COMPONENT_ENABLED_STATE_DEFAULT
3968                                     || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
3969                         // ok
3970                     } else {
3971                         throw new SecurityException(
3972                                 "Shell cannot change component state for "
3973                                         + setting.getComponentName() + " to " + newState);
3974                     }
3975                 }
3976                 pkgSettings.put(packageName, pkgSetting);
3977             }
3978             // Checks for target components
3979             for (int i = 0; i < targetSize; i++) {
3980                 final ComponentEnabledSetting setting = settings.get(i);
3981                 // skip if it's application
3982                 if (!setting.isComponent()) continue;
3983 
3984                 // Only allow apps with CHANGE_COMPONENT_ENABLED_STATE permission to change hidden
3985                 // app details activity
3986                 final String packageName = setting.getPackageName();
3987                 final String className = setting.getClassName();
3988                 if (!allowedByPermission
3989                         && PackageManager.APP_DETAILS_ACTIVITY_CLASS_NAME.equals(className)) {
3990                     throw new SecurityException("Cannot disable a system-generated component");
3991                 }
3992                 // Verify that this is a valid class name.
3993                 final AndroidPackage pkg = pkgSettings.get(packageName).getPkg();
3994                 if (pkg == null || !AndroidPackageUtils.hasComponentClassName(pkg, className)) {
3995                     if (pkg != null
3996                             && pkg.getTargetSdkVersion() >= Build.VERSION_CODES.JELLY_BEAN) {
3997                         throw new IllegalArgumentException("Component class " + className
3998                                 + " does not exist in " + packageName);
3999                     } else {
4000                         Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
4001                                 + className + " does not exist in " + packageName);
4002                         updateAllowed[i] = false;
4003                     }
4004                 }
4005             }
4006         }
4007 
4008         // More work for application enabled setting updates
4009         for (int i = 0; i < targetSize; i++) {
4010             final ComponentEnabledSetting setting = settings.get(i);
4011             // skip if it's component
4012             if (setting.isComponent()) continue;
4013 
4014             final PackageSetting pkgSetting = pkgSettings.get(setting.getPackageName());
4015             final int newState = setting.getEnabledState();
4016             synchronized (mLock) {
4017                 if (pkgSetting.getEnabled(userId) == newState) {
4018                     // Nothing to do
4019                     updateAllowed[i] = false;
4020                     continue;
4021                 }
4022             }
4023             // If we're enabling a system stub, there's a little more work to do.
4024             // Prior to enabling the package, we need to decompress the APK(s) to the
4025             // data partition and then replace the version on the system partition.
4026             final AndroidPackage deletedPkg = pkgSetting.getPkg();
4027             final boolean isSystemStub = (deletedPkg != null)
4028                     && deletedPkg.isStub()
4029                     && pkgSetting.isSystem();
4030             if (isSystemStub
4031                     && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
4032                     || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
4033                 if (!enableCompressedPackage(deletedPkg, pkgSetting)) {
4034                     Slog.w(TAG, "Failed setApplicationEnabledSetting: failed to enable "
4035                             + "commpressed package " + setting.getPackageName());
4036                     updateAllowed[i] = false;
4037                 }
4038             }
4039         }
4040 
4041         // packageName -> list of components to send broadcasts now
4042         final ArrayMap<String, ArrayList<String>> sendNowBroadcasts = new ArrayMap<>(targetSize);
4043         final List<PackageMetrics.ComponentStateMetrics> componentStateMetricsList =
4044                 new ArrayList<PackageMetrics.ComponentStateMetrics>();
4045         synchronized (mLock) {
4046             Computer computer = snapshotComputer();
4047             boolean scheduleBroadcastMessage = false;
4048             boolean isSynchronous = false;
4049             boolean anyChanged = false;
4050 
4051             for (int i = 0; i < targetSize; i++) {
4052                 if (!updateAllowed[i]) {
4053                     continue;
4054                 }
4055                 // update enabled settings
4056                 final ComponentEnabledSetting setting = settings.get(i);
4057                 final String packageName = setting.getPackageName();
4058                 final PackageSetting packageSetting = pkgSettings.get(packageName);
4059                 final PackageMetrics.ComponentStateMetrics componentStateMetrics =
4060                         new PackageMetrics.ComponentStateMetrics(setting,
4061                                 UserHandle.getUid(userId, packageSetting.getAppId()),
4062                                 setting.isComponent() ? computer.getComponentEnabledSettingInternal(
4063                                         setting.getComponentName(), callingUid, userId)
4064                                         : packageSetting.getEnabled(userId), callingUid);
4065                 if (!setEnabledSettingInternalLocked(computer, packageSetting, setting, userId,
4066                         callingPackage)) {
4067                     continue;
4068                 }
4069                 anyChanged = true;
4070                 componentStateMetricsList.add(componentStateMetrics);
4071 
4072                 if ((setting.getEnabledFlags() & PackageManager.SYNCHRONOUS) != 0) {
4073                     isSynchronous = true;
4074                 }
4075                 // collect broadcast list for the package
4076                 final String componentName = setting.isComponent()
4077                         ? setting.getClassName() : packageName;
4078                 if ((setting.getEnabledFlags() & PackageManager.DONT_KILL_APP) == 0) {
4079                     ArrayList<String> componentList = sendNowBroadcasts.get(packageName);
4080                     componentList = componentList == null ? new ArrayList<>() : componentList;
4081                     if (!componentList.contains(componentName)) {
4082                         componentList.add(componentName);
4083                     }
4084                     sendNowBroadcasts.put(packageName, componentList);
4085                     // Purge entry from pending broadcast list if another one exists already
4086                     // since we are sending one right away.
4087                     mPendingBroadcasts.remove(userId, packageName);
4088                 } else {
4089                     mPendingBroadcasts.addComponent(userId, packageName, componentName);
4090                     Trace.instant(Trace.TRACE_TAG_PACKAGE_MANAGER, "setEnabledSetting broadcast: "
4091                                    + componentName + ": " + setting.getEnabledState());
4092                     scheduleBroadcastMessage = true;
4093                 }
4094             }
4095             if (!anyChanged) {
4096                 // nothing changed, return immediately
4097                 return;
4098             }
4099 
4100             if (isSynchronous) {
4101                 flushPackageRestrictionsAsUserInternalLocked(userId);
4102             } else {
4103                 scheduleWritePackageRestrictions(userId);
4104             }
4105             if (scheduleBroadcastMessage) {
4106                 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
4107                     // Schedule a message - if it has been a "reasonably long time" since the
4108                     // service started, send the broadcast with a delay of one second to avoid
4109                     // delayed reactions from the receiver, else keep the default ten second delay
4110                     // to avoid extreme thrashing on service startup.
4111                     final long broadcastDelay = SystemClock.uptimeMillis() > mServiceStartWithDelay
4112                             ? BROADCAST_DELAY
4113                             : BROADCAST_DELAY_DURING_STARTUP;
4114                     mHandler.sendMessageDelayed(
4115                             mHandler.obtainMessage(SEND_PENDING_BROADCAST, callingUid,
4116                                     0 /* arg2 */, "component_state_changed" /* obj */),
4117                             broadcastDelay);
4118                 }
4119             }
4120         }
4121 
4122         // Log the metrics when the component state is changed.
4123         PackageMetrics.reportComponentStateChanged(snapshotComputer(), componentStateMetricsList,
4124                 userId);
4125 
4126         final long callingId = Binder.clearCallingIdentity();
4127         try {
4128             final Computer newSnapshot = snapshotComputer();
4129             for (int i = 0; i < sendNowBroadcasts.size(); i++) {
4130                 final String packageName = sendNowBroadcasts.keyAt(i);
4131                 final ArrayList<String> components = sendNowBroadcasts.valueAt(i);
4132                 final int packageUid = UserHandle.getUid(
4133                         userId, pkgSettings.get(packageName).getAppId());
4134                 mBroadcastHelper.sendPackageChangedBroadcast(newSnapshot, packageName,
4135                         false /* dontKillApp */, components, packageUid, null /* reason */,
4136                         "component_state_changed" /* reasonForTrace */, callingUid);
4137             }
4138         } finally {
4139             Binder.restoreCallingIdentity(callingId);
4140         }
4141     }
4142 
4143     @GuardedBy("mLock")
4144     private boolean setEnabledSettingInternalLocked(@NonNull Computer computer,
4145             PackageSetting pkgSetting, ComponentEnabledSetting setting, @UserIdInt int userId,
4146             String callingPackage) {
4147         final int newState = setting.getEnabledState();
4148         final String packageName = setting.getPackageName();
4149         boolean success = false;
4150         if (!setting.isComponent()) {
4151             // We're dealing with an application/package level state change
4152             pkgSetting.setEnabled(newState, userId, callingPackage);
4153             if ((newState == COMPONENT_ENABLED_STATE_DISABLED_USER
4154                     || newState == COMPONENT_ENABLED_STATE_DISABLED)
4155                     && checkPermission(Manifest.permission.SUSPEND_APPS, packageName, userId)
4156                     == PERMISSION_GRANTED) {
4157                 // This app should not generally be allowed to get disabled by the UI, but
4158                 // if it ever does, we don't want to end up with some of the user's apps
4159                 // permanently suspended.
4160                 unsuspendForSuspendingPackage(computer, packageName, userId, USER_ALL);
4161                 removeAllDistractingPackageRestrictions(computer, userId);
4162             }
4163             success = true;
4164         } else {
4165             // We're dealing with a component level state change
4166             final String className = setting.getClassName();
4167             switch (newState) {
4168                 case COMPONENT_ENABLED_STATE_ENABLED:
4169                     success = pkgSetting.enableComponentLPw(className, userId);
4170                     break;
4171                 case COMPONENT_ENABLED_STATE_DISABLED:
4172                     success = pkgSetting.disableComponentLPw(className, userId);
4173                     break;
4174                 case COMPONENT_ENABLED_STATE_DEFAULT:
4175                     success = pkgSetting.restoreComponentLPw(className, userId);
4176                     break;
4177                 default:
4178                     Slog.e(TAG, "Failed setComponentEnabledSetting: component "
4179                             + packageName + "/" + className
4180                             + " requested an invalid new component state: " + newState);
4181                     break;
4182             }
4183         }
4184         if (!success) {
4185             return false;
4186         }
4187 
4188         updateSequenceNumberLP(pkgSetting, new int[] { userId });
4189         final long callingId = Binder.clearCallingIdentity();
4190         try {
4191             updateInstantAppInstallerLocked(packageName);
4192         } finally {
4193             Binder.restoreCallingIdentity(callingId);
4194         }
4195 
4196         return true;
4197     }
4198 
4199     @GuardedBy("mLock")
4200     private void flushPackageRestrictionsAsUserInternalLocked(int userId) {
4201         // NOTE: this invokes synchronous disk access, so callers using this
4202         // method should consider running on a background thread
4203         mSettings.writePackageRestrictionsLPr(userId);
4204         synchronized (mDirtyUsers) {
4205             mDirtyUsers.remove(userId);
4206             if (mDirtyUsers.isEmpty()) {
4207                 mBackgroundHandler.removeMessages(WRITE_DIRTY_PACKAGE_RESTRICTIONS);
4208             }
4209         }
4210     }
4211 
4212     /**
4213      * Used by SystemServer
4214      */
4215     public void waitForAppDataPrepared() {
4216         if (mPrepareAppDataFuture == null) {
4217             return;
4218         }
4219         ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
4220         mPrepareAppDataFuture = null;
4221     }
4222 
4223     public void systemReady() {
4224         PackageManagerServiceUtils.enforceSystemOrRoot(
4225                 "Only the system can claim the system is ready");
4226 
4227         final ContentResolver resolver = mContext.getContentResolver();
4228         if (mReleaseOnSystemReady != null) {
4229             for (int i = mReleaseOnSystemReady.size() - 1; i >= 0; --i) {
4230                 final File dstCodePath = mReleaseOnSystemReady.get(i);
4231                 F2fsUtils.releaseCompressedBlocks(resolver, dstCodePath);
4232             }
4233             mReleaseOnSystemReady = null;
4234         }
4235         mSystemReady = true;
4236         ContentObserver co = new ContentObserver(mHandler) {
4237             @Override
4238             public void onChange(boolean selfChange) {
4239                 final boolean ephemeralFeatureDisabled =
4240                         Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0;
4241                 for (int userId : UserManagerService.getInstance().getUserIds()) {
4242                     final boolean instantAppsDisabledForUser =
4243                             ephemeralFeatureDisabled || Secure.getIntForUser(resolver,
4244                                     Secure.INSTANT_APPS_ENABLED, 1, userId) == 0;
4245                     mWebInstantAppsDisabled.put(userId, instantAppsDisabledForUser);
4246                 }
4247             }
4248         };
4249         mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
4250                         .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
4251                 false, co, USER_ALL);
4252         mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
4253                 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, USER_ALL);
4254         co.onChange(true);
4255 
4256         mAppsFilter.onSystemReady(LocalServices.getService(PackageManagerInternal.class));
4257 
4258         // Disable any carrier apps. We do this very early in boot to prevent the apps from being
4259         // disabled after already being started.
4260         CarrierAppUtils.disableCarrierAppsUntilPrivileged(
4261                 mContext.getOpPackageName(), UserHandle.USER_SYSTEM, mContext);
4262 
4263         // Read the compatibilty setting when the system is ready.
4264         boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
4265                 mContext.getContentResolver(),
4266                 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
4267         ParsingPackageUtils.setCompatibilityModeEnabled(compatibilityModeEnabled);
4268 
4269         if (DEBUG_SETTINGS) {
4270             Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
4271         }
4272 
4273         synchronized (mLock) {
4274             ArrayList<Integer> changed = mSettings.systemReady(mComponentResolver);
4275             for (int i = 0; i < changed.size(); i++) {
4276                 mSettings.writePackageRestrictionsLPr(changed.get(i));
4277             }
4278         }
4279 
4280         mUserManager.systemReady();
4281 
4282         // Watch for external volumes that come and go over time
4283         final StorageManager storage = mInjector.getSystemService(StorageManager.class);
4284         storage.registerListener(mStorageEventHelper);
4285 
4286         mInstallerService.systemReady();
4287         mPackageDexOptimizer.systemReady();
4288 
4289         // Now that we're mostly running, clean up stale users and apps
4290         mUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
4291         mStorageEventHelper.reconcileApps(snapshotComputer(), StorageManager.UUID_PRIVATE_INTERNAL);
4292 
4293         mPermissionManager.onSystemReady();
4294 
4295         int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
4296         final List<UserInfo> livingUsers = mInjector.getUserManagerInternal().getUsers(
4297                 /* excludePartial= */ true,
4298                 /* excludeDying= */ true,
4299                 /* excludePreCreated= */ false);
4300         final int livingUserCount = livingUsers.size();
4301         for (int i = 0; i < livingUserCount; i++) {
4302             final int userId = livingUsers.get(i).id;
4303             final boolean isPermissionUpgradeNeeded = !Objects.equals(
4304                     mPermissionManager.getDefaultPermissionGrantFingerprint(userId),
4305                     Build.FINGERPRINT);
4306             if (isPermissionUpgradeNeeded) {
4307                 grantPermissionsUserIds = ArrayUtils.appendInt(
4308                         grantPermissionsUserIds, userId);
4309             }
4310         }
4311         // If we upgraded grant all default permissions before kicking off.
4312         for (int userId : grantPermissionsUserIds) {
4313             mLegacyPermissionManager.grantDefaultPermissions(userId);
4314             mPermissionManager.setDefaultPermissionGrantFingerprint(Build.FINGERPRINT, userId);
4315         }
4316         if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
4317             // If we did not grant default permissions, we preload from this the
4318             // default permission exceptions lazily to ensure we don't hit the
4319             // disk on a new user creation.
4320             mLegacyPermissionManager.scheduleReadDefaultPermissionExceptions();
4321         }
4322 
4323         if (mInstantAppResolverConnection != null) {
4324             mContext.registerReceiver(new BroadcastReceiver() {
4325                 @Override
4326                 public void onReceive(Context context, Intent intent) {
4327                     mInstantAppResolverConnection.optimisticBind();
4328                     mContext.unregisterReceiver(this);
4329                 }
4330             }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
4331         }
4332 
4333         IntentFilter overlayFilter = new IntentFilter(Intent.ACTION_OVERLAY_CHANGED);
4334         overlayFilter.addDataScheme("package");
4335         mContext.registerReceiver(new BroadcastReceiver() {
4336             @Override
4337             public void onReceive(Context context, Intent intent) {
4338                 if (intent == null) {
4339                     return;
4340                 }
4341                 final String action = intent.getAction();
4342                 if (action == null) {
4343                     return;
4344                 }
4345                 Uri data = intent.getData();
4346                 if (data == null) {
4347                     return;
4348                 }
4349                 String packageName = data.getSchemeSpecificPart();
4350                 if (packageName == null) {
4351                     return;
4352                 }
4353                 final Computer snapshot = snapshotComputer();
4354                 AndroidPackage pkg = snapshot.getPackage(packageName);
4355                 if (pkg == null) {
4356                     return;
4357                 }
4358                 mBroadcastHelper.sendPackageChangedBroadcast(snapshot, pkg.getPackageName(),
4359                         true /* dontKillApp */,
4360                         new ArrayList<>(Collections.singletonList(pkg.getPackageName())),
4361                         pkg.getUid(),
4362                         Intent.ACTION_OVERLAY_CHANGED, "overlay_changed" /* reasonForTrace */,
4363                         Process.SYSTEM_UID);
4364             }
4365         }, overlayFilter);
4366 
4367         mModuleInfoProvider.systemReady();
4368 
4369         // Installer service might attempt to install some packages that have been staged for
4370         // installation on reboot. Make sure this is the last component to be call since the
4371         // installation might require other components to be ready.
4372         mInstallerService.restoreAndApplyStagedSessionIfNeeded();
4373 
4374         mExistingPackages = null;
4375 
4376         // Clear cache on flags changes.
4377         DeviceConfig.addOnPropertiesChangedListener(
4378                 NAMESPACE_PACKAGE_MANAGER_SERVICE, mInjector.getBackgroundExecutor(),
4379                 properties -> {
4380                     final Set<String> keyset = properties.getKeyset();
4381                     if (keyset.contains(PROPERTY_INCFS_DEFAULT_TIMEOUTS) || keyset.contains(
4382                             PROPERTY_KNOWN_DIGESTERS_LIST)) {
4383                         mPerUidReadTimeoutsCache = null;
4384                     }
4385                 });
4386 
4387         // Prune unused static shared libraries which have been cached a period of time
4388         schedulePruneUnusedStaticSharedLibraries(false /* delay */);
4389 
4390         DexUseManagerLocal dexUseManager = DexOptHelper.getDexUseManagerLocal();
4391         if (dexUseManager != null) {
4392             dexUseManager.systemReady();
4393         }
4394     }
4395 
4396     public PackageFreezer freezePackage(String packageName, @CanBeALL @UserIdInt int userId,
4397             String killReason, int exitInfoReason, InstallRequest request) {
4398         return freezePackage(packageName, userId, killReason, exitInfoReason, request,
4399                 /* waitAppKilled= */ false);
4400     }
4401 
4402     private PackageFreezer freezePackage(String packageName, @CanBeALL @UserIdInt int userId,
4403             String killReason, int exitInfoReason, InstallRequest request, boolean waitAppKilled) {
4404         return new PackageFreezer(packageName, userId, killReason, this, exitInfoReason, request,
4405                 waitAppKilled);
4406     }
4407 
4408     public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
4409             String killReason, int exitInfoReason) {
4410         if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
4411             return new PackageFreezer(this, null /* request */);
4412         } else {
4413             return freezePackage(packageName, userId, killReason, exitInfoReason,
4414                     null /* request */);
4415         }
4416     }
4417 
4418     /** Called by UserManagerService */
4419     void cleanUpUser(UserManagerService userManager, @UserIdInt int userId) {
4420         synchronized (mLock) {
4421             synchronized (mDirtyUsers) {
4422                 mDirtyUsers.remove(userId);
4423             }
4424             mUserNeedsBadging.delete(userId);
4425             mDeletePackageHelper.removeUnusedPackagesLPw(userManager, userId);
4426             mSettings.removeUserLPw(userId);
4427             mPendingBroadcasts.remove(userId);
4428             mAppsFilter.onUserDeleted(snapshotComputer(), userId);
4429             mPermissionManager.onUserRemoved(userId);
4430         }
4431         mInstantAppRegistry.onUserRemoved(userId);
4432         mPackageMonitorCallbackHelper.onUserRemoved(userId);
4433         if (crossUserSuspensionEnabledRo()) {
4434             cleanUpCrossUserSuspension(userId);
4435         }
4436     }
4437 
4438     private void cleanUpCrossUserSuspension(int removedUser) {
4439         final Computer computer = snapshotComputer();
4440         var allPackages = computer.getAllAvailablePackageNames();
4441         for (int targetUserId : mUserManager.getUserIds()) {
4442             if (targetUserId == removedUser) continue;
4443             mSuspendPackageHelper.removeSuspensionsBySuspendingPackage(computer, allPackages,
4444                     userPackage -> userPackage.userId == removedUser, targetUserId);
4445         }
4446     }
4447 
4448     /**
4449      * Called by UserManagerService.
4450      *
4451      * @param userTypeInstallablePackages system packages that should be initially installed for
4452      *                                    this type of user, or {@code null} if all system packages
4453      *                                    should be installed
4454      * @param disallowedPackages packages that should not be initially installed. Takes precedence
4455      *                           over installablePackages.
4456      */
4457     void createNewUser(int userId, @Nullable Set<String> userTypeInstallablePackages,
4458             String[] disallowedPackages) {
4459         try (PackageManagerTracedLock installLock = mInstallLock.acquireLock()) {
4460             mSettings.createNewUserLI(this, mInstaller, userId,
4461                     userTypeInstallablePackages, disallowedPackages);
4462         }
4463         synchronized (mLock) {
4464             scheduleWritePackageRestrictions(userId);
4465             scheduleWritePackageListLocked(userId);
4466             mAppsFilter.onUserCreated(snapshotComputer(), userId);
4467         }
4468     }
4469 
4470     void onNewUserCreated(@UserIdInt int userId, boolean convertedFromPreCreated) {
4471         if (DEBUG_PERMISSIONS) {
4472             Slog.d(TAG, "onNewUserCreated(id=" + userId
4473                     + ", convertedFromPreCreated=" + convertedFromPreCreated + ")");
4474         }
4475         if (!convertedFromPreCreated || !readPermissionStateForUser(userId)) {
4476             mPermissionManager.onUserCreated(userId);
4477             mLegacyPermissionManager.grantDefaultPermissions(userId);
4478             mPermissionManager.setDefaultPermissionGrantFingerprint(Build.FINGERPRINT, userId);
4479             mDomainVerificationManager.clearUser(userId);
4480         }
4481     }
4482 
4483     private boolean readPermissionStateForUser(@UserIdInt int userId) {
4484         synchronized (mLock) {
4485             mPermissionManager.writeLegacyPermissionStateTEMP();
4486             mSettings.readPermissionStateForUserSyncLPr(userId);
4487             mPermissionManager.readLegacyPermissionStateTEMP();
4488             final boolean isPermissionUpgradeNeeded = !Objects.equals(
4489                     mPermissionManager.getDefaultPermissionGrantFingerprint(userId),
4490                     Build.FINGERPRINT);
4491             return isPermissionUpgradeNeeded;
4492         }
4493     }
4494 
4495     public boolean isStorageLow() {
4496         // allow instant applications
4497         final long token = Binder.clearCallingIdentity();
4498         try {
4499             final DeviceStorageMonitorInternal
4500                     dsm = mInjector.getLocalService(DeviceStorageMonitorInternal.class);
4501             if (dsm != null) {
4502                 return dsm.isMemoryLow();
4503             } else {
4504                 return false;
4505             }
4506         } finally {
4507             Binder.restoreCallingIdentity(token);
4508         }
4509     }
4510 
4511     private void deletePackageIfUnused(@NonNull Computer snapshot, final String packageName) {
4512         PackageStateInternal ps = snapshot.getPackageStateInternal(packageName);
4513         if (ps == null) {
4514             return;
4515         }
4516         final SparseArray<? extends PackageUserStateInternal> userStates = ps.getUserStates();
4517         for (int index = 0; index < userStates.size(); index++) {
4518             if (userStates.valueAt(index).isInstalled()) {
4519                 return;
4520             }
4521         }
4522         // TODO Implement atomic delete if package is unused
4523         // It is currently possible that the package will be deleted even if it is installed
4524         // after this method returns.
4525         mHandler.post(() -> mDeletePackageHelper.deletePackageX(
4526                 packageName, PackageManager.VERSION_CODE_HIGHEST,
4527                 0, PackageManager.DELETE_ALL_USERS, true /*removedBySystem*/));
4528     }
4529 
4530     void deletePreloadsFileCache() {
4531         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CLEAR_APP_CACHE,
4532                 "deletePreloadsFileCache");
4533         File dir = Environment.getDataPreloadsFileCacheDirectory();
4534         Slog.i(PackageManagerService.TAG, "Deleting preloaded file cache " + dir);
4535         FileUtils.deleteContents(dir);
4536     }
4537 
4538     void setSystemAppHiddenUntilInstalled(@NonNull Computer snapshot, String packageName,
4539             boolean hidden) {
4540         final int callingUid = Binder.getCallingUid();
4541         final boolean calledFromSystemOrPhone = isSystemOrPhone(callingUid);
4542         if (!calledFromSystemOrPhone) {
4543             mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS,
4544                     "setSystemAppHiddenUntilInstalled");
4545         }
4546 
4547         final PackageStateInternal stateRead = snapshot.getPackageStateInternal(packageName);
4548         if (stateRead == null || !stateRead.isSystem() || stateRead.getPkg() == null) {
4549             return;
4550         }
4551         if (stateRead.getPkg().isCoreApp() && !calledFromSystemOrPhone) {
4552             throw new SecurityException("Only system or phone callers can modify core apps");
4553         }
4554 
4555         commitPackageStateMutation(null, mutator -> {
4556             mutator.forPackage(packageName)
4557                     .setHiddenUntilInstalled(hidden);
4558             mutator.forDisabledSystemPackage(packageName)
4559                     .setHiddenUntilInstalled(hidden);
4560         });
4561     }
4562 
4563     boolean setSystemAppInstallState(@NonNull Computer snapshot, String packageName,
4564             boolean installed, int userId) {
4565         final int callingUid = Binder.getCallingUid();
4566         final boolean calledFromSystemOrPhone = isSystemOrPhone(callingUid);
4567         if (!calledFromSystemOrPhone) {
4568             mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS,
4569                     "setSystemAppHiddenUntilInstalled");
4570         }
4571 
4572         final PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName);
4573         // The target app should always be in system
4574         if (packageState == null || !packageState.isSystem() || packageState.getPkg() == null) {
4575             return false;
4576         }
4577         if (packageState.getPkg().isCoreApp() && !calledFromSystemOrPhone) {
4578             throw new SecurityException("Only system or phone callers can modify core apps");
4579         }
4580         // Check if the install state is the same
4581         if (packageState.getUserStateOrDefault(userId).isInstalled() == installed) {
4582             return false;
4583         }
4584 
4585         final long callingId = Binder.clearCallingIdentity();
4586         try {
4587             if (installed) {
4588                 // install the app from uninstalled state
4589                 mInstallPackageHelper.installExistingPackageAsUser(
4590                         packageName,
4591                         userId,
4592                         PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
4593                         PackageManager.INSTALL_REASON_DEVICE_SETUP,
4594                         null,
4595                         null);
4596                 return true;
4597             }
4598 
4599             // uninstall the app from installed state
4600             deletePackageVersioned(
4601                     new VersionedPackage(packageName, PackageManager.VERSION_CODE_HIGHEST),
4602                     new PackageManager.LegacyPackageDeleteObserver(null).getBinder(),
4603                     userId,
4604                     PackageManager.DELETE_SYSTEM_APP);
4605             return true;
4606         } finally {
4607             Binder.restoreCallingIdentity(callingId);
4608         }
4609     }
4610 
4611     void finishPackageInstall(int token, boolean didLaunch) {
4612         PackageManagerServiceUtils.enforceSystemOrRoot(
4613                 "Only the system is allowed to finish installs");
4614 
4615         if (PackageManagerService.DEBUG_INSTALL) {
4616             Slog.v(PackageManagerService.TAG, "BM finishing package install for " + token);
4617         }
4618         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
4619 
4620         final Message msg = mHandler.obtainMessage(PackageManagerService.POST_INSTALL, token,
4621                 didLaunch ? 1 : 0);
4622         mHandler.sendMessage(msg);
4623     }
4624 
4625     void checkPackageStartable(@NonNull Computer snapshot, @NonNull String packageName,
4626             @UserIdInt int userId) {
4627         final int callingUid = Binder.getCallingUid();
4628         if (snapshot.getInstantAppPackageName(callingUid) != null) {
4629             throw new SecurityException("Instant applications don't have access to this method");
4630         }
4631         if (!mUserManager.exists(userId)) {
4632             throw new SecurityException("User doesn't exist");
4633         }
4634         snapshot.enforceCrossUserPermission(callingUid, userId, false, false,
4635                 "checkPackageStartable");
4636         switch (snapshot.getPackageStartability(mSafeMode, packageName, callingUid, userId)) {
4637             case PACKAGE_STARTABILITY_NOT_FOUND:
4638                 throw new SecurityException("Package " + packageName + " was not found!");
4639             case PACKAGE_STARTABILITY_NOT_SYSTEM:
4640                 throw new SecurityException("Package " + packageName + " not a system app!");
4641             case PACKAGE_STARTABILITY_FROZEN:
4642                 throw new SecurityException("Package " + packageName + " is currently frozen!");
4643             case PACKAGE_STARTABILITY_DIRECT_BOOT_UNSUPPORTED:
4644                 throw new SecurityException("Package " + packageName + " is not encryption aware!");
4645             case PACKAGE_STARTABILITY_OK:
4646             default:
4647         }
4648     }
4649 
4650     void setPackageStoppedState(@NonNull Computer snapshot, @NonNull String packageName,
4651             boolean stopped, @UserIdInt int userId) {
4652         if (!mUserManager.exists(userId)) return;
4653         final int callingUid = Binder.getCallingUid();
4654         boolean wasStopped = false;
4655         if (snapshot.getInstantAppPackageName(callingUid) == null) {
4656             final int permission = mContext.checkCallingOrSelfPermission(
4657                     Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
4658             final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
4659             if (!allowedByPermission
4660                     && !ArrayUtils.contains(snapshot.getPackagesForUid(callingUid), packageName)) {
4661                 throw new SecurityException(
4662                         "Permission Denial: attempt to change stopped state from pid="
4663                                 + Binder.getCallingPid()
4664                                 + ", uid=" + callingUid + ", package=" + packageName);
4665             }
4666             snapshot.enforceCrossUserPermission(callingUid, userId,
4667                     true /* requireFullPermission */, true /* checkShell */, "stop package");
4668 
4669             final PackageStateInternal packageState =
4670                     snapshot.getPackageStateForInstalledAndFiltered(
4671                             packageName, callingUid, userId);
4672             final PackageUserState packageUserState = packageState == null
4673                     ? null : packageState.getUserStateOrDefault(userId);
4674             if (packageState != null && packageUserState.isStopped() != stopped) {
4675                 boolean wasNotLaunched = packageUserState.isNotLaunched();
4676                 wasStopped = packageUserState.isStopped();
4677                 commitPackageStateMutation(null, packageName, state -> {
4678                     PackageUserStateWrite userState = state.userState(userId);
4679                     userState.setStopped(stopped);
4680                     if (wasNotLaunched) {
4681                         userState.setNotLaunched(false);
4682                     }
4683                 });
4684 
4685                 if (wasNotLaunched) {
4686                     final String installerPackageName =
4687                             packageState.getInstallSource().mInstallerPackageName;
4688                     if (installerPackageName != null) {
4689                         notifyFirstLaunch(packageName, installerPackageName, userId);
4690                     }
4691                 }
4692 
4693                 scheduleWritePackageRestrictions(userId);
4694             }
4695         }
4696 
4697         // If this would cause the app to leave force-stop, then also make sure to unhibernate the
4698         // app if needed.
4699         if (!stopped) {
4700             mHandler.post(() -> {
4701                 AppHibernationManagerInternal ah =
4702                         mInjector.getLocalService(AppHibernationManagerInternal.class);
4703                 if (ah != null && ah.isHibernatingForUser(packageName, userId)) {
4704                     ah.setHibernatingForUser(packageName, userId, false);
4705                     ah.setHibernatingGlobally(packageName, false);
4706                 }
4707             });
4708             // Send UNSTOPPED broadcast if necessary
4709             if (wasStopped && Flags.stayStopped()) {
4710                 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "unstoppedBroadcast");
4711                 final PackageManagerInternal pmi =
4712                         mInjector.getLocalService(PackageManagerInternal.class);
4713                 final int [] userIds = resolveUserIds(userId);
4714                 final SparseArray<int[]> broadcastAllowList =
4715                         snapshotComputer().getVisibilityAllowLists(packageName, userIds);
4716                 final Bundle extras = new Bundle();
4717                 extras.putInt(Intent.EXTRA_UID, pmi.getPackageUid(packageName, 0, userId));
4718                 extras.putInt(Intent.EXTRA_USER_HANDLE, userId);
4719                 extras.putLong(Intent.EXTRA_TIME, SystemClock.elapsedRealtime());
4720                 mHandler.post(() -> {
4721                     mBroadcastHelper.sendPackageBroadcast(Intent.ACTION_PACKAGE_UNSTOPPED,
4722                             packageName, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY,
4723                             null /* targetPkg */, null /* finishedReceiver */, userIds,
4724                             null /* instantUserIds */, broadcastAllowList,
4725                             null /* filterExtrasForReceiver */, null /* bOptions */,
4726                             null /* requiredPermissions */);
4727                 });
4728                 mPackageMonitorCallbackHelper.notifyPackageMonitor(Intent.ACTION_PACKAGE_UNSTOPPED,
4729                         packageName, extras, userIds, null /* instantUserIds */,
4730                         broadcastAllowList, mHandler, null /* filterExtras */);
4731                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
4732             }
4733         }
4734     }
4735 
4736     void notifyComponentUsed(@NonNull Computer snapshot, @NonNull String packageName,
4737             @UserIdInt int userId, @Nullable String recentCallingPackage,
4738             @NonNull String debugInfo) {
4739         synchronized (mLock) {
4740             final PackageSetting pkgSetting = mSettings.getPackageLPr(packageName);
4741             // If the package doesn't exist, don't need to proceed to setPackageStoppedState.
4742             if (pkgSetting == null) {
4743                 return;
4744             }
4745             if (pkgSetting.getUserStateOrDefault(userId).isQuarantined()) {
4746                 Slog.i(TAG,
4747                         "Component is quarantined+suspended but being used: "
4748                                 + packageName + " by " + recentCallingPackage + ", debugInfo: "
4749                                 + debugInfo);
4750             }
4751         }
4752         PackageManagerService.this
4753                 .setPackageStoppedState(snapshot, packageName, false /* stopped */,
4754                         userId);
4755     }
4756 
4757     public class IPackageManagerImpl extends IPackageManagerBase {
4758 
4759         public IPackageManagerImpl() {
4760             super(PackageManagerService.this, mContext, mDexOptHelper, mModuleInfoProvider,
4761                     mPreferredActivityHelper, mResolveIntentHelper, mDomainVerificationManager,
4762                     mDomainVerificationConnection, mInstallerService, mPackageProperty,
4763                     mResolveComponentName, mInstantAppResolverSettingsComponent,
4764                     mServicesExtensionPackageName, mSharedSystemSharedLibraryPackageName);
4765         }
4766 
4767         @Override
4768         public void checkPackageStartable(String packageName, int userId) {
4769             PackageManagerService.this
4770                     .checkPackageStartable(snapshotComputer(), packageName, userId);
4771         }
4772 
4773         @Override
4774         public void clearApplicationProfileData(String packageName) {
4775             PackageManagerServiceUtils.enforceSystemOrRootOrShell(
4776                     "Only the system or shell can clear all profile data");
4777 
4778             final Computer snapshot = snapshotComputer();
4779             final AndroidPackage pkg = snapshot.getPackage(packageName);
4780             try (PackageFreezer ignored =
4781                             freezePackage(packageName, USER_ALL,
4782                                     "clearApplicationProfileData",
4783                                     ApplicationExitInfo.REASON_OTHER, null /* request */)) {
4784                 try (PackageManagerTracedLock installLock = mInstallLock.acquireLock()) {
4785                     mAppDataHelper.clearAppProfilesLIF(pkg);
4786                 }
4787             }
4788         }
4789 
4790         @android.annotation.EnforcePermission(android.Manifest.permission.CLEAR_APP_USER_DATA)
4791         @Override
4792         public void clearApplicationUserData(final String packageName,
4793                 final IPackageDataObserver observer, final int userId) {
4794             clearApplicationUserData_enforcePermission();
4795 
4796             final int callingUid = Binder.getCallingUid();
4797             final Computer snapshot = snapshotComputer();
4798             snapshot.enforceCrossUserPermission(callingUid, userId, true /* requireFullPermission */,
4799                     false /* checkShell */, "clear application data");
4800 
4801             if (snapshot.getPackageStateForInstalledAndFiltered(
4802                     packageName, callingUid, userId) == null) {
4803                 if (observer != null) {
4804                     mHandler.post(() -> {
4805                         try {
4806                             observer.onRemoveCompleted(packageName, false);
4807                         } catch (RemoteException e) {
4808                             Log.i(TAG, "Observer no longer exists.");
4809                         }
4810                     });
4811                 }
4812                 return;
4813             }
4814             if (mProtectedPackages.isPackageDataProtected(userId, packageName)) {
4815                 throw new SecurityException("Cannot clear data for a protected package: "
4816                         + packageName);
4817             }
4818             final int callingPid = Binder.getCallingPid();
4819             EventLog.writeEvent(EventLogTags.PM_CLEAR_APP_DATA_CALLER, callingPid, callingUid,
4820                     packageName);
4821 
4822             // Queue up an async operation since the package deletion may take a little while.
4823             mHandler.post(new Runnable() {
4824                 public void run() {
4825                     mHandler.removeCallbacks(this);
4826                     final boolean succeeded;
4827                     try (PackageFreezer freezer = freezePackage(packageName, USER_ALL,
4828                             "clearApplicationUserData",
4829                             ApplicationExitInfo.REASON_USER_REQUESTED, null /* request */,
4830                             /* waitAppKilled= */ true)) {
4831                         try (PackageManagerTracedLock installLock = mInstallLock.acquireLock()) {
4832                             succeeded = clearApplicationUserDataLIF(snapshotComputer(), packageName,
4833                                     userId);
4834                         }
4835                         mInstantAppRegistry.deleteInstantApplicationMetadata(packageName, userId);
4836                         synchronized (mLock) {
4837                             if (succeeded) {
4838                                 resetComponentEnabledSettingsIfNeededLPw(packageName, userId,
4839                                         callingUid);
4840                             }
4841                         }
4842                     }
4843                     if (succeeded) {
4844                         // invoke DeviceStorageMonitor's update method to clear any notifications
4845                         DeviceStorageMonitorInternal dsm = LocalServices
4846                                 .getService(DeviceStorageMonitorInternal.class);
4847                         if (dsm != null) {
4848                             dsm.checkMemory();
4849                         }
4850                         if (checkPermission(Manifest.permission.SUSPEND_APPS, packageName, userId)
4851                                 == PERMISSION_GRANTED) {
4852                             final Computer snapshot = snapshotComputer();
4853                             unsuspendForSuspendingPackage(
4854                                     snapshot, packageName, userId, USER_ALL);
4855                             removeAllDistractingPackageRestrictions(snapshot, userId);
4856                             synchronized (mLock) {
4857                                 flushPackageRestrictionsAsUserInternalLocked(userId);
4858                             }
4859                         }
4860                     }
4861                     if (observer != null) {
4862                         try {
4863                             observer.onRemoveCompleted(packageName, succeeded);
4864                         } catch (RemoteException e) {
4865                             Log.i(TAG, "Observer no longer exists.");
4866                         }
4867                     } //end if observer
4868                 } //end run
4869             });
4870         }
4871 
4872         @android.annotation.EnforcePermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
4873         @Override
4874         public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
4875             clearCrossProfileIntentFilters_enforcePermission();
4876             final int callingUid = Binder.getCallingUid();
4877             final Computer snapshot = snapshotComputer();
4878             enforceOwnerRights(snapshot, ownerPackage, callingUid);
4879             PackageManagerServiceUtils.enforceShellRestriction(mInjector.getUserManagerInternal(),
4880                     UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
4881             PackageManagerService.this.mInjector.getCrossProfileIntentFilterHelper()
4882                             .clearCrossProfileIntentFilters(sourceUserId, ownerPackage,
4883                                     null);
4884             scheduleWritePackageRestrictions(sourceUserId);
4885         }
4886 
4887         @android.annotation.EnforcePermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
4888         @Override
4889         public boolean removeCrossProfileIntentFilter(IntentFilter intentFilter,
4890                 String ownerPackage,
4891                 int sourceUserId,
4892                 int targetUserId, int flags) {
4893             removeCrossProfileIntentFilter_enforcePermission();
4894             final int callingUid = Binder.getCallingUid();
4895             enforceOwnerRights(snapshotComputer(), ownerPackage, callingUid);
4896             mUserManager.enforceCrossProfileIntentFilterAccess(sourceUserId, targetUserId,
4897                     callingUid, /* addCrossProfileIntentFilter */ false);
4898             PackageManagerServiceUtils.enforceShellRestriction(mInjector.getUserManagerInternal(),
4899                     UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
4900 
4901             boolean removedMatchingFilter = false;
4902             synchronized (mLock) {
4903                 CrossProfileIntentResolver resolver =
4904                         mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
4905 
4906                 ArraySet<CrossProfileIntentFilter> set =
4907                         new ArraySet<>(resolver.filterSet());
4908                 for (int i = 0; i < set.size(); i++) {
4909                     final CrossProfileIntentFilter filter = set.valueAt(i);
4910                     if (IntentFilter.filterEquals(filter.mFilter, intentFilter)
4911                             && filter.getOwnerPackage().equals(ownerPackage)
4912                             && filter.getTargetUserId() == targetUserId
4913                             && filter.getFlags() == flags) {
4914                         resolver.removeFilter(filter);
4915                         removedMatchingFilter = true;
4916                         break;
4917                     }
4918                 }
4919             }
4920             if (removedMatchingFilter) {
4921                 scheduleWritePackageRestrictions(sourceUserId);
4922             }
4923             return removedMatchingFilter;
4924         }
4925 
4926         @Override
4927         public final void deleteApplicationCacheFiles(final String packageName,
4928                 final IPackageDataObserver observer) {
4929             final int userId = UserHandle.getCallingUserId();
4930             deleteApplicationCacheFilesAsUser(packageName, userId, observer);
4931         }
4932 
4933         @Override
4934         public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
4935                 final IPackageDataObserver observer) {
4936             final int callingUid = Binder.getCallingUid();
4937             if (mContext.checkCallingOrSelfPermission(
4938                     android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
4939                     != PackageManager.PERMISSION_GRANTED) {
4940                 // If the caller has the old delete cache permission, silently ignore.  Else throw.
4941                 if (mContext.checkCallingOrSelfPermission(
4942                         android.Manifest.permission.DELETE_CACHE_FILES)
4943                         == PackageManager.PERMISSION_GRANTED) {
4944                     Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
4945                             android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
4946                             ", silently ignoring");
4947                     return;
4948                 }
4949                 mContext.enforceCallingOrSelfPermission(
4950                         android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
4951             }
4952             final Computer snapshot = snapshotComputer();
4953             snapshot.enforceCrossUserPermission(callingUid, userId, /* requireFullPermission= */ true,
4954                     /* checkShell= */ false, "delete application cache files");
4955             final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
4956                     android.Manifest.permission.ACCESS_INSTANT_APPS);
4957             final int callingPid = Binder.getCallingPid();
4958             EventLog.writeEvent(EventLogTags.PM_CLEAR_APP_DATA_CALLER, callingPid, callingUid,
4959                     packageName);
4960 
4961             // Queue up an async operation since the package deletion may take a little while.
4962             mHandler.post(() -> {
4963                 // Snapshot in the Handler Runnable since this may be deferred quite a bit
4964                 // TODO: Is this and the later mInstallLock re-snapshot necessary?
4965                 final Computer newSnapshot = snapshotComputer();
4966                 final PackageStateInternal ps = newSnapshot.getPackageStateInternal(packageName);
4967                 boolean doClearData = true;
4968                 if (ps != null) {
4969                     final boolean targetIsInstantApp =
4970                             ps.getUserStateOrDefault(UserHandle.getUserId(callingUid)).isInstantApp();
4971                     doClearData = !targetIsInstantApp
4972                             || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
4973                 }
4974                 if (doClearData) {
4975                     try (PackageManagerTracedLock installLock = mInstallLock.acquireLock()) {
4976                         final int flags = FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL;
4977                         // Snapshot again after mInstallLock?
4978                         final AndroidPackage pkg = snapshotComputer().getPackage(packageName);
4979                         // We're only clearing cache files, so we don't care if the
4980                         // app is unfrozen and still able to run
4981                         mAppDataHelper.clearAppDataLIF(pkg, userId,
4982                                 flags | Installer.FLAG_CLEAR_CACHE_ONLY);
4983                         mAppDataHelper.clearAppDataLIF(pkg, userId,
4984                                 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
4985                     }
4986                 }
4987                 if (observer != null) {
4988                     try {
4989                         observer.onRemoveCompleted(packageName, true);
4990                     } catch (RemoteException e) {
4991                         Log.i(TAG, "Observer no longer exists.");
4992                     }
4993                 }
4994             });
4995         }
4996 
4997         @Override
4998         public void enterSafeMode() {
4999             PackageManagerServiceUtils.enforceSystemOrRoot(
5000                     "Only the system can request entering safe mode");
5001 
5002             if (!mSystemReady) {
5003                 mSafeMode = true;
5004             }
5005         }
5006 
5007         @Override
5008         public void extendVerificationTimeout(int verificationId, int verificationCodeAtTimeout,
5009                 long millisecondsToDelay) {
5010             // Negative ids correspond to testing verifiers and will be silently enforced in
5011             // the handler thread.
5012             if (verificationId >= 0) {
5013                 mContext.enforceCallingOrSelfPermission(
5014                         Manifest.permission.PACKAGE_VERIFICATION_AGENT,
5015                         "Only package verification agents can extend verification timeouts");
5016             }
5017             final int callingUid = Binder.getCallingUid();
5018 
5019             mHandler.post(() -> {
5020                 final int id = verificationId >= 0 ? verificationId : -verificationId;
5021                 final PackageVerificationState state = mPendingVerification.get(id);
5022                 if (state == null || !state.extendTimeout(callingUid)) {
5023                     // Invalid uid or already extended.
5024                     return;
5025                 }
5026 
5027                 final PackageVerificationResponse response = new PackageVerificationResponse(
5028                         verificationCodeAtTimeout, callingUid);
5029 
5030                 long delay = millisecondsToDelay;
5031                 if (delay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
5032                     delay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
5033                 }
5034                 if (delay < 0) {
5035                     delay = 0;
5036                 }
5037 
5038                 final Message msg = mHandler.obtainMessage(PackageManagerService.PACKAGE_VERIFIED);
5039                 msg.arg1 = id;
5040                 msg.obj = response;
5041                 mHandler.sendMessageDelayed(msg, delay);
5042             });
5043         }
5044 
5045         @WorkerThread
5046         @Override
5047         public void flushPackageRestrictionsAsUser(int userId) {
5048             final Computer snapshot = snapshotComputer();
5049             final int callingUid = Binder.getCallingUid();
5050             if (snapshot.getInstantAppPackageName(callingUid) != null) {
5051                 return;
5052             }
5053             if (!mUserManager.exists(userId)) {
5054                 return;
5055             }
5056             snapshot.enforceCrossUserPermission(callingUid, userId,
5057                     false /* requireFullPermission*/, false /* checkShell */,
5058                     "flushPackageRestrictions");
5059             synchronized (mLock) {
5060                 flushPackageRestrictionsAsUserInternalLocked(userId);
5061             }
5062         }
5063 
5064 
5065         @android.annotation.EnforcePermission(android.Manifest.permission.CLEAR_APP_CACHE)
5066         @Override
5067         public void freeStorage(final String volumeUuid, final long freeStorageSize,
5068                 final @StorageManager.AllocateFlags int flags, final IntentSender pi) {
5069             freeStorage_enforcePermission();
5070             mHandler.post(() -> {
5071                 boolean success = false;
5072                 try {
5073                     PackageManagerService.this.freeStorage(volumeUuid, freeStorageSize, flags);
5074                     success = true;
5075                 } catch (IOException e) {
5076                     Slog.w(TAG, e);
5077                 }
5078                 if (pi != null) {
5079                     try {
5080                         final BroadcastOptions options = BroadcastOptions.makeBasic();
5081                         options.setPendingIntentBackgroundActivityLaunchAllowed(false);
5082                         pi.sendIntent(null, success ? 1 : 0, null /* intent */,
5083                                 null /* requiredPermission */, options.toBundle(),
5084                                 null /* executor */, null /* onFinished*/);
5085                     } catch (SendIntentException e) {
5086                         Slog.w(TAG, e);
5087                     }
5088                 }
5089             });
5090         }
5091 
5092         @android.annotation.EnforcePermission(android.Manifest.permission.CLEAR_APP_CACHE)
5093         @Override
5094         public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
5095                 final @StorageManager.AllocateFlags int flags, final IPackageDataObserver observer) {
5096             freeStorageAndNotify_enforcePermission();
5097             mHandler.post(() -> {
5098                 boolean success = false;
5099                 try {
5100                     PackageManagerService.this.freeStorage(volumeUuid, freeStorageSize, flags);
5101                     success = true;
5102                 } catch (IOException e) {
5103                     Slog.w(PackageManagerService.TAG, e);
5104                 }
5105                 if (observer != null) {
5106                     try {
5107                         observer.onRemoveCompleted(null, success);
5108                     } catch (RemoteException e) {
5109                         Slog.w(PackageManagerService.TAG, e);
5110                     }
5111                 }
5112             });
5113         }
5114 
5115         @Override
5116         public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5117             final int callingUid = Binder.getCallingUid();
5118             final Computer snapshot = snapshotComputer();
5119             if (snapshot.getInstantAppPackageName(callingUid) != null) {
5120                 return null;
5121             }
5122             if (!mUserManager.exists(userId)) {
5123                 return null;
5124             }
5125             snapshot.enforceCrossUserPermission(callingUid, userId, false, false,
5126                     "getChangedPackages");
5127             final ChangedPackages changedPackages = mChangedPackagesTracker.getChangedPackages(
5128                     sequenceNumber, userId);
5129 
5130             if (changedPackages != null) {
5131                 final List<String> packageNames = changedPackages.getPackageNames();
5132                 for (int index = packageNames.size() - 1; index >= 0; index--) {
5133                     // Filter out the changes if the calling package should not be able to see it.
5134                     final PackageStateInternal packageState =
5135                             snapshot.getPackageStateInternal(packageNames.get(index));
5136                     if (snapshot.shouldFilterApplication(packageState, callingUid, userId)) {
5137                         packageNames.remove(index);
5138                     }
5139                 }
5140             }
5141 
5142             return changedPackages;
5143         }
5144 
5145         @Override
5146         public byte[] getDomainVerificationBackup(int userId) {
5147             if (Binder.getCallingUid() != Process.SYSTEM_UID) {
5148                 throw new SecurityException("Only the system may call getDomainVerificationBackup()");
5149             }
5150 
5151             try {
5152                 try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
5153                     TypedXmlSerializer serializer = Xml.resolveSerializer(output);
5154                     mDomainVerificationManager.writeSettings(snapshotComputer(), serializer, true,
5155                             userId);
5156                     return output.toByteArray();
5157                 }
5158             } catch (Exception e) {
5159                 if (PackageManagerService.DEBUG_BACKUP) {
5160                     Slog.e(PackageManagerService.TAG, "Unable to write domain verification for backup", e);
5161                 }
5162                 return null;
5163             }
5164         }
5165 
5166         @Override
5167         public IBinder getHoldLockToken() {
5168             if (!Build.IS_DEBUGGABLE) {
5169                 throw new SecurityException("getHoldLockToken requires a debuggable build");
5170             }
5171 
5172             mContext.enforceCallingPermission(
5173                     Manifest.permission.INJECT_EVENTS,
5174                     "getHoldLockToken requires INJECT_EVENTS permission");
5175 
5176             final Binder token = new Binder();
5177             token.attachInterface(this, "holdLock:" + Binder.getCallingUid());
5178             return token;
5179         }
5180 
5181         @android.annotation.EnforcePermission(android.Manifest.permission.ACCESS_INSTANT_APPS)
5182         @Override
5183         public String getInstantAppAndroidId(String packageName, int userId) {
5184             getInstantAppAndroidId_enforcePermission();
5185             final Computer snapshot = snapshotComputer();
5186             snapshot.enforceCrossUserPermission(Binder.getCallingUid(), userId,
5187                     true /* requireFullPermission */, false /* checkShell */,
5188                     "getInstantAppAndroidId");
5189             // Make sure the target is an Instant App.
5190             if (!snapshot.isInstantApp(packageName, userId)) {
5191                 return null;
5192             }
5193             return mInstantAppRegistry.getInstantAppAndroidId(packageName, userId);
5194         }
5195 
5196         @Override
5197         public byte[] getInstantAppCookie(String packageName, int userId) {
5198             if (HIDE_EPHEMERAL_APIS) {
5199                 return null;
5200             }
5201 
5202             final Computer snapshot = snapshotComputer();
5203             snapshot.enforceCrossUserPermission(Binder.getCallingUid(), userId,
5204                     true /* requireFullPermission */, false /* checkShell */,
5205                     "getInstantAppCookie");
5206             if (!snapshot.isCallerSameApp(packageName, Binder.getCallingUid())) {
5207                 return null;
5208             }
5209             PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName);
5210             if (packageState == null || packageState.getPkg() == null) {
5211                 return null;
5212             }
5213             return mInstantAppRegistry.getInstantAppCookie(packageState.getPkg(), userId);
5214         }
5215 
5216         @Override
5217         public Bitmap getInstantAppIcon(String packageName, int userId) {
5218             if (HIDE_EPHEMERAL_APIS) {
5219                 return null;
5220             }
5221 
5222             final Computer snapshot = snapshotComputer();
5223             if (!snapshot.canViewInstantApps(Binder.getCallingUid(), userId)) {
5224                 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
5225                         "getInstantAppIcon");
5226             }
5227             snapshot.enforceCrossUserPermission(Binder.getCallingUid(), userId,
5228                     true /* requireFullPermission */, false /* checkShell */,
5229                     "getInstantAppIcon");
5230 
5231             return mInstantAppRegistry.getInstantAppIcon(packageName, userId);
5232         }
5233 
5234         @Override
5235         public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
5236             if (HIDE_EPHEMERAL_APIS) {
5237                 return null;
5238             }
5239 
5240             final Computer snapshot = snapshotComputer();
5241             if (!snapshot.canViewInstantApps(Binder.getCallingUid(), userId)) {
5242                 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
5243                         "getEphemeralApplications");
5244             }
5245             snapshot.enforceCrossUserPermission(Binder.getCallingUid(), userId,
5246                     true /* requireFullPermission */, false /* checkShell */,
5247                     "getEphemeralApplications");
5248 
5249             List<InstantAppInfo> instantApps = mInstantAppRegistry.getInstantApps(snapshot, userId);
5250             if (instantApps != null) {
5251                 return new ParceledListSlice<>(instantApps);
5252             }
5253             return null;
5254         }
5255 
5256         @Override
5257         public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
5258             return mPreferredActivityHelper.getLastChosenActivity(snapshotComputer(), intent,
5259                     resolvedType, flags);
5260         }
5261 
5262         @Override
5263         public IntentSender getLaunchIntentSenderForPackage(String packageName, String callingPackage,
5264                 String featureId, int userId) throws RemoteException {
5265             return mResolveIntentHelper.getLaunchIntentSenderForPackage(snapshotComputer(),
5266                     packageName, callingPackage, featureId, userId);
5267         }
5268 
5269         @Override
5270         public List<String> getMimeGroup(String packageName, String mimeGroup) {
5271             final Computer snapshot = snapshotComputer();
5272             enforceOwnerRights(snapshot, packageName, Binder.getCallingUid());
5273             return getMimeGroupInternal(snapshot, packageName, mimeGroup);
5274         }
5275 
5276         @android.annotation.EnforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS)
5277         @Override
5278         public int getMoveStatus(int moveId) {
5279             getMoveStatus_enforcePermission();
5280             return mMoveCallbacks.mLastStatus.get(moveId);
5281         }
5282 
5283         @android.annotation.EnforcePermission(android.Manifest.permission.GET_APP_METADATA)
5284         @Override
5285         public ParcelFileDescriptor getAppMetadataFd(String packageName, int userId) {
5286             getAppMetadataFd_enforcePermission();
5287             final int callingUid = Binder.getCallingUid();
5288             final Computer snapshot = snapshotComputer();
5289             final PackageStateInternal ps = snapshot.getPackageStateForInstalledAndFiltered(
5290                     packageName, callingUid, userId);
5291             if (ps == null) {
5292                 throw new ParcelableException(
5293                         new PackageManager.NameNotFoundException(packageName));
5294             }
5295             String filePath = ps.getAppMetadataFilePath();
5296             if (filePath == null) {
5297                 return null;
5298             }
5299             File file = new File(filePath);
5300             try {
5301                 return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
5302             } catch (FileNotFoundException e) {
5303                 return null;
5304             }
5305         }
5306 
5307         @android.annotation.EnforcePermission(android.Manifest.permission.GET_APP_METADATA)
5308         @Override
5309         public int getAppMetadataSource(String packageName, int userId) {
5310             getAppMetadataSource_enforcePermission();
5311             final int callingUid = Binder.getCallingUid();
5312             final Computer snapshot = snapshotComputer();
5313             final PackageStateInternal ps = snapshot.getPackageStateForInstalledAndFiltered(
5314                     packageName, callingUid, userId);
5315             if (ps == null) {
5316                 throw new ParcelableException(
5317                         new PackageManager.NameNotFoundException(packageName));
5318             }
5319             return ps.getAppMetadataSource();
5320         }
5321 
5322         @Override
5323         public String getPermissionControllerPackageName() {
5324             final int callingUid = Binder.getCallingUid();
5325             final int callingUserId = UserHandle.getUserId(callingUid);
5326             final Computer snapshot = snapshotComputer();
5327             if (snapshot.getPackageStateForInstalledAndFiltered(
5328                     mRequiredPermissionControllerPackage, callingUid, callingUserId) != null) {
5329                 return mRequiredPermissionControllerPackage;
5330             }
5331 
5332             throw new IllegalStateException("PermissionController is not found");
5333         }
5334 
5335         @Override
5336         @SuppressWarnings("GuardedBy")
5337         public int getRuntimePermissionsVersion(@UserIdInt int userId) {
5338             Preconditions.checkArgumentNonnegative(userId);
5339             enforceAdjustRuntimePermissionsPolicyOrUpgradeRuntimePermissions(
5340                     "getRuntimePermissionVersion");
5341             return mSettings.getDefaultRuntimePermissionsVersion(userId);
5342         }
5343 
5344         @Override
5345         public String getSplashScreenTheme(@NonNull String packageName, int userId) {
5346             final Computer snapshot = snapshotComputer();
5347             final int callingUid = Binder.getCallingUid();
5348             snapshot.enforceCrossUserPermission(
5349                     callingUid, userId, false /* requireFullPermission */,
5350                     false /* checkShell */, "getSplashScreenTheme");
5351             PackageStateInternal packageState = snapshot.getPackageStateForInstalledAndFiltered(
5352                     packageName, callingUid, userId);
5353             return packageState == null ? null
5354                     : packageState.getUserStateOrDefault(userId).getSplashScreenTheme();
5355         }
5356 
5357         @Override
5358         @PackageManager.UserMinAspectRatio
5359         public int getUserMinAspectRatio(@NonNull String packageName, int userId) {
5360             final Computer snapshot = snapshotComputer();
5361             final int callingUid = Binder.getCallingUid();
5362             final PackageStateInternal packageState = snapshot
5363                     .getPackageStateForInstalledAndFiltered(packageName, callingUid, userId);
5364             return packageState == null ? USER_MIN_ASPECT_RATIO_UNSET
5365                     : packageState.getUserStateOrDefault(userId).getMinAspectRatio();
5366         }
5367 
5368         @Override
5369         public Bundle getSuspendedPackageAppExtras(String packageName, int userId) {
5370             final int callingUid = Binder.getCallingUid();
5371             final Computer snapshot = snapshot();
5372             if (snapshot.getPackageUid(packageName, 0, userId) != callingUid) {
5373                 throw new SecurityException("Calling package " + packageName
5374                         + " does not belong to calling uid " + callingUid);
5375             }
5376             return SuspendPackageHelper
5377                     .getSuspendedPackageAppExtras(snapshot, packageName, userId, callingUid);
5378         }
5379 
5380         @Override
5381         public String getSuspendingPackage(String packageName, int userId) {
5382             try {
5383                 final int callingUid = Binder.getCallingUid();
5384                 final Computer snapshot = snapshot();
5385                 // This will do visibility checks as well.
5386                 if (!snapshot.isPackageSuspendedForUser(packageName, userId)) {
5387                     return null;
5388                 }
5389                 final UserPackage suspender = mSuspendPackageHelper.getSuspendingPackage(
5390                         snapshot, packageName, userId, callingUid);
5391                 return suspender != null ? suspender.packageName : null;
5392             } catch (PackageManager.NameNotFoundException e) {
5393                 return null;
5394             }
5395         }
5396 
5397         @Override
5398         public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5399             // allow instant applications
5400             ArrayList<FeatureInfo> res;
5401             res = new ArrayList<>(mAvailableFeatures.size() + 1);
5402             res.addAll(mAvailableFeatures.values());
5403             final FeatureInfo fi = new FeatureInfo();
5404             fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5405                     FeatureInfo.GL_ES_VERSION_UNDEFINED);
5406             res.add(fi);
5407 
5408             return new ParceledListSlice<>(res);
5409         }
5410 
5411         @Override
5412         public @NonNull List<String> getInitialNonStoppedSystemPackages() {
5413             return mInitialNonStoppedSystemPackages != null
5414                     ? new ArrayList<>(mInitialNonStoppedSystemPackages) : new ArrayList<>();
5415         }
5416 
5417         @Override
5418         public String[] getUnsuspendablePackagesForUser(String[] packageNames, int userId) {
5419             Objects.requireNonNull(packageNames, "packageNames cannot be null");
5420             mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS,
5421                     "getUnsuspendablePackagesForUser");
5422             final int callingUid = Binder.getCallingUid();
5423             if (UserHandle.getUserId(callingUid) != userId) {
5424                 mContext.enforceCallingOrSelfPermission(
5425                         Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5426                         "Calling uid " + callingUid
5427                                 + " cannot query getUnsuspendablePackagesForUser for user "
5428                                 + userId);
5429             }
5430             return mSuspendPackageHelper.getUnsuspendablePackagesForUser(snapshotComputer(),
5431                     packageNames, userId, callingUid);
5432         }
5433 
5434         @android.annotation.EnforcePermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)
5435         @Override
5436         public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
5437             getVerifierDeviceIdentity_enforcePermission();
5438 
5439             synchronized (mLock) {
5440                 return mSettings.getVerifierDeviceIdentityLPw(mLiveComputer);
5441             }
5442         }
5443 
5444         @Override
5445         public void makeProviderVisible(int recipientUid, @NonNull String visibleAuthority) {
5446             final Computer snapshot = snapshotComputer();
5447             final int recipientUserId = UserHandle.getUserId(recipientUid);
5448             final ProviderInfo providerInfo =
5449                     snapshot.getGrantImplicitAccessProviderInfo(recipientUid, visibleAuthority);
5450             if (providerInfo == null) {
5451                 return;
5452             }
5453             int visibleUid = providerInfo.applicationInfo.uid;
5454             PackageManagerService.this.grantImplicitAccess(snapshot, recipientUserId,
5455                     null /*Intent*/, UserHandle.getAppId(recipientUid), visibleUid,
5456                     false /*direct*/, false /* retainOnUpdate */);
5457         }
5458 
5459         @android.annotation.EnforcePermission(android.Manifest.permission.MAKE_UID_VISIBLE)
5460         @Override
5461         public void makeUidVisible(int recipientUid, int visibleUid) {
5462             makeUidVisible_enforcePermission();
5463             final int callingUid = Binder.getCallingUid();
5464             final int recipientUserId = UserHandle.getUserId(recipientUid);
5465             final int visibleUserId = UserHandle.getUserId(visibleUid);
5466             final Computer snapshot = snapshotComputer();
5467             snapshot.enforceCrossUserPermission(callingUid, recipientUserId,
5468                     false /* requireFullPermission */, false /* checkShell */, "makeUidVisible");
5469             snapshot.enforceCrossUserPermission(callingUid, visibleUserId,
5470                     false /* requireFullPermission */, false /* checkShell */, "makeUidVisible");
5471             snapshot.enforceCrossUserPermission(recipientUid, visibleUserId,
5472                     false /* requireFullPermission */, false /* checkShell */, "makeUidVisible");
5473 
5474             PackageManagerService.this.grantImplicitAccess(snapshot, recipientUserId,
5475                     null /*Intent*/, UserHandle.getAppId(recipientUid), visibleUid,
5476                     false /*direct*/, false /* retainOnUpdate */);
5477         }
5478 
5479         @Override
5480         public void holdLock(IBinder token, int durationMs) {
5481             mTestUtilityService.verifyHoldLockToken(token);
5482 
5483             synchronized (mLock) {
5484                 SystemClock.sleep(durationMs);
5485             }
5486         }
5487 
5488         /**
5489          * @hide
5490          */
5491         @Override
5492         public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
5493                 int installReason, List<String> whiteListedPermissions) {
5494             return mInstallPackageHelper.installExistingPackageAsUser(packageName, userId, installFlags,
5495                     installReason, whiteListedPermissions, null).first;
5496         }
5497 
5498         @Override
5499         public boolean isAutoRevokeWhitelisted(String packageName) {
5500             int mode = mInjector.getSystemService(AppOpsManager.class).checkOpNoThrow(
5501                     AppOpsManager.OP_AUTO_REVOKE_PERMISSIONS_IF_UNUSED,
5502                     Binder.getCallingUid(), packageName);
5503             return mode == MODE_IGNORED;
5504         }
5505 
5506         @Override
5507         public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
5508             final int callingUid = Binder.getCallingUid();
5509             final int callingAppId = UserHandle.getAppId(callingUid);
5510 
5511             final Computer snapshot = snapshotComputer();
5512             snapshot.enforceCrossUserPermission(callingUid, userId, false /*requireFullPermission*/,
5513                     true /*checkShell*/, "isPackageStateProtected");
5514 
5515             if (!PackageManagerServiceUtils.isSystemOrRoot(callingAppId)
5516                     && snapshot.checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid)
5517                     != PERMISSION_GRANTED) {
5518                 throw new SecurityException("Caller must have the "
5519                         + MANAGE_DEVICE_ADMINS + " permission.");
5520             }
5521 
5522             return mProtectedPackages.isPackageStateProtected(userId, packageName);
5523         }
5524 
5525         @Override
5526         public boolean isProtectedBroadcast(String actionName) {
5527             if (actionName != null) {
5528                 // TODO: remove these terrible hacks
5529                 if (actionName.startsWith("android.net.netmon.lingerExpired")
5530                         || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
5531                         || actionName.startsWith("com.android.internal.telephony.data-reconnect")
5532                         || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
5533                     return true;
5534                 }
5535             }
5536             // allow instant applications
5537             synchronized (mProtectedBroadcasts) {
5538                 return mProtectedBroadcasts.contains(actionName);
5539             }
5540         }
5541 
5542         /**
5543          * Logs process start information (including base APK hash) to the security log.
5544          * @hide
5545          */
5546         @Override
5547         public void logAppProcessStartIfNeeded(String packageName, String processName, int uid,
5548                 String seinfo, String apkFile, int pid) {
5549             final Computer snapshot = snapshotComputer();
5550             if (snapshot.getInstantAppPackageName(Binder.getCallingUid()) != null) {
5551                 return;
5552             }
5553             if (!SecurityLog.isLoggingEnabled()) {
5554                 return;
5555             }
5556             mProcessLoggingHandler.logAppProcessStart(mContext,
5557                     LocalServices.getService(PackageManagerInternal.class), apkFile, packageName,
5558                     processName, uid, seinfo, pid);
5559         }
5560 
5561         @android.annotation.EnforcePermission(android.Manifest.permission.MOVE_PACKAGE)
5562         @Override
5563         public int movePackage(final String packageName, final String volumeUuid) {
5564             movePackage_enforcePermission();
5565 
5566             final int callingUid = Binder.getCallingUid();
5567             final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
5568             final int moveId = mNextMoveId.getAndIncrement();
5569             mHandler.post(() -> {
5570                 try {
5571                     MovePackageHelper movePackageHelper =
5572                             new MovePackageHelper(PackageManagerService.this);
5573                     movePackageHelper.movePackageInternal(
5574                             packageName, volumeUuid, moveId, callingUid, user);
5575                 } catch (PackageManagerException e) {
5576                     Slog.w(PackageManagerService.TAG, "Failed to move " + packageName, e);
5577                     mMoveCallbacks.notifyStatusChanged(moveId, e.error);
5578                 }
5579             });
5580             return moveId;
5581         }
5582 
5583         @android.annotation.EnforcePermission(android.Manifest.permission.MOVE_PACKAGE)
5584         @Override
5585         public int movePrimaryStorage(String volumeUuid) throws RemoteException {
5586             movePrimaryStorage_enforcePermission();
5587 
5588             final int realMoveId = mNextMoveId.getAndIncrement();
5589             final Bundle extras = new Bundle();
5590             extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
5591             mMoveCallbacks.notifyCreated(realMoveId, extras);
5592 
5593             final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
5594                 @Override
5595                 public void onCreated(int moveId, Bundle extras) {
5596                     // Ignored
5597                 }
5598 
5599                 @Override
5600                 public void onStatusChanged(int moveId, int status, long estMillis) {
5601                     mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
5602                 }
5603             };
5604 
5605             final StorageManager storage = mInjector.getSystemService(StorageManager.class);
5606             storage.setPrimaryStorageUuid(volumeUuid, callback);
5607             return realMoveId;
5608         }
5609 
5610         @Override
5611         public void notifyDexLoad(String loadingPackageName,
5612                 Map<String, String> classLoaderContextMap,
5613                 String loaderIsa) {
5614             int callingUid = Binder.getCallingUid();
5615             Computer snapshot = snapshot();
5616 
5617             // System server should be able to report dex load on behalf of other apps. E.g., it
5618             // could potentially resend the notifications in order to migrate the existing dex load
5619             // info to ART Service.
5620             if (!PackageManagerServiceUtils.isSystemOrRoot()
5621                     && !snapshot.isCallerSameApp(
5622                             loadingPackageName, callingUid, true /* resolveIsolatedUid */)) {
5623                 Slog.w(PackageManagerService.TAG,
5624                         TextUtils.formatSimple(
5625                                 "Invalid dex load report. loadingPackageName=%s, uid=%d",
5626                                 loadingPackageName, callingUid));
5627                 return;
5628             }
5629 
5630             UserHandle user = Binder.getCallingUserHandle();
5631             int userId = user.getIdentifier();
5632 
5633             // Proxy the call to either ART Service or the legacy implementation. If the
5634             // implementation is switched with the system property, the dex usage info will be
5635             // incomplete, with these effects:
5636             //
5637             // -  Shared dex files may temporarily get compiled for private use.
5638             // -  Secondary dex files may not get compiled at all.
5639             // -  Stale compiled artifacts for secondary dex files may not get cleaned up.
5640             //
5641             // This recovers in the first background dexopt after the depending apps have been
5642             // loaded for the first time.
5643 
5644             DexUseManagerLocal dexUseManager = DexOptHelper.getDexUseManagerLocal();
5645             if (dexUseManager != null) {
5646                 // TODO(chiuwinson): Retrieve filtered snapshot from Computer instance instead.
5647                 try (PackageManagerLocal.FilteredSnapshot filteredSnapshot =
5648                                 LocalManagerRegistry.getManager(PackageManagerLocal.class)
5649                                         .withFilteredSnapshot(callingUid, user)) {
5650                     if (loaderIsa != null) {
5651                         // Check that loaderIsa agrees with the ISA that dexUseManager will
5652                         // determine.
5653                         PackageState loadingPkgState =
5654                                 filteredSnapshot.getPackageState(loadingPackageName);
5655                         // If we don't find the loading package just pass it through and let
5656                         // dexUseManager throw on it.
5657                         if (loadingPkgState != null) {
5658                             String loadingPkgAbi = loadingPkgState.getPrimaryCpuAbi();
5659                             if (loadingPkgAbi == null) {
5660                                 loadingPkgAbi = Build.SUPPORTED_ABIS[0];
5661                             }
5662                             String loadingPkgDexCodeIsa = InstructionSets.getDexCodeInstructionSet(
5663                                     VMRuntime.getInstructionSet(loadingPkgAbi));
5664                             if (!loaderIsa.equals(loadingPkgDexCodeIsa)) {
5665                                 // TODO(b/251903639): We make this a wtf to surface any situations
5666                                 // where this argument doesn't correspond to our expectations. Later
5667                                 // it should be turned into an IllegalArgumentException, when we can
5668                                 // assume it's the caller that's wrong rather than us.
5669                                 Log.wtf(TAG,
5670                                         "Invalid loaderIsa in notifyDexLoad call from "
5671                                                 + loadingPackageName + ", uid " + callingUid
5672                                                 + ": expected " + loadingPkgDexCodeIsa + ", got "
5673                                                 + loaderIsa);
5674                                 return;
5675                             }
5676                         }
5677                     }
5678 
5679                     // This is called from binder, so exceptions thrown here are caught and handled
5680                     // by it.
5681                     dexUseManager.notifyDexContainersLoaded(
5682                             filteredSnapshot, loadingPackageName, classLoaderContextMap);
5683                 }
5684             } else {
5685                 ApplicationInfo ai =
5686                         snapshot.getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
5687                 if (ai == null) {
5688                     Slog.w(PackageManagerService.TAG,
5689                             "Loading a package that does not exist for the calling user. package="
5690                                     + loadingPackageName + ", user=" + userId);
5691                     return;
5692                 }
5693                 mDexManager.notifyDexLoad(ai, classLoaderContextMap, loaderIsa, userId,
5694                         Process.isIsolated(callingUid));
5695             }
5696         }
5697 
5698         @Override
5699         public void notifyPackageUse(String packageName, int reason) {
5700             final int callingUid = Binder.getCallingUid();
5701             final int callingUserId = UserHandle.getUserId(callingUid);
5702             Computer snapshot = snapshotComputer();
5703             final boolean notify;
5704             if (snapshot.getInstantAppPackageName(callingUid) != null) {
5705                 notify = snapshot.isCallerSameApp(packageName, callingUid);
5706             } else {
5707                 notify = !snapshot.isInstantAppInternal(packageName, callingUserId,
5708                         Process.SYSTEM_UID);
5709             }
5710             if (!notify) {
5711                 return;
5712             }
5713 
5714             notifyPackageUseInternal(packageName, reason);
5715         }
5716 
5717         @Override
5718         public void overrideLabelAndIcon(@NonNull ComponentName componentName,
5719                 @NonNull String nonLocalizedLabel, int icon, int userId) {
5720             if (TextUtils.isEmpty(nonLocalizedLabel)) {
5721                 throw new IllegalArgumentException("Override label should be a valid String");
5722             }
5723             updateComponentLabelIcon(componentName, nonLocalizedLabel, icon, userId);
5724         }
5725 
5726         @Override
5727         public ParceledListSlice<PackageManager.Property> queryProperty(
5728                 String propertyName, @PackageManager.PropertyLocation int componentType) {
5729             Objects.requireNonNull(propertyName);
5730             final int callingUid = Binder.getCallingUid();
5731             final int callingUserId = UserHandle.getCallingUserId();
5732             final Computer snapshot = snapshotComputer();
5733             final List<PackageManager.Property> result =
5734                     mPackageProperty.queryProperty(propertyName, componentType,
5735                             packageName -> snapshot.getPackageStateForInstalledAndFiltered(
5736                                     packageName, callingUid, callingUserId) == null
5737                     );
5738             if (result == null) {
5739                 return ParceledListSlice.emptyList();
5740             }
5741             return new ParceledListSlice<>(result);
5742         }
5743 
5744         @Override
5745         public void registerDexModule(String packageName, String dexModulePath,
5746                 boolean isSharedModule,
5747                 IDexModuleRegisterCallback callback) {
5748             // ART Service doesn't support this explicit dexopting and instead relies on background
5749             // dexopt for secondary dex files. For compat parity between ART Service and the legacy
5750             // code it's disabled for both.
5751             //
5752             // Also, this API is problematic anyway since it doesn't provide the correct classloader
5753             // context, so it is hard to produce dexopt artifacts that the runtime can load
5754             // successfully.
5755             Slog.i(TAG,
5756                     "Ignored unsupported registerDexModule call for " + dexModulePath + " in "
5757                             + packageName);
5758             DexManager.RegisterDexModuleResult result = new DexManager.RegisterDexModuleResult(
5759                     false, "registerDexModule call not supported since Android U");
5760 
5761             if (callback != null) {
5762                 mHandler.post(() -> {
5763                     try {
5764                         callback.onDexModuleRegistered(dexModulePath, result.success,
5765                                 result.message);
5766                     } catch (RemoteException e) {
5767                         Slog.w(PackageManagerService.TAG,
5768                                 "Failed to callback after module registration " + dexModulePath, e);
5769                     }
5770                 });
5771             }
5772         }
5773 
5774         @android.annotation.EnforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS)
5775         @Override
registerMoveCallback(IPackageMoveObserver callback)5776         public void registerMoveCallback(IPackageMoveObserver callback) {
5777             registerMoveCallback_enforcePermission();
5778             mMoveCallbacks.register(callback);
5779         }
5780 
5781         @Override
restoreDomainVerification(byte[] backup, int userId)5782         public void restoreDomainVerification(byte[] backup, int userId) {
5783             if (Binder.getCallingUid() != Process.SYSTEM_UID) {
5784                 throw new SecurityException("Only the system may call restorePreferredActivities()");
5785             }
5786 
5787             try {
5788                 ByteArrayInputStream input = new ByteArrayInputStream(backup);
5789                 TypedXmlPullParser parser = Xml.resolvePullParser(input);
5790 
5791                 // User ID input isn't necessary here as it assumes the user integers match and that
5792                 // the only states inside the backup XML are for the target user.
5793                 mDomainVerificationManager.restoreSettings(snapshotComputer(), parser);
5794                 input.close();
5795             } catch (Exception e) {
5796                 if (PackageManagerService.DEBUG_BACKUP) {
5797                     Slog.e(PackageManagerService.TAG, "Exception restoring domain verification: " + e.getMessage());
5798                 }
5799             }
5800         }
5801 
5802         @Override
restoreLabelAndIcon(@onNull ComponentName componentName, int userId)5803         public void restoreLabelAndIcon(@NonNull ComponentName componentName, int userId) {
5804             updateComponentLabelIcon(componentName, null, null, userId);
5805         }
5806 
5807         @Override
sendDeviceCustomizationReadyBroadcast()5808         public void sendDeviceCustomizationReadyBroadcast() {
5809             mContext.enforceCallingPermission(Manifest.permission.SEND_DEVICE_CUSTOMIZATION_READY,
5810                     "sendDeviceCustomizationReadyBroadcast");
5811 
5812             final long ident = Binder.clearCallingIdentity();
5813             try {
5814                 BroadcastHelper.sendDeviceCustomizationReadyBroadcast();
5815             } finally {
5816                 Binder.restoreCallingIdentity(ident);
5817             }
5818         }
5819 
5820         @Override
setApplicationCategoryHint(String packageName, int categoryHint, String callerPackageName)5821         public void setApplicationCategoryHint(String packageName, int categoryHint,
5822                 String callerPackageName) {
5823             final int callingUid = Binder.getCallingUid();
5824             final int userId = UserHandle.getCallingUserId();
5825             final FunctionalUtils.ThrowingBiFunction<PackageStateMutator.InitialState, Computer,
5826                     PackageStateMutator.Result> implementation = (initialState, computer) -> {
5827                 if (computer.getInstantAppPackageName(callingUid) != null) {
5828                     throw new SecurityException(
5829                             "Instant applications don't have access to this method");
5830                 }
5831                 final int callerPackageUid = computer.getPackageUid(callerPackageName, 0, userId);
5832                 if (callerPackageUid != callingUid) {
5833                     throw new SecurityException(
5834                             "Package " + callerPackageName + " does not belong to " + callingUid);
5835                 }
5836 
5837                 PackageStateInternal packageState = computer.getPackageStateForInstalledAndFiltered(
5838                         packageName, callingUid, userId);
5839                 if (packageState == null) {
5840                     throw new IllegalArgumentException("Unknown target package " + packageName);
5841                 }
5842 
5843                 if (!Objects.equals(callerPackageName,
5844                         packageState.getInstallSource().mInstallerPackageName)) {
5845                     throw new IllegalArgumentException("Calling package " + callerPackageName
5846                             + " is not installer for " + packageName);
5847                 }
5848 
5849                 if (packageState.getCategoryOverride() != categoryHint) {
5850                     return commitPackageStateMutation(initialState,
5851                             packageName, state -> state.setCategoryOverride(categoryHint));
5852                 } else {
5853                     return null;
5854                 }
5855             };
5856 
5857             PackageStateMutator.Result result =
5858                     implementation.apply(recordInitialState(), snapshotComputer());
5859             if (result != null && result.isStateChanged() && !result.isSpecificPackageNull()) {
5860                 // TODO: Specific return value of what state changed?
5861                 // The installer on record might have changed, retry with lock
5862                 synchronized (mPackageStateWriteLock) {
5863                     result = implementation.apply(recordInitialState(), snapshotComputer());
5864                 }
5865             }
5866 
5867             if (result != null && result.isCommitted()) {
5868                 scheduleWriteSettings();
5869             }
5870         }
5871 
5872         @Override
setApplicationEnabledSetting(String appPackageName, int newState, int flags, int userId, String callingPackage)5873         public void setApplicationEnabledSetting(String appPackageName,
5874                 int newState, int flags, int userId, String callingPackage) {
5875             if (!mUserManager.exists(userId)) return;
5876             if (callingPackage == null) {
5877                 callingPackage = Integer.toString(Binder.getCallingUid());
5878             }
5879 
5880             setEnabledSettings(List.of(new PackageManager.ComponentEnabledSetting(appPackageName, newState, flags)),
5881                     userId, callingPackage);
5882         }
5883 
5884         @Override
setPageSizeAppCompatFlagsSettingsOverride(String packageName, boolean enabled)5885         public void setPageSizeAppCompatFlagsSettingsOverride(String packageName, boolean enabled) {
5886             final int callingUid = Binder.getCallingUid();
5887             final int callingAppId = UserHandle.getAppId(callingUid);
5888 
5889             if (!PackageManagerServiceUtils.isSystemOrRoot(callingAppId)) {
5890                 throw new SecurityException("Caller must be the system or root.");
5891             }
5892 
5893             int settingsMode = enabled
5894                     ? ApplicationInfo.PAGE_SIZE_APP_COMPAT_FLAG_SETTINGS_OVERRIDE_ENABLED
5895                     : ApplicationInfo.PAGE_SIZE_APP_COMPAT_FLAG_SETTINGS_OVERRIDE_DISABLED;
5896             PackageStateMutator.Result result =
5897                     commitPackageStateMutation(
5898                             null,
5899                             packageName,
5900                             packageState ->
5901                                     packageState
5902                                             .setPageSizeAppCompatFlags(settingsMode));
5903             if (result.isSpecificPackageNull()) {
5904                 throw new IllegalArgumentException("Unknown package: " + packageName);
5905             }
5906             scheduleWriteSettings();
5907         }
5908 
5909         @Override
isPageSizeCompatEnabled(String packageName)5910         public boolean isPageSizeCompatEnabled(String packageName) {
5911             final int callingUid = Binder.getCallingUid();
5912             final int callingAppId = UserHandle.getAppId(callingUid);
5913             final int userId = UserHandle.getCallingUserId();
5914 
5915             if (!PackageManagerServiceUtils.isSystemOrRoot(callingAppId)) {
5916                 throw new SecurityException("Caller must be the system or root.");
5917             }
5918 
5919             PackageStateInternal packageState =
5920                     snapshotComputer().getPackageStateForInstalledAndFiltered(
5921                             packageName, callingUid, userId);
5922 
5923             return packageState == null ? false : packageState.isPageSizeAppCompatEnabled();
5924         }
5925 
5926         @Override
getPageSizeCompatWarningMessage(String packageName)5927         public String getPageSizeCompatWarningMessage(String packageName) {
5928             final int callingUid = Binder.getCallingUid();
5929             final int callingAppId = UserHandle.getAppId(callingUid);
5930             final int userId = UserHandle.getCallingUserId();
5931 
5932             if (!PackageManagerServiceUtils.isSystemOrRoot(callingAppId)) {
5933                 throw new SecurityException("Caller must be the system or root.");
5934             }
5935 
5936             PackageStateInternal packageState =
5937                     snapshotComputer().getPackageStateForInstalledAndFiltered(
5938                             packageName, callingUid, userId);
5939 
5940             return packageState == null
5941                     ? null
5942                     : packageState.getPageSizeCompatWarningMessage(mContext);
5943         }
5944 
5945         @android.annotation.EnforcePermission(android.Manifest.permission.MANAGE_USERS)
5946         @Override
setApplicationHiddenSettingAsUser(String packageName, boolean hidden, int userId)5947         public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
5948                 int userId) {
5949             setApplicationHiddenSettingAsUser_enforcePermission();
5950             final int callingUid = Binder.getCallingUid();
5951             final Computer snapshot = snapshotComputer();
5952             snapshot.enforceCrossUserPermission(callingUid, userId, true /* requireFullPermission */,
5953                     true /* checkShell */, "setApplicationHiddenSetting for user " + userId);
5954 
5955             if (hidden && isPackageDeviceAdmin(packageName, userId)) {
5956                 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
5957                 return false;
5958             }
5959 
5960             // Do not allow "android" is being disabled
5961             if ("android".equals(packageName)) {
5962                 Slog.w(TAG, "Cannot hide package: android");
5963                 return false;
5964             }
5965 
5966             final long callingId = Binder.clearCallingIdentity();
5967             try {
5968                 final PackageStateInternal packageState = snapshot.getPackageStateInternal(
5969                         packageName);
5970                 if (packageState == null) {
5971                     return false;
5972                 }
5973 
5974                 final PackageUserStateInternal userState = packageState.getUserStateOrDefault(
5975                         userId);
5976                 if (userState.isHidden() == hidden || !userState.isInstalled()
5977                         || snapshot.shouldFilterApplication(packageState, callingUid, userId)) {
5978                     return false;
5979                 }
5980 
5981                 // Cannot hide static shared libs as they are considered
5982                 // a part of the using app (emulating static linking). Also
5983                 // static libs are installed always on internal storage.
5984                 AndroidPackage pkg = packageState.getPkg();
5985                 if (pkg != null) {
5986                     // Cannot hide SDK libs as they are controlled by SDK manager.
5987                     if (pkg.getSdkLibraryName() != null) {
5988                         Slog.w(TAG, "Cannot hide package: " + packageName
5989                                 + " providing SDK library: "
5990                                 + pkg.getSdkLibraryName());
5991                         return false;
5992                     }
5993                     // Cannot hide static shared libs as they are considered
5994                     // a part of the using app (emulating static linking). Also
5995                     // static libs are installed always on internal storage.
5996                     if (pkg.getStaticSharedLibraryName() != null) {
5997                         Slog.w(TAG, "Cannot hide package: " + packageName
5998                                 + " providing static shared library: "
5999                                 + pkg.getStaticSharedLibraryName());
6000                         return false;
6001                     }
6002                 }
6003                 // Only allow protected packages to hide themselves.
6004                 if (hidden && !UserHandle.isSameApp(callingUid, packageState.getAppId())
6005                         && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
6006                     Slog.w(TAG, "Not hiding protected package: " + packageName);
6007                     return false;
6008                 }
6009 
6010                 commitPackageStateMutation(null, packageName, packageState1 ->
6011                         packageState1.userState(userId).setHidden(hidden));
6012 
6013                 final Computer newSnapshot = snapshotComputer();
6014                 final PackageStateInternal newPackageState =
6015                         newSnapshot.getPackageStateInternal(packageName);
6016 
6017                 if (hidden) {
6018                     killApplication(packageName, newPackageState.getAppId(), userId, "hiding pkg",
6019                             ApplicationExitInfo.REASON_OTHER);
6020                     mBroadcastHelper.sendApplicationHiddenForUser(
6021                             packageName, newPackageState, userId,
6022                             /* packageSender= */ PackageManagerService.this);
6023                 } else {
6024                     mBroadcastHelper.sendPackageAddedForUser(
6025                             newSnapshot, packageName, newPackageState, userId,
6026                             false /* isArchived */, DataLoaderType.NONE,
6027                             mAppPredictionServicePackage);
6028                 }
6029 
6030                 scheduleWritePackageRestrictions(userId);
6031                 return true;
6032             } finally {
6033                 Binder.restoreCallingIdentity(callingId);
6034             }
6035         }
6036 
6037         @android.annotation.EnforcePermission(android.Manifest.permission.DELETE_PACKAGES)
6038         @Override
setBlockUninstallForUser(String packageName, boolean blockUninstall, int userId)6039         public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
6040                 int userId) {
6041             setBlockUninstallForUser_enforcePermission();
6042             final Computer snapshot = snapshotComputer();
6043             PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName);
6044             if (packageState != null && packageState.getPkg() != null) {
6045                 AndroidPackage pkg = packageState.getPkg();
6046                 // Cannot block uninstall SDK libs as they are controlled by SDK manager.
6047                 if (pkg.getSdkLibraryName() != null) {
6048                     Slog.w(PackageManagerService.TAG, "Cannot block uninstall of package: " + packageName
6049                             + " providing SDK library: " + pkg.getSdkLibraryName());
6050                     return false;
6051                 }
6052                 // Cannot block uninstall of static shared libs as they are
6053                 // considered a part of the using app (emulating static linking).
6054                 // Also static libs are installed always on internal storage.
6055                 if (pkg.getStaticSharedLibraryName() != null) {
6056                     Slog.w(PackageManagerService.TAG, "Cannot block uninstall of package: " + packageName
6057                             + " providing static shared library: " + pkg.getStaticSharedLibraryName());
6058                     return false;
6059                 }
6060             }
6061             synchronized (mLock) {
6062                 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
6063             }
6064 
6065             scheduleWritePackageRestrictions(userId);
6066             return true;
6067         }
6068 
6069         @Override
setComponentEnabledSetting(ComponentName componentName, int newState, int flags, int userId, String callingPackage)6070         public void setComponentEnabledSetting(ComponentName componentName,
6071                 int newState, int flags, int userId, String callingPackage) {
6072             if (!mUserManager.exists(userId)) return;
6073             if (callingPackage == null) {
6074                 callingPackage = Integer.toString(Binder.getCallingUid());
6075             }
6076 
6077             setEnabledSettings(List.of(new PackageManager.ComponentEnabledSetting(componentName, newState, flags)),
6078                     userId, callingPackage);
6079         }
6080 
6081         @Override
setComponentEnabledSettings( List<PackageManager.ComponentEnabledSetting> settings, int userId, String callingPackage)6082         public void setComponentEnabledSettings(
6083                 List<PackageManager.ComponentEnabledSetting> settings, int userId,
6084                 String callingPackage) {
6085             if (!mUserManager.exists(userId)) return;
6086             if (settings == null || settings.isEmpty()) {
6087                 throw new IllegalArgumentException("The list of enabled settings is empty");
6088             }
6089             if (callingPackage == null) {
6090                 callingPackage = Integer.toString(Binder.getCallingUid());
6091             }
6092             setEnabledSettings(settings, userId, callingPackage);
6093         }
6094 
6095         @Override
setDistractingPackageRestrictionsAsUser(String[] packageNames, int restrictionFlags, int userId)6096         public String[] setDistractingPackageRestrictionsAsUser(String[] packageNames,
6097                 int restrictionFlags, int userId) {
6098             final int callingUid = Binder.getCallingUid();
6099             final Computer snapshot = snapshotComputer();
6100             enforceCanSetDistractingPackageRestrictionsAsUser(callingUid, userId,
6101                     "setDistractingPackageRestrictionsAsUser");
6102             Objects.requireNonNull(packageNames, "packageNames cannot be null");
6103             return mDistractingPackageHelper.setDistractingPackageRestrictionsAsUser(snapshot,
6104                     packageNames, restrictionFlags, userId, callingUid);
6105         }
6106 
6107         @Override
setHarmfulAppWarning(@onNull String packageName, @Nullable CharSequence warning, int userId)6108         public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
6109                 int userId) {
6110             final int callingUid = Binder.getCallingUid();
6111             final int callingAppId = UserHandle.getAppId(callingUid);
6112 
6113             final Computer snapshot = snapshotComputer();
6114             snapshot.enforceCrossUserPermission(callingUid, userId, true /*requireFullPermission*/,
6115                     true /*checkShell*/, "setHarmfulAppInfo");
6116 
6117             if (!PackageManagerServiceUtils.isSystemOrRoot(callingAppId)
6118                     && snapshot.checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid)
6119                             != PERMISSION_GRANTED) {
6120                 throw new SecurityException("Caller must have the "
6121                         + SET_HARMFUL_APP_WARNINGS + " permission.");
6122             }
6123 
6124             PackageStateMutator.Result result = commitPackageStateMutation(null, packageName,
6125                     packageState -> packageState.userState(userId)
6126                             .setHarmfulAppWarning(warning == null ? null : warning.toString()));
6127             if (result.isSpecificPackageNull()) {
6128                 throw new IllegalArgumentException("Unknown package: " + packageName);
6129             }
6130             scheduleWritePackageRestrictions(userId);
6131         }
6132 
6133         @android.annotation.EnforcePermission(android.Manifest.permission.WRITE_SECURE_SETTINGS)
6134         @Override
setInstallLocation(int loc)6135         public boolean setInstallLocation(int loc) {
6136             setInstallLocation_enforcePermission();
6137             if (getInstallLocation() == loc) {
6138                 return true;
6139             }
6140             if (loc == InstallLocationUtils.APP_INSTALL_AUTO
6141                     || loc == InstallLocationUtils.APP_INSTALL_INTERNAL
6142                     || loc == InstallLocationUtils.APP_INSTALL_EXTERNAL) {
6143                 android.provider.Settings.Global.putInt(mContext.getContentResolver(),
6144                         android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
6145                 return true;
6146             }
6147             return false;
6148         }
6149 
6150         @Override
setInstallerPackageName(String targetPackage, @Nullable String installerPackageName)6151         public void setInstallerPackageName(String targetPackage,
6152                 @Nullable String installerPackageName) {
6153             final int callingUid = Binder.getCallingUid();
6154             final int callingUserId = UserHandle.getUserId(callingUid);
6155             final FunctionalUtils.ThrowingCheckedFunction<Computer, Boolean, RuntimeException>
6156                     implementation = snapshot -> {
6157                 if (snapshot.getInstantAppPackageName(callingUid) != null) {
6158                     return false;
6159                 }
6160 
6161                 PackageStateInternal targetPackageState =
6162                         snapshot.getPackageStateForInstalledAndFiltered(
6163                                 targetPackage, callingUid, callingUserId);
6164                 if (targetPackageState == null) {
6165                     throw new IllegalArgumentException("Unknown target package: " + targetPackage);
6166                 }
6167 
6168                 PackageStateInternal installerPackageState = null;
6169                 if (installerPackageName != null) {
6170                     installerPackageState = snapshot.getPackageStateForInstalledAndFiltered(
6171                             installerPackageName, callingUid, callingUserId);
6172                     if (installerPackageState == null) {
6173                         throw new IllegalArgumentException("Unknown installer package: "
6174                                 + installerPackageName);
6175                     }
6176                 }
6177 
6178                 SigningDetails callerSigningDetails;
6179                 final int appId = UserHandle.getAppId(callingUid);
6180                 Pair<PackageStateInternal, SharedUserApi> either =
6181                         snapshot.getPackageOrSharedUser(appId);
6182                 if (either != null) {
6183                     if (either.first != null) {
6184                         callerSigningDetails = either.first.getSigningDetails();
6185                     } else {
6186                         callerSigningDetails = either.second.getSigningDetails();
6187                     }
6188                 } else {
6189                     throw new SecurityException("Unknown calling UID: " + callingUid);
6190                 }
6191 
6192                 // Verify: can't set installerPackageName to a package that is
6193                 // not signed with the same cert as the caller.
6194                 if (installerPackageState != null) {
6195                     if (compareSignatures(callerSigningDetails,
6196                             installerPackageState.getSigningDetails())
6197                             != PackageManager.SIGNATURE_MATCH) {
6198                         throw new SecurityException(
6199                                 "Caller does not have same cert as new installer package "
6200                                         + installerPackageName);
6201                     }
6202                 }
6203 
6204                 // Verify: if target already has an installer package, it must
6205                 // be signed with the same cert as the caller.
6206                 String targetInstallerPackageName =
6207                         targetPackageState.getInstallSource().mInstallerPackageName;
6208                 PackageStateInternal targetInstallerPkgSetting = targetInstallerPackageName == null
6209                         ? null : snapshot.getPackageStateInternal(targetInstallerPackageName);
6210 
6211                 if (targetInstallerPkgSetting != null) {
6212                     if (compareSignatures(callerSigningDetails,
6213                             targetInstallerPkgSetting.getSigningDetails())
6214                             != PackageManager.SIGNATURE_MATCH) {
6215                         throw new SecurityException(
6216                                 "Caller does not have same cert as old installer package "
6217                                         + targetInstallerPackageName);
6218                     }
6219                 } else if (mContext.checkCallingOrSelfPermission(
6220                         Manifest.permission.INSTALL_PACKAGES) != PERMISSION_GRANTED) {
6221                     // This is probably an attempt to exploit vulnerability b/150857253 of taking
6222                     // privileged installer permissions when the installer has been uninstalled or
6223                     // was never set.
6224                     EventLog.writeEvent(0x534e4554, "150857253", callingUid, "");
6225 
6226                     final long binderToken = Binder.clearCallingIdentity();
6227                     try {
6228                         if (mInjector.getCompatibility().isChangeEnabledByUid(
6229                                 PackageManagerService.THROW_EXCEPTION_ON_REQUIRE_INSTALL_PACKAGES_TO_ADD_INSTALLER_PACKAGE,
6230                                 callingUid)) {
6231                             throw new SecurityException("Neither user " + callingUid
6232                                     + " nor current process has "
6233                                     + Manifest.permission.INSTALL_PACKAGES);
6234                         } else {
6235                             // If change disabled, fail silently for backwards compatibility
6236                             return false;
6237                         }
6238                     } finally {
6239                         Binder.restoreCallingIdentity(binderToken);
6240                     }
6241                 }
6242 
6243                 return true;
6244             };
6245             PackageStateMutator.InitialState initialState = recordInitialState();
6246             boolean allowed = implementation.apply(snapshotComputer());
6247             if (allowed) {
6248                 // TODO: Need to lock around here to handle mSettings.addInstallerPackageNames,
6249                 //  should find an alternative which avoids any race conditions
6250                 final int installerPackageUid = installerPackageName == null
6251                         ? INVALID_UID : snapshotComputer().getPackageUid(installerPackageName,
6252                         0 /* flags */, callingUserId);
6253                 PackageStateInternal targetPackageState;
6254                 synchronized (mLock) {
6255                     PackageStateMutator.Result result = commitPackageStateMutation(initialState,
6256                             targetPackage, state -> state.setInstaller(installerPackageName,
6257                                     installerPackageUid));
6258                     if (result.isPackagesChanged() || result.isStateChanged()) {
6259                         synchronized (mPackageStateWriteLock) {
6260                             allowed = implementation.apply(snapshotComputer());
6261                             if (allowed) {
6262                                 commitPackageStateMutation(null, targetPackage,
6263                                         state -> state.setInstaller(installerPackageName,
6264                                                 installerPackageUid));
6265                             } else {
6266                                 return;
6267                             }
6268                         }
6269                     }
6270                     targetPackageState = snapshotComputer().getPackageStateInternal(targetPackage);
6271                     mSettings.addInstallerPackageNames(targetPackageState.getInstallSource());
6272                 }
6273                 mAppsFilter.addPackage(snapshotComputer(), targetPackageState);
6274                 scheduleWriteSettings();
6275             }
6276         }
6277 
6278         @Override
relinquishUpdateOwnership(String targetPackage)6279         public void relinquishUpdateOwnership(String targetPackage) {
6280             final int callingUid = Binder.getCallingUid();
6281             final int callingUserId = UserHandle.getUserId(callingUid);
6282             final Computer snapshot = snapshotComputer();
6283 
6284             final PackageStateInternal targetPackageState =
6285                     snapshot.getPackageStateForInstalledAndFiltered(targetPackage, callingUid,
6286                             callingUserId);
6287             if (targetPackageState == null) {
6288                 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
6289             }
6290 
6291             final String targetUpdateOwnerPackageName =
6292                     targetPackageState.getInstallSource().mUpdateOwnerPackageName;
6293             final PackageStateInternal targetUpdateOwnerPkgSetting =
6294                     targetUpdateOwnerPackageName == null ? null
6295                             : snapshot.getPackageStateInternal(targetUpdateOwnerPackageName);
6296 
6297             if (targetUpdateOwnerPkgSetting == null) {
6298                 return;
6299             }
6300 
6301             final int callingAppId = UserHandle.getAppId(callingUid);
6302             final int targetUpdateOwnerAppId = targetUpdateOwnerPkgSetting.getAppId();
6303             if (callingAppId != Process.SYSTEM_UID
6304                     && callingAppId != Process.SHELL_UID
6305                     && callingAppId != targetUpdateOwnerAppId) {
6306                 throw new SecurityException("Caller is not the current update owner.");
6307             }
6308 
6309             commitPackageStateMutation(null /* initialState */, targetPackage,
6310                     state -> state.setUpdateOwner(null /* updateOwnerPackageName */));
6311             scheduleWriteSettings();
6312         }
6313 
6314         @Override
setInstantAppCookie(String packageName, byte[] cookie, int userId)6315         public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
6316             if (HIDE_EPHEMERAL_APIS) {
6317                 return true;
6318             }
6319 
6320             final Computer snapshot = snapshotComputer();
6321             snapshot.enforceCrossUserPermission(Binder.getCallingUid(), userId,
6322                     true /* requireFullPermission */, true /* checkShell */,
6323                     "setInstantAppCookie");
6324             if (!snapshot.isCallerSameApp(packageName, Binder.getCallingUid())) {
6325                 return false;
6326             }
6327 
6328             PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName);
6329             if (packageState == null || packageState.getPkg() == null) {
6330                 return false;
6331             }
6332             return mInstantAppRegistry.setInstantAppCookie(packageState.getPkg(), cookie,
6333                     mContext.getPackageManager().getInstantAppCookieMaxBytes(), userId);
6334         }
6335 
6336         @Override
setKeepUninstalledPackages(List<String> packageList)6337         public void setKeepUninstalledPackages(List<String> packageList) {
6338             mContext.enforceCallingPermission(
6339                     Manifest.permission.KEEP_UNINSTALLED_PACKAGES,
6340                     "setKeepUninstalledPackages requires KEEP_UNINSTALLED_PACKAGES permission");
6341             Objects.requireNonNull(packageList);
6342 
6343             setKeepUninstalledPackagesInternal(snapshot(), packageList);
6344         }
6345 
6346         @Override
setMimeGroup(String packageName, String mimeGroup, List<String> mimeTypes)6347         public void setMimeGroup(String packageName, String mimeGroup, List<String> mimeTypes) {
6348             final Computer snapshot = snapshotComputer();
6349             final int callingUid = Binder.getCallingUid();
6350             enforceOwnerRights(snapshot, packageName, callingUid);
6351             mimeTypes = CollectionUtils.emptyIfNull(mimeTypes);
6352             for (int i = 0; i < mimeTypes.size(); i++) {
6353                 if (mimeTypes.get(i).length() > 255) {
6354                     throw new IllegalArgumentException("MIME type length exceeds 255 characters");
6355                 }
6356             }
6357             final PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName);
6358             Set<String> existingMimeTypes = packageState.getMimeGroups().get(mimeGroup);
6359             if (existingMimeTypes == null) {
6360                 throw new IllegalArgumentException("Unknown MIME group " + mimeGroup
6361                         + " for package " + packageName);
6362             }
6363             if (existingMimeTypes.size() == mimeTypes.size()
6364                     && existingMimeTypes.containsAll(mimeTypes)) {
6365                 return;
6366             }
6367             if (mimeTypes.size() > 500) {
6368                 throw new IllegalStateException("Max limit on MIME types for MIME group "
6369                         + mimeGroup + " exceeded for package " + packageName);
6370             }
6371 
6372             ArraySet<String> mimeTypesSet = new ArraySet<>(mimeTypes);
6373             commitPackageStateMutation(null, packageName, packageStateWrite -> {
6374                 packageStateWrite.setMimeGroup(mimeGroup, mimeTypesSet);
6375             });
6376             if (mComponentResolver.updateMimeGroup(snapshotComputer(), packageName, mimeGroup)) {
6377                 Binder.withCleanCallingIdentity(() -> {
6378                     mPreferredActivityHelper.clearPackagePreferredActivities(packageName,
6379                             USER_ALL);
6380                     // Send the ACTION_PACKAGE_CHANGED when the mimeGroup has changes
6381                     final Computer snapShot = snapshotComputer();
6382                     final ArrayList<String> components = new ArrayList<>(
6383                             Collections.singletonList(packageName));
6384                     final int appId = packageState.getAppId();
6385                     final int[] userIds = resolveUserIds(USER_ALL);
6386                     final String reason = "The mimeGroup is changed";
6387                     for (int i = 0; i < userIds.length; i++) {
6388                         final PackageUserStateInternal pkgUserState =
6389                                 packageState.getUserStates().get(userIds[i]);
6390                         if (pkgUserState != null && pkgUserState.isInstalled()) {
6391                             final int packageUid = UserHandle.getUid(userIds[i], appId);
6392                             mBroadcastHelper.sendPackageChangedBroadcast(snapShot, packageName,
6393                                     true /* dontKillApp */, components, packageUid, reason,
6394                                     "mime_group_changed" /* reasonForTrace */, callingUid);
6395                         }
6396                     }
6397                 });
6398             }
6399 
6400             scheduleWriteSettings();
6401         }
6402 
6403         @Override
setPackageStoppedState(String packageName, boolean stopped, int userId)6404         public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
6405             PackageManagerService.this
6406                     .setPackageStoppedState(snapshotComputer(), packageName, stopped, userId);
6407         }
6408 
6409         @Override
setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, PersistableBundle appExtras, PersistableBundle launcherExtras, SuspendDialogInfo dialogInfo, int flags, String suspendingPackage, int suspendingUserId, int targetUserId)6410         public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
6411                 PersistableBundle appExtras, PersistableBundle launcherExtras,
6412                 SuspendDialogInfo dialogInfo, int flags, String suspendingPackage,
6413                 int suspendingUserId, int targetUserId) {
6414             final int callingUid = Binder.getCallingUid();
6415             final boolean quarantined = ((flags & PackageManager.FLAG_SUSPEND_QUARANTINED) != 0)
6416                     && Flags.quarantinedEnabled();
6417             final Computer snapshot = snapshotComputer();
6418             final UserPackage suspender = crossUserSuspensionEnabledRo()
6419                     ? UserPackage.of(suspendingUserId, suspendingPackage)
6420                     : UserPackage.of(targetUserId, suspendingPackage);
6421             enforceCanSetPackagesSuspendedAsUser(snapshot, quarantined, suspender, callingUid,
6422                     targetUserId, "setPackagesSuspendedAsUser");
6423             return mSuspendPackageHelper.setPackagesSuspended(snapshot, packageNames, suspended,
6424                     appExtras, launcherExtras, dialogInfo, suspender, targetUserId, callingUid,
6425                     quarantined);
6426         }
6427 
6428         @Override
setRequiredForSystemUser(String packageName, boolean requiredForSystemUser)6429         public boolean setRequiredForSystemUser(String packageName, boolean requiredForSystemUser) {
6430             PackageManagerServiceUtils.enforceSystemOrRoot(
6431                     "setRequiredForSystemUser can only be run by the system or root");
6432 
6433             PackageStateMutator.Result result = commitPackageStateMutation(null, packageName,
6434                     packageState -> packageState.setRequiredForSystemUser(requiredForSystemUser));
6435             if (!result.isCommitted()) {
6436                 return false;
6437             }
6438 
6439             scheduleWriteSettings();
6440             return true;
6441         }
6442 
6443         @android.annotation.EnforcePermission(android.Manifest.permission.INSTALL_PACKAGES)
6444         @Override
setUserMinAspectRatio(@onNull String packageName, int userId, @PackageManager.UserMinAspectRatio int aspectRatio)6445         public void setUserMinAspectRatio(@NonNull String packageName, int userId,
6446                 @PackageManager.UserMinAspectRatio int aspectRatio) {
6447             setUserMinAspectRatio_enforcePermission();
6448             final int callingUid = Binder.getCallingUid();
6449             final Computer snapshot = snapshotComputer();
6450             snapshot.enforceCrossUserPermission(callingUid, userId,
6451                     false /* requireFullPermission */, false /* checkShell */,
6452                     "setUserMinAspectRatio");
6453             enforceOwnerRights(snapshot, packageName, callingUid);
6454 
6455             final PackageStateInternal packageState = snapshot
6456                     .getPackageStateForInstalledAndFiltered(packageName, callingUid, userId);
6457             if (packageState == null) {
6458                 return;
6459             }
6460 
6461             if (packageState.getUserStateOrDefault(userId).getMinAspectRatio() == aspectRatio) {
6462                 return;
6463             }
6464 
6465             commitPackageStateMutation(null, packageName, state ->
6466                     state.userState(userId).setMinAspectRatio(aspectRatio));
6467         }
6468 
6469         @Override
6470         @SuppressWarnings("GuardedBy")
setRuntimePermissionsVersion(int version, @UserIdInt int userId)6471         public void setRuntimePermissionsVersion(int version, @UserIdInt int userId) {
6472             Preconditions.checkArgumentNonnegative(version);
6473             Preconditions.checkArgumentNonnegative(userId);
6474             enforceAdjustRuntimePermissionsPolicyOrUpgradeRuntimePermissions(
6475                     "setRuntimePermissionVersion");
6476             mSettings.setDefaultRuntimePermissionsVersion(version, userId);
6477         }
6478 
6479         @Override
setSplashScreenTheme(@onNull String packageName, @Nullable String themeId, int userId)6480         public void setSplashScreenTheme(@NonNull String packageName, @Nullable String themeId,
6481                 int userId) {
6482             final int callingUid = Binder.getCallingUid();
6483             final Computer snapshot = snapshotComputer();
6484             snapshot.enforceCrossUserPermission(callingUid, userId, false /* requireFullPermission */,
6485                     false /* checkShell */, "setSplashScreenTheme");
6486             enforceOwnerRights(snapshot, packageName, callingUid);
6487 
6488             PackageStateInternal packageState = snapshot.getPackageStateForInstalledAndFiltered(
6489                     packageName, callingUid, userId);
6490             if (packageState == null) {
6491                 return;
6492             }
6493 
6494             commitPackageStateMutation(null, packageName, state ->
6495                     state.userState(userId).setSplashScreenTheme(themeId));
6496         }
6497 
6498         @android.annotation.EnforcePermission(android.Manifest.permission.INSTALL_PACKAGES)
6499         @Override
setUpdateAvailable(String packageName, boolean updateAvailable)6500         public void setUpdateAvailable(String packageName, boolean updateAvailable) {
6501             setUpdateAvailable_enforcePermission();
6502             commitPackageStateMutation(null, packageName, state ->
6503                     state.setUpdateAvailable(updateAvailable));
6504         }
6505 
6506         @android.annotation.EnforcePermission(android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS)
6507         @Override
unregisterMoveCallback(IPackageMoveObserver callback)6508         public void unregisterMoveCallback(IPackageMoveObserver callback) {
6509             unregisterMoveCallback_enforcePermission();
6510             mMoveCallbacks.unregister(callback);
6511         }
6512 
6513         @Override
verifyPendingInstall(int verificationId, int verificationCode)6514         public void verifyPendingInstall(int verificationId, int verificationCode)
6515                 throws RemoteException {
6516             // Negative ids correspond to testing verifiers and will be silently enforced in
6517             // the handler thread.
6518             if (verificationId >= 0) {
6519                 mContext.enforceCallingOrSelfPermission(
6520                         Manifest.permission.PACKAGE_VERIFICATION_AGENT,
6521                         "Only package verification agents can verify applications");
6522             }
6523             final int callingUid = Binder.getCallingUid();
6524 
6525             mHandler.post(() -> {
6526                 final int id = verificationId >= 0 ? verificationId : -verificationId;
6527                 final PackageVerificationState state = mPendingVerification.get(id);
6528                 if (state == null) {
6529                     return;
6530                 }
6531                 if (!state.checkRequiredVerifierUid(callingUid)
6532                         && !state.checkSufficientVerifierUid(callingUid)) {
6533                     // Only allow calls from verifiers.
6534                     return;
6535                 }
6536 
6537                 final Message msg = mHandler.obtainMessage(PackageManagerService.PACKAGE_VERIFIED);
6538                 final PackageVerificationResponse response = new PackageVerificationResponse(
6539                         verificationCode, callingUid);
6540                 msg.arg1 = id;
6541                 msg.obj = response;
6542                 mHandler.sendMessage(msg);
6543             });
6544         }
6545 
6546         @Override
registerPackageMonitorCallback(@onNull IRemoteCallback callback, int userId)6547         public void registerPackageMonitorCallback(@NonNull IRemoteCallback callback, int userId) {
6548             int uid = Binder.getCallingUid();
6549             int targetUserId = ActivityManager.handleIncomingUser(Binder.getCallingPid(), uid,
6550                     userId, true, true, "registerPackageMonitorCallback",
6551                     mContext.getPackageName());
6552             mPackageMonitorCallbackHelper.registerPackageMonitorCallback(callback, targetUserId,
6553                     uid);
6554         }
6555 
6556         @Override
unregisterPackageMonitorCallback(@onNull IRemoteCallback callback)6557         public void unregisterPackageMonitorCallback(@NonNull IRemoteCallback callback) {
6558             mPackageMonitorCallbackHelper.unregisterPackageMonitorCallback(callback);
6559         }
6560 
6561         @Override
requestPackageChecksums(@onNull String packageName, boolean includeSplits, @Checksum.TypeMask int optional, @Checksum.TypeMask int required, @Nullable List trustedInstallers, @NonNull IOnChecksumsReadyListener onChecksumsReadyListener, int userId)6562         public void requestPackageChecksums(@NonNull String packageName, boolean includeSplits,
6563                 @Checksum.TypeMask int optional, @Checksum.TypeMask int required,
6564                 @Nullable List trustedInstallers,
6565                 @NonNull IOnChecksumsReadyListener onChecksumsReadyListener, int userId) {
6566             requestChecksumsInternal(snapshotComputer(), packageName, includeSplits, optional,
6567                     required, trustedInstallers, onChecksumsReadyListener, userId,
6568                     mInjector.getBackgroundExecutor(), mInjector.getBackgroundHandler());
6569         }
6570 
6571         @Override
notifyPackagesReplacedReceived(String[] packages)6572         public void notifyPackagesReplacedReceived(String[] packages) {
6573             Computer computer = snapshotComputer();
6574             ArraySet<String> packagesToNotify = computer.getNotifyPackagesForReplacedReceived(packages);
6575             for (int index = 0; index < packagesToNotify.size(); index++) {
6576                 notifyInstallObserver(packagesToNotify.valueAt(index), false /* killApp */);
6577             }
6578         }
6579 
6580         @Override
getArchivedPackage(@onNull String packageName, int userId)6581         public ArchivedPackageParcel getArchivedPackage(@NonNull String packageName, int userId) {
6582             return getArchivedPackageInternal(packageName, userId);
6583         }
6584 
6585         @Override
getArchivedAppIcon(@onNull String packageName, @NonNull UserHandle user, @NonNull String callingPackageName)6586         public Bitmap getArchivedAppIcon(@NonNull String packageName, @NonNull UserHandle user,
6587                 @NonNull String callingPackageName) {
6588             return mInstallerService.mPackageArchiver.getArchivedAppIcon(packageName, user,
6589                     callingPackageName);
6590         }
6591 
6592         @Override
isAppArchivable(@onNull String packageName, @NonNull UserHandle user)6593         public boolean isAppArchivable(@NonNull String packageName, @NonNull UserHandle user) {
6594             return mInstallerService.mPackageArchiver.isAppArchivable(packageName, user);
6595         }
6596 
6597         /**
6598          * Wait for the handler to finish handling all pending messages.
6599          * @param timeoutMillis Maximum time in milliseconds to wait.
6600          * @param forBackgroundHandler Whether to wait for the background handler instead.
6601          * @return True if all the waiting messages in the handler has been handled.
6602          *         False if timeout.
6603          */
6604         @Override
waitForHandler(long timeoutMillis, boolean forBackgroundHandler)6605         public boolean waitForHandler(long timeoutMillis, boolean forBackgroundHandler) {
6606             final CountDownLatch latch = new CountDownLatch(1);
6607             if (forBackgroundHandler) {
6608                 mBackgroundHandler.post(latch::countDown);
6609             } else {
6610                 mHandler.post(latch::countDown);
6611             }
6612             final long endTimeMillis = System.currentTimeMillis() + timeoutMillis;
6613             while (latch.getCount() > 0) {
6614                 try {
6615                     final long remainingTimeMillis = endTimeMillis - System.currentTimeMillis();
6616                     if (remainingTimeMillis <= 0) {
6617                         return false;
6618                     }
6619                     return latch.await(remainingTimeMillis, TimeUnit.MILLISECONDS);
6620                 } catch (InterruptedException e) {
6621                     // ignore and retry
6622                 }
6623             }
6624             return true;
6625         }
6626 
6627         @Override
6628         @Nullable
getDomainVerificationAgent(int userId)6629         public ComponentName getDomainVerificationAgent(int userId) {
6630             final int callerUid = Binder.getCallingUid();
6631             if (!PackageManagerServiceUtils.isRootOrShell(callerUid)) {
6632                 throw new SecurityException("Not allowed to query domain verification agent");
6633             }
6634             final Computer snapshot = snapshotComputer();
6635             final ComponentName agent = mDomainVerificationManager.getProxy().getComponentName();
6636             final PackageStateInternal ps = snapshot.getPackageStateForInstalledAndFiltered(
6637                     agent.getPackageName(), callerUid, userId);
6638             if (ps == null) {
6639                 return null;
6640             }
6641             final var disabledComponents =
6642                     ps.getUserStateOrDefault(userId).getDisabledComponentsNoCopy();
6643             if (disabledComponents != null && disabledComponents.contains(agent.getClassName())) {
6644                 return null;
6645             }
6646             // Only return the result if the agent is installed and enabled on the target user
6647             return agent;
6648         }
6649 
6650         @Override
6651         @NonNull
getAllApexDirectories()6652         public List<String> getAllApexDirectories() {
6653             PackageManagerServiceUtils.enforceSystemOrRoot(
6654                     "getAllApexDirectories can only be called by system or root");
6655             List<String> apexDirectories = new ArrayList<>();
6656             List<ApexManager.ActiveApexInfo> apexes = mApexManager.getActiveApexInfos();
6657             for (int i = 0; i < apexes.size(); i++) {
6658                 ApexManager.ActiveApexInfo apex = apexes.get(i);
6659                 apexDirectories.add(apex.apexDirectory.getAbsolutePath());
6660             }
6661             return apexDirectories;
6662         }
6663 
6664         @Override
onTransact(int code, Parcel data, Parcel reply, int flags)6665         public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
6666                 throws RemoteException {
6667             try {
6668                 return super.onTransact(code, data, reply, flags);
6669             } catch (RuntimeException e) {
6670                 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)
6671                         && !(e instanceof ParcelableException)) {
6672                     Slog.wtf(TAG, "Package Manager Unexpected Exception", e);
6673                 }
6674                 throw e;
6675             }
6676         }
6677 
6678         @Override
onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver)6679         public void onShellCommand(FileDescriptor in, FileDescriptor out,
6680                 FileDescriptor err, String[] args, ShellCallback callback,
6681                 ResultReceiver resultReceiver) {
6682             (new PackageManagerShellCommand(this, mContext,
6683                     mDomainVerificationManager.getShell()))
6684                     .exec(this, in, out, err, args, callback, resultReceiver);
6685         }
6686 
6687         @SuppressWarnings("resource")
6688         @Override
dump(FileDescriptor fd, PrintWriter pw, String[] args)6689         protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6690             if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
6691             final Computer snapshot = snapshotComputer();
6692             final KnownPackages knownPackages = new KnownPackages(
6693                     mDefaultAppProvider,
6694                     mRequiredInstallerPackage,
6695                     mRequiredUninstallerPackage,
6696                     mSetupWizardPackage,
6697                     mRequiredVerifierPackages,
6698                     mDefaultTextClassifierPackage,
6699                     mSystemTextClassifierPackageName,
6700                     mRequiredPermissionControllerPackage,
6701                     mConfiguratorPackage,
6702                     mIncidentReportApproverPackage,
6703                     mAmbientContextDetectionPackage,
6704                     mWearableSensingPackage,
6705                     mAppPredictionServicePackage,
6706                     COMPANION_PACKAGE_NAME,
6707                     mRetailDemoPackage,
6708                     mOverlayConfigSignaturePackage,
6709                     mRecentsPackage);
6710             final ArrayMap<String, FeatureInfo> availableFeatures;
6711             availableFeatures = new ArrayMap<>(mAvailableFeatures);
6712             final ArraySet<String> protectedBroadcasts;
6713             synchronized (mProtectedBroadcasts) {
6714                 protectedBroadcasts = new ArraySet<>(mProtectedBroadcasts);
6715             }
6716             new DumpHelper(mPermissionManager, mStorageEventHelper,
6717                     mDomainVerificationManager, mInstallerService, mRequiredVerifierPackages,
6718                     knownPackages, mChangedPackagesTracker, availableFeatures, protectedBroadcasts,
6719                     getPerUidReadTimeouts(snapshot), mSnapshotStatistics
6720             ).doDump(snapshot, fd, pw, args);
6721         }
6722     }
6723 
6724     private class PackageManagerInternalImpl extends PackageManagerInternalBase {
6725 
PackageManagerInternalImpl()6726         public PackageManagerInternalImpl() {
6727             super(PackageManagerService.this);
6728         }
6729 
6730         @NonNull
6731         @Override
getContext()6732         protected Context getContext() {
6733             return mContext;
6734         }
6735 
6736         @NonNull
6737         @Override
getPermissionManager()6738         protected PermissionManagerServiceInternal getPermissionManager() {
6739             return mPermissionManager;
6740         }
6741 
6742         @NonNull
6743         @Override
getAppDataHelper()6744         protected AppDataHelper getAppDataHelper() {
6745             return mAppDataHelper;
6746         }
6747 
6748         @NonNull
6749         @Override
getPackageObserverHelper()6750         protected PackageObserverHelper getPackageObserverHelper() {
6751             return mPackageObserverHelper;
6752         }
6753 
6754         @NonNull
6755         @Override
getResolveIntentHelper()6756         protected ResolveIntentHelper getResolveIntentHelper() {
6757             return mResolveIntentHelper;
6758         }
6759 
6760         @NonNull
6761         @Override
getSuspendPackageHelper()6762         protected SuspendPackageHelper getSuspendPackageHelper() {
6763             return mSuspendPackageHelper;
6764         }
6765 
6766         @NonNull
6767         @Override
getDistractingPackageHelper()6768         protected DistractingPackageHelper getDistractingPackageHelper() {
6769             return mDistractingPackageHelper;
6770         }
6771 
6772         @NonNull
6773         @Override
getProtectedPackages()6774         protected ProtectedPackages getProtectedPackages() {
6775             return mProtectedPackages;
6776         }
6777 
6778         @NonNull
6779         @Override
getUserNeedsBadging()6780         protected UserNeedsBadgingCache getUserNeedsBadging() {
6781             return mUserNeedsBadging;
6782         }
6783 
6784         @NonNull
6785         @Override
getInstantAppRegistry()6786         protected InstantAppRegistry getInstantAppRegistry() {
6787             return mInstantAppRegistry;
6788         }
6789 
6790         @NonNull
6791         @Override
getApexManager()6792         protected ApexManager getApexManager() {
6793             return mApexManager;
6794         }
6795 
6796         @NonNull
6797         @Override
getDexManager()6798         protected DexManager getDexManager() {
6799             return mDexManager;
6800         }
6801 
6802         @NonNull
6803         @Override
getDynamicCodeLogger()6804         public DynamicCodeLogger getDynamicCodeLogger() {
6805             return mDynamicCodeLogger;
6806         }
6807 
6808         @Override
isPlatformSigned(String packageName)6809         public boolean isPlatformSigned(String packageName) {
6810             PackageStateInternal packageState = snapshot().getPackageStateInternal(packageName);
6811             if (packageState == null) {
6812                 return false;
6813             }
6814             SigningDetails signingDetails = packageState.getSigningDetails();
6815             return signingDetails.hasAncestorOrSelf(mPlatformPackage.getSigningDetails())
6816                     || mPlatformPackage.getSigningDetails().checkCapability(signingDetails,
6817                     SigningDetails.CertCapabilities.PERMISSION);
6818         }
6819 
6820         @Override
isDataRestoreSafe(byte[] restoringFromSigHash, String packageName)6821         public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
6822             final Computer snapshot = snapshot();
6823             SigningDetails sd = snapshot.getSigningDetails(packageName);
6824             if (sd == null) {
6825                 return false;
6826             }
6827             return sd.hasSha256Certificate(restoringFromSigHash,
6828                     SigningDetails.CertCapabilities.INSTALLED_DATA);
6829         }
6830 
6831         @Override
isDataRestoreSafe(Signature restoringFromSig, String packageName)6832         public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
6833             final Computer snapshot = snapshot();
6834             SigningDetails sd = snapshot.getSigningDetails(packageName);
6835             if (sd == null) {
6836                 return false;
6837             }
6838             return sd.hasCertificate(restoringFromSig,
6839                     SigningDetails.CertCapabilities.INSTALLED_DATA);
6840         }
6841 
6842         @Override
hasSignatureCapability(int serverUid, int clientUid, @SigningDetails.CertCapabilities int capability)6843         public boolean hasSignatureCapability(int serverUid, int clientUid,
6844                 @SigningDetails.CertCapabilities int capability) {
6845             final Computer snapshot = snapshot();
6846             SigningDetails serverSigningDetails = snapshot.getSigningDetails(serverUid);
6847             SigningDetails clientSigningDetails = snapshot.getSigningDetails(clientUid);
6848             return serverSigningDetails.checkCapability(clientSigningDetails, capability)
6849                     || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails);
6850         }
6851 
6852         @Override
getPackageList(@ullable PackageListObserver observer)6853         public PackageList getPackageList(@Nullable PackageListObserver observer) {
6854             final ArrayList<String> list = new ArrayList<>();
6855             PackageManagerService.this.forEachPackageState(snapshot(), packageState -> {
6856                 AndroidPackage pkg = packageState.getPkg();
6857                 if (pkg != null) {
6858                     list.add(pkg.getPackageName());
6859                 }
6860             });
6861             final PackageList packageList = new PackageList(list, observer);
6862             if (observer != null) {
6863                 mPackageObserverHelper.addObserver(packageList);
6864             }
6865             return packageList;
6866         }
6867 
6868         @Override
6869         public @Nullable
getDisabledSystemPackageName(@onNull String packageName)6870         String getDisabledSystemPackageName(@NonNull String packageName) {
6871             PackageStateInternal disabledPkgSetting = snapshot().getDisabledSystemPackage(
6872                     packageName);
6873             AndroidPackage disabledPkg = disabledPkgSetting == null
6874                     ? null : disabledPkgSetting.getPkg();
6875             return disabledPkg == null ? null : disabledPkg.getPackageName();
6876         }
6877 
6878         @Override
isResolveActivityComponent(ComponentInfo component)6879         public boolean isResolveActivityComponent(ComponentInfo component) {
6880             return mResolveActivity.packageName.equals(component.packageName)
6881                     && mResolveActivity.name.equals(component.name);
6882         }
6883 
6884         @Override
getCeDataInode(String packageName, int userId)6885         public long getCeDataInode(String packageName, int userId) {
6886             final PackageStateInternal packageState =
6887                     snapshot().getPackageStateInternal(packageName);
6888             if (packageState == null) {
6889                 return 0;
6890             } else {
6891                 return packageState.getUserStateOrDefault(userId).getCeDataInode();
6892             }
6893         }
6894 
6895         @Override
removeAllNonSystemPackageSuspensions(int userId)6896         public void removeAllNonSystemPackageSuspensions(int userId) {
6897             final Computer computer = snapshotComputer();
6898             final String[] allPackages = computer.getAllAvailablePackageNames();
6899             mSuspendPackageHelper.removeSuspensionsBySuspendingPackage(computer, allPackages,
6900                     (suspender) -> !PLATFORM_PACKAGE_NAME.equals(suspender.packageName),
6901                     userId);
6902         }
6903 
6904         @Override
flushPackageRestrictions(int userId)6905         public void flushPackageRestrictions(int userId) {
6906             synchronized (mLock) {
6907                 PackageManagerService.this.flushPackageRestrictionsAsUserInternalLocked(userId);
6908             }
6909         }
6910 
6911         @Override
setPackagesSuspendedByAdmin( @serIdInt int userId, @NonNull String[] packageNames, boolean suspended)6912         public String[] setPackagesSuspendedByAdmin(
6913                 @UserIdInt int userId, @NonNull String[] packageNames, boolean suspended) {
6914             // Suspension by admin isn't attributed to admin package but to the platform,
6915             // Using USER_SYSTEM for consistency with other internal suspenders, like shell or root.
6916             final int suspendingUserId =
6917                     crossUserSuspensionEnabledRo() ? UserHandle.USER_SYSTEM : userId;
6918             final UserPackage suspender = UserPackage.of(
6919                     suspendingUserId, PackageManagerService.PLATFORM_PACKAGE_NAME);
6920             return mSuspendPackageHelper.setPackagesSuspended(snapshotComputer(), packageNames,
6921                     suspended, null /* appExtras */, null /* launcherExtras */,
6922                     null /* dialogInfo */, suspender, userId, Process.SYSTEM_UID,
6923                     false /* quarantined */);
6924         }
6925 
6926         @Override
setDeviceAndProfileOwnerPackages( int deviceOwnerUserId, String deviceOwnerPackage, SparseArray<String> profileOwnerPackages)6927         public void setDeviceAndProfileOwnerPackages(
6928                 int deviceOwnerUserId, String deviceOwnerPackage,
6929                 SparseArray<String> profileOwnerPackages) {
6930             mProtectedPackages.setDeviceAndProfileOwnerPackages(
6931                     deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
6932             final ArraySet<Integer> usersWithPoOrDo = new ArraySet<>();
6933             if (deviceOwnerPackage != null) {
6934                 usersWithPoOrDo.add(deviceOwnerUserId);
6935             }
6936             final int sz = profileOwnerPackages.size();
6937             for (int i = 0; i < sz; i++) {
6938                 if (profileOwnerPackages.valueAt(i) != null) {
6939                     removeAllNonSystemPackageSuspensions(profileOwnerPackages.keyAt(i));
6940                 }
6941             }
6942         }
6943 
6944         @Override
setExternalSourcesPolicy(ExternalSourcesPolicy policy)6945         public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
6946             if (policy != null) {
6947                 mExternalSourcesPolicy = policy;
6948             }
6949         }
6950 
6951         @Override
isPackagePersistent(String packageName)6952         public boolean isPackagePersistent(String packageName) {
6953             final PackageStateInternal packageState =
6954                     snapshot().getPackageStateInternal(packageName);
6955             if (packageState == null) {
6956                 return false;
6957             }
6958 
6959             AndroidPackage pkg = packageState.getPkg();
6960             return pkg != null && packageState.isSystem() && pkg.isPersistent();
6961         }
6962 
6963         @Override
getOverlayPackages(int userId)6964         public List<PackageInfo> getOverlayPackages(int userId) {
6965             final Computer snapshot = snapshotComputer();
6966             final ArrayList<PackageInfo> overlayPackages = new ArrayList<>();
6967             final ArrayMap<String, ? extends PackageStateInternal> packageStates =
6968                     snapshot.getPackageStates();
6969             for (int index = 0; index < packageStates.size(); index++) {
6970                 final PackageStateInternal packageState = packageStates.valueAt(index);
6971                 final AndroidPackage pkg = packageState.getPkg();
6972                 if (pkg != null && pkg.getOverlayTarget() != null) {
6973                     PackageInfo pkgInfo = snapshot.generatePackageInfo(packageState, 0, userId);
6974                     if (pkgInfo != null) {
6975                         overlayPackages.add(pkgInfo);
6976                     }
6977                 }
6978             }
6979 
6980             return overlayPackages;
6981         }
6982 
6983         @Override
getTargetPackageNames(int userId)6984         public List<String> getTargetPackageNames(int userId) {
6985             List<String> targetPackages = new ArrayList<>();
6986             PackageManagerService.this.forEachPackageState(snapshot(), packageState -> {
6987                 final AndroidPackage pkg = packageState.getPkg();
6988                 if (pkg != null && !pkg.isResourceOverlay()) {
6989                     targetPackages.add(pkg.getPackageName());
6990                 }
6991             });
6992             return targetPackages;
6993         }
6994 
6995         @Override
setEnabledOverlayPackages(int userId, @NonNull ArrayMap<String, OverlayPaths> pendingChanges, @NonNull Set<String> outUpdatedPackageNames, @NonNull Set<String> outInvalidPackageNames)6996         public void setEnabledOverlayPackages(int userId,
6997                 @NonNull ArrayMap<String, OverlayPaths> pendingChanges,
6998                 @NonNull Set<String> outUpdatedPackageNames,
6999                 @NonNull Set<String> outInvalidPackageNames) {
7000             PackageManagerService.this.setEnabledOverlayPackages(userId,
7001                     pendingChanges, outUpdatedPackageNames, outInvalidPackageNames);
7002         }
7003 
7004         @Override
addIsolatedUid(int isolatedUid, int ownerUid)7005         public void addIsolatedUid(int isolatedUid, int ownerUid) {
7006             synchronized (mLock) {
7007                 mIsolatedOwners.put(isolatedUid, ownerUid);
7008             }
7009         }
7010 
7011         @Override
removeIsolatedUid(int isolatedUid)7012         public void removeIsolatedUid(int isolatedUid) {
7013             synchronized (mLock) {
7014                 mIsolatedOwners.delete(isolatedUid);
7015             }
7016         }
7017 
7018         @Override
notifyPackageUse(String packageName, int reason)7019         public void notifyPackageUse(String packageName, int reason) {
7020             PackageManagerService.this.notifyPackageUseInternal(packageName, reason);
7021         }
7022 
7023         @Nullable
7024         @Override
removeLegacyDefaultBrowserPackageName(int userId)7025         public String removeLegacyDefaultBrowserPackageName(int userId) {
7026             synchronized (mLock) {
7027                 return mSettings.removePendingDefaultBrowserLPw(userId);
7028             }
7029         }
7030 
7031         @Override
uninstallApex(String packageName, long versionCode, int userId, IntentSender intentSender, int flags)7032         public void uninstallApex(String packageName, long versionCode, int userId,
7033                 IntentSender intentSender, int flags) {
7034             final int callerUid = Binder.getCallingUid();
7035             if (!PackageManagerServiceUtils.isRootOrShell(callerUid)) {
7036                 throw new SecurityException("Not allowed to uninstall apexes");
7037             }
7038             PackageInstallerService.PackageDeleteObserverAdapter adapter =
7039                     new PackageInstallerService.PackageDeleteObserverAdapter(
7040                             PackageManagerService.this.mContext, intentSender, packageName,
7041                             false, userId);
7042             if ((flags & PackageManager.DELETE_ALL_USERS) == 0) {
7043                 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED,
7044                         "Can't uninstall an apex for a single user");
7045                 return;
7046             }
7047             final ApexManager am = PackageManagerService.this.mApexManager;
7048             PackageInfo activePackage = snapshot().getPackageInfo(
7049                     packageName, PackageManager.MATCH_APEX, UserHandle.USER_SYSTEM);
7050             if (activePackage == null) {
7051                 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED,
7052                         packageName + " is not an apex package");
7053                 return;
7054             }
7055             if (versionCode != PackageManager.VERSION_CODE_HIGHEST
7056                     && activePackage.getLongVersionCode() != versionCode) {
7057                 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED,
7058                         "Active version " + activePackage.getLongVersionCode()
7059                                 + " is not equal to " + versionCode + "]");
7060                 return;
7061             }
7062             if (!am.uninstallApex(activePackage.applicationInfo.sourceDir)) {
7063                 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED,
7064                         "Failed to uninstall apex " + packageName);
7065             } else {
7066                 adapter.onPackageDeleted(packageName, PackageManager.DELETE_SUCCEEDED,
7067                         null);
7068             }
7069         }
7070 
7071         @Override
7072         @SuppressWarnings("GuardedBy")
updateRuntimePermissionsFingerprint(@serIdInt int userId)7073         public void updateRuntimePermissionsFingerprint(@UserIdInt int userId) {
7074             mSettings.updateRuntimePermissionsFingerprint(userId);
7075         }
7076 
7077         @Override
migrateLegacyObbData()7078         public void migrateLegacyObbData() {
7079             try {
7080                 mInstaller.migrateLegacyObbData();
7081             } catch (Exception e) {
7082                 Slog.wtf(TAG, e);
7083             }
7084         }
7085 
7086         @Override
writeSettings(boolean async)7087         public void writeSettings(boolean async) {
7088             synchronized (mLock) {
7089                 if (async) {
7090                     scheduleWriteSettings();
7091                 } else {
7092                     writeSettingsLPrTEMP();
7093                 }
7094             }
7095         }
7096 
7097         @Override
writePermissionSettings(int[] userIds, boolean async)7098         public void writePermissionSettings(int[] userIds, boolean async) {
7099             synchronized (mLock) {
7100                 for (int userId : userIds) {
7101                     mSettings.writePermissionStateForUserLPr(userId, !async);
7102                 }
7103             }
7104         }
7105 
7106         @Override
getLegacyPermissions()7107         public LegacyPermissionSettings getLegacyPermissions() {
7108             synchronized (mLock) {
7109                 return mSettings.mPermissions;
7110             }
7111         }
7112 
7113         /**
7114          * Read legacy permission states for permissions migration to new permission subsystem.
7115          */
7116         @Override
getLegacyPermissionsState(int userId)7117         public RuntimePermissionsState getLegacyPermissionsState(int userId) {
7118             synchronized (mLock) {
7119                 return mSettings.getLegacyPermissionsState(userId);
7120             }
7121         }
7122 
7123         @Override
getLegacyPermissionsVersion(@serIdInt int userId)7124         public int getLegacyPermissionsVersion(@UserIdInt int userId) {
7125             synchronized (mLock) {
7126                 return mSettings.getDefaultRuntimePermissionsVersion(userId);
7127             }
7128         }
7129 
7130         @Override
7131         @SuppressWarnings("GuardedBy")
isPermissionUpgradeNeeded(int userId)7132         public boolean isPermissionUpgradeNeeded(int userId) {
7133             return mSettings.isPermissionUpgradeNeeded(userId);
7134         }
7135 
7136         @Deprecated
7137         @Override
setIntegrityVerificationResult(int verificationId, int verificationResult)7138         public void setIntegrityVerificationResult(int verificationId, int verificationResult) {
7139           // Do nothing.
7140         }
7141 
7142         @Override
setVisibilityLogging(String packageName, boolean enable)7143         public void setVisibilityLogging(String packageName, boolean enable) {
7144             PackageManagerServiceUtils.enforceSystemOrRootOrShell(
7145                     "Only the system or shell can set visibility logging.");
7146             final PackageStateInternal packageState =
7147                     snapshot().getPackageStateInternal(packageName);
7148             if (packageState == null) {
7149                 throw new IllegalStateException("No package found for " + packageName);
7150             }
7151             mAppsFilter.getFeatureConfig().enableLogging(packageState.getAppId(), enable);
7152         }
7153 
7154         @Override
clearBlockUninstallForUser(@serIdInt int userId)7155         public void clearBlockUninstallForUser(@UserIdInt int userId) {
7156             synchronized (mLock) {
7157                 mSettings.clearBlockUninstallLPw(userId);
7158                 mSettings.writePackageRestrictionsLPr(userId);
7159             }
7160         }
7161 
7162         @Override
registerInstalledLoadingProgressCallback(String packageName, PackageManagerInternal.InstalledLoadingProgressCallback callback, int userId)7163         public boolean registerInstalledLoadingProgressCallback(String packageName,
7164                 PackageManagerInternal.InstalledLoadingProgressCallback callback, int userId) {
7165             final Computer snapshot = snapshotComputer();
7166             final PackageStateInternal ps = snapshot.getPackageStateForInstalledAndFiltered(
7167                     packageName, Binder.getCallingUid(), userId);
7168             if (ps == null) {
7169                 return false;
7170             }
7171             if (!ps.isLoading()) {
7172                 Slog.w(TAG,
7173                         "Failed registering loading progress callback. Package is fully loaded.");
7174                 return false;
7175             }
7176             if (mIncrementalManager == null) {
7177                 Slog.w(TAG,
7178                         "Failed registering loading progress callback. Incremental is not enabled");
7179                 return false;
7180             }
7181             return mIncrementalManager.registerLoadingProgressCallback(ps.getPathString(),
7182                     (IPackageLoadingProgressCallback) callback.getBinder());
7183         }
7184 
7185         @Override
getIncrementalStatesInfo( @onNull String packageName, int filterCallingUid, int userId)7186         public IncrementalStatesInfo getIncrementalStatesInfo(
7187                 @NonNull String packageName, int filterCallingUid, int userId) {
7188             final Computer snapshot = snapshotComputer();
7189             final PackageStateInternal ps = snapshot.getPackageStateForInstalledAndFiltered(
7190                     packageName, filterCallingUid, userId);
7191             if (ps == null) {
7192                 return null;
7193             }
7194             return new IncrementalStatesInfo(ps.isLoading(), ps.getLoadingProgress(),
7195                     ps.getLoadingCompletedTime());
7196         }
7197 
7198         @Override
isSameApp(@ullable String packageName, int callingUid, int userId)7199         public boolean isSameApp(@Nullable String packageName, int callingUid, int userId) {
7200             return isSameApp(packageName, /*flags=*/0, callingUid, userId);
7201         }
7202 
7203         @Override
isSameApp(@ullable String packageName, @PackageManager.PackageInfoFlagsBits long flags, int callingUid, int userId)7204         public boolean isSameApp(@Nullable String packageName,
7205                 @PackageManager.PackageInfoFlagsBits long flags, int callingUid, int userId) {
7206             if (packageName == null) {
7207                 return false;
7208             }
7209 
7210             if (Process.isSdkSandboxUid(callingUid)) {
7211                 return packageName.equals(mRequiredSdkSandboxPackage);
7212             }
7213             Computer snapshot = snapshot();
7214             int uid = snapshot.getPackageUid(packageName, flags, userId);
7215             return UserHandle.isSameApp(uid, callingUid);
7216         }
7217 
7218         @Override
onPackageProcessKilledForUninstall(String packageName)7219         public void onPackageProcessKilledForUninstall(String packageName) {
7220             mHandler.post(() -> PackageManagerService.this.notifyInstallObserver(packageName,
7221                     true /* killApp */));
7222         }
7223 
7224         @Override
getDistractingPackageRestrictionsAsUser( @onNull String[] packageNames, int userId)7225         public int[] getDistractingPackageRestrictionsAsUser(
7226                 @NonNull String[] packageNames, int userId) {
7227             final int callingUid = Binder.getCallingUid();
7228             final Computer snapshot = snapshotComputer();
7229             Objects.requireNonNull(packageNames, "packageNames cannot be null");
7230             return mDistractingPackageHelper.getDistractingPackageRestrictionsAsUser(snapshot,
7231                     packageNames, userId, callingUid);
7232         }
7233 
7234         @Override
getHistoricalSessions(int userId)7235         public ParceledListSlice<PackageInstaller.SessionInfo> getHistoricalSessions(int userId) {
7236             return mInstallerService.getHistoricalSessions(userId);
7237         }
7238 
7239         @Override
getPackageArchiver()7240         public PackageArchiver getPackageArchiver() {
7241             return mInstallerService.mPackageArchiver;
7242         }
7243 
7244         @Override
sendPackageRestartedBroadcast(@onNull String packageName, int uid, @Intent.Flags int flags)7245         public void sendPackageRestartedBroadcast(@NonNull String packageName,
7246                 int uid, @Intent.Flags int flags) {
7247             final int userId = UserHandle.getUserId(uid);
7248             final int [] userIds = resolveUserIds(userId);
7249             final SparseArray<int[]> broadcastAllowList =
7250                     snapshotComputer().getVisibilityAllowLists(packageName, userIds);
7251             final Bundle extras = new Bundle();
7252             extras.putInt(Intent.EXTRA_UID, uid);
7253             extras.putInt(Intent.EXTRA_USER_HANDLE, userId);
7254             if (android.content.pm.Flags.stayStopped()) {
7255                 extras.putLong(Intent.EXTRA_TIME, SystemClock.elapsedRealtime());
7256                 // Sent async using the PM handler, to maintain ordering with PACKAGE_UNSTOPPED
7257                 mHandler.post(() -> {
7258                     mBroadcastHelper.sendPackageBroadcast(Intent.ACTION_PACKAGE_RESTARTED,
7259                             packageName, extras, flags, null /* targetPkg */,
7260                             null /* finishedReceiver */, userIds, null /* instantUserIds */,
7261                             broadcastAllowList, null /* filterExtrasForReceiver */,
7262                             null /* bOptions */, null /* requiredPermissions */);
7263                 });
7264             } else {
7265                 mBroadcastHelper.sendPackageBroadcast(Intent.ACTION_PACKAGE_RESTARTED,
7266                         packageName, extras, flags, null /* targetPkg */,
7267                         null /* finishedReceiver */, userIds, null /* instantUserIds */,
7268                         broadcastAllowList, null /* filterExtrasForReceiver */, null /* bOptions */,
7269                         null /* requiredPermissions */);
7270             }
7271             mPackageMonitorCallbackHelper.notifyPackageMonitor(Intent.ACTION_PACKAGE_RESTARTED,
7272                     packageName, extras, userIds, null /* instantUserIds */,
7273                     broadcastAllowList, mHandler, null /* filterExtras */);
7274         }
7275 
7276         @Override
sendPackageDataClearedBroadcast(@onNull String packageName, int uid, int userId, boolean isRestore, boolean isInstantApp)7277         public void sendPackageDataClearedBroadcast(@NonNull String packageName,
7278                 int uid, int userId, boolean isRestore, boolean isInstantApp) {
7279             int[] visibilityAllowList =
7280                     snapshotComputer().getVisibilityAllowList(packageName, userId);
7281             final Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
7282                     Uri.fromParts("package", packageName, null /* fragment */));
7283             intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
7284                     | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7285             intent.putExtra(Intent.EXTRA_UID, uid);
7286             intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
7287             if (isRestore) {
7288                 intent.putExtra(Intent.EXTRA_IS_RESTORE, true);
7289             }
7290             if (isInstantApp) {
7291                 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
7292             }
7293             mBroadcastHelper.sendPackageBroadcastWithIntent(intent, userId, isInstantApp,
7294                     0 /* flags */, visibilityAllowList, null /* finishedReceiver */,
7295                     null /* filterExtrasForReceiver */, null /* bOptions */);
7296             mPackageMonitorCallbackHelper.notifyPackageMonitorWithIntent(intent, userId,
7297                     visibilityAllowList, mHandler);
7298         }
7299 
7300         @Override
isUpgradingFromLowerThan(int sdkVersion)7301         public boolean isUpgradingFromLowerThan(int sdkVersion) {
7302             final boolean isUpgrading = mPriorSdkVersion != -1;
7303             return isUpgrading && mPriorSdkVersion < sdkVersion;
7304         }
7305     }
7306 
setEnabledOverlayPackages(@serIdInt int userId, @NonNull ArrayMap<String, OverlayPaths> pendingChanges, @NonNull Set<String> outUpdatedPackageNames, @NonNull Set<String> outInvalidPackageNames)7307     private void setEnabledOverlayPackages(@UserIdInt int userId,
7308             @NonNull ArrayMap<String, OverlayPaths> pendingChanges,
7309             @NonNull Set<String> outUpdatedPackageNames,
7310             @NonNull Set<String> outInvalidPackageNames) {
7311         final ArrayMap<String, ArrayMap<String, ArraySet<String>>>
7312                 targetPkgToLibNameToModifiedDependents = new ArrayMap<>();
7313         final int numberOfPendingChanges = pendingChanges.size();
7314 
7315         synchronized (mOverlayPathsLock) {
7316             Computer computer = snapshotComputer();
7317             for (int i = 0; i < numberOfPendingChanges; i++) {
7318                 final String targetPackageName = pendingChanges.keyAt(i);
7319                 final OverlayPaths newOverlayPaths = pendingChanges.valueAt(i);
7320                 final PackageStateInternal packageState = computer.getPackageStateInternal(
7321                         targetPackageName);
7322                 final AndroidPackage targetPkg =
7323                         packageState == null ? null : packageState.getPkg();
7324                 if (targetPackageName == null || targetPkg == null) {
7325                     Slog.e(TAG, "failed to find package " + targetPackageName);
7326                     outInvalidPackageNames.add(targetPackageName);
7327                     continue;
7328                 }
7329 
7330                 if (Objects.equals(packageState.getUserStateOrDefault(userId).getOverlayPaths(),
7331                         newOverlayPaths)) {
7332                     continue;
7333                 }
7334 
7335                 if (targetPkg.getLibraryNames() != null) {
7336                     // Set the overlay paths for dependencies of the shared library.
7337                     List<String> libraryNames = targetPkg.getLibraryNames();
7338                     for (int j = 0; j < libraryNames.size(); j++) {
7339                         final String libName = libraryNames.get(j);
7340                         ArraySet<String> modifiedDependents = null;
7341 
7342                         final SharedLibraryInfo info = computer.getSharedLibraryInfo(libName,
7343                                 SharedLibraryInfo.VERSION_UNDEFINED);
7344                         if (info == null) {
7345                             continue;
7346                         }
7347                         var usingSharedLibraryPair = computer.getPackagesUsingSharedLibrary(info, 0,
7348                                 Process.SYSTEM_UID, userId);
7349                         final List<VersionedPackage> dependents = usingSharedLibraryPair.first;
7350                         if (dependents == null) {
7351                             continue;
7352                         }
7353                         for (int k = 0; k < dependents.size(); k++) {
7354                             final VersionedPackage dependent = dependents.get(k);
7355                             final PackageStateInternal dependentState =
7356                                     computer.getPackageStateInternal(dependent.getPackageName());
7357                             if (dependentState == null) {
7358                                 continue;
7359                             }
7360                             if (canSetOverlayPaths(dependentState.getUserStateOrDefault(userId)
7361                                     .getSharedLibraryOverlayPaths()
7362                                     .get(libName), newOverlayPaths)) {
7363                                 String dependentPackageName = dependent.getPackageName();
7364                                 modifiedDependents = ArrayUtils.add(modifiedDependents,
7365                                         dependentPackageName);
7366                                 outUpdatedPackageNames.add(dependentPackageName);
7367                             }
7368                         }
7369 
7370                         if (modifiedDependents != null) {
7371                             ArrayMap<String, ArraySet<String>> libNameToModifiedDependents =
7372                                     targetPkgToLibNameToModifiedDependents.get(
7373                                             targetPackageName);
7374                             if (libNameToModifiedDependents == null) {
7375                                 libNameToModifiedDependents = new ArrayMap<>();
7376                                 targetPkgToLibNameToModifiedDependents.put(targetPackageName,
7377                                         libNameToModifiedDependents);
7378                             }
7379                             libNameToModifiedDependents.put(libName, modifiedDependents);
7380                         }
7381                     }
7382                 }
7383 
7384                 if (canSetOverlayPaths(packageState.getUserStateOrDefault(userId).getOverlayPaths(),
7385                         newOverlayPaths)) {
7386                     outUpdatedPackageNames.add(targetPackageName);
7387                 }
7388             }
7389 
7390             commitPackageStateMutation(null, mutator -> {
7391                 for (int i = 0; i < numberOfPendingChanges; i++) {
7392                     final String targetPackageName = pendingChanges.keyAt(i);
7393                     final OverlayPaths newOverlayPaths = pendingChanges.valueAt(i);
7394 
7395                     if (!outUpdatedPackageNames.contains(targetPackageName)) {
7396                         continue;
7397                     }
7398 
7399                     mutator.forPackage(targetPackageName)
7400                             .userState(userId)
7401                             .setOverlayPaths(newOverlayPaths);
7402 
7403                     final ArrayMap<String, ArraySet<String>> libNameToModifiedDependents =
7404                             targetPkgToLibNameToModifiedDependents.get(
7405                                     targetPackageName);
7406                     if (libNameToModifiedDependents == null) {
7407                         continue;
7408                     }
7409 
7410                     for (int mapIndex = 0; mapIndex < libNameToModifiedDependents.size();
7411                             mapIndex++) {
7412                         String libName = libNameToModifiedDependents.keyAt(mapIndex);
7413                         ArraySet<String> modifiedDependents =
7414                                 libNameToModifiedDependents.valueAt(mapIndex);
7415                         for (int setIndex = 0; setIndex < modifiedDependents.size(); setIndex++) {
7416                             mutator.forPackage(modifiedDependents.valueAt(setIndex))
7417                                     .userState(userId)
7418                                     .setOverlayPathsForLibrary(libName, newOverlayPaths);
7419                         }
7420                     }
7421                 }
7422             });
7423         }
7424 
7425         if (userId == UserHandle.USER_SYSTEM) {
7426             // Keep the overlays in the system application info (and anything special cased as well)
7427             // up to date to make sure system ui is themed correctly.
7428             for (int i = 0; i < numberOfPendingChanges; i++) {
7429                 final String targetPackageName = pendingChanges.keyAt(i);
7430                 final OverlayPaths newOverlayPaths = pendingChanges.valueAt(i);
7431                 maybeUpdateSystemOverlays(targetPackageName, newOverlayPaths);
7432             }
7433         }
7434 
7435         invalidatePackageInfoCache();
7436     }
7437 
canSetOverlayPaths(OverlayPaths origPaths, OverlayPaths newPaths)7438     private boolean canSetOverlayPaths(OverlayPaths origPaths, OverlayPaths newPaths) {
7439         if (Objects.equals(origPaths, newPaths)) {
7440             return false;
7441         }
7442         if ((origPaths == null && newPaths.isEmpty())
7443                 || (newPaths == null && origPaths.isEmpty())) {
7444             return false;
7445         }
7446         return true;
7447     }
7448 
maybeUpdateSystemOverlays(String targetPackageName, OverlayPaths newOverlayPaths)7449     private void maybeUpdateSystemOverlays(String targetPackageName, OverlayPaths newOverlayPaths) {
7450         if (!mResolverReplaced) {
7451             if (targetPackageName.equals("android")) {
7452                 if (newOverlayPaths == null) {
7453                     mPlatformPackageOverlayPaths = null;
7454                     mPlatformPackageOverlayResourceDirs = null;
7455                 } else {
7456                     mPlatformPackageOverlayPaths = newOverlayPaths.getOverlayPaths().toArray(
7457                             new String[0]);
7458                     mPlatformPackageOverlayResourceDirs = newOverlayPaths.getResourceDirs().toArray(
7459                             new String[0]);
7460                 }
7461                 applyUpdatedSystemOverlayPaths();
7462             }
7463         } else {
7464             if (targetPackageName.equals(mResolveActivity.applicationInfo.packageName)) {
7465                 if (newOverlayPaths == null) {
7466                     mReplacedResolverPackageOverlayPaths = null;
7467                     mReplacedResolverPackageOverlayResourceDirs = null;
7468                 } else {
7469                     mReplacedResolverPackageOverlayPaths =
7470                             newOverlayPaths.getOverlayPaths().toArray(new String[0]);
7471                     mReplacedResolverPackageOverlayResourceDirs =
7472                             newOverlayPaths.getResourceDirs().toArray(new String[0]);
7473                 }
7474                 applyUpdatedSystemOverlayPaths();
7475             }
7476         }
7477     }
7478 
applyUpdatedSystemOverlayPaths()7479     private void applyUpdatedSystemOverlayPaths() {
7480         if (mAndroidApplication == null) {
7481             Slog.i(TAG, "Skipped the AndroidApplication overlay paths update - no app yet");
7482         } else {
7483             mAndroidApplication.overlayPaths = mPlatformPackageOverlayPaths;
7484             mAndroidApplication.resourceDirs = mPlatformPackageOverlayResourceDirs;
7485         }
7486         if (mResolverReplaced) {
7487             mResolveActivity.applicationInfo.overlayPaths = mReplacedResolverPackageOverlayPaths;
7488             mResolveActivity.applicationInfo.resourceDirs =
7489                     mReplacedResolverPackageOverlayResourceDirs;
7490         }
7491     }
7492 
enforceAdjustRuntimePermissionsPolicyOrUpgradeRuntimePermissions( @onNull String message)7493     private void enforceAdjustRuntimePermissionsPolicyOrUpgradeRuntimePermissions(
7494             @NonNull String message) {
7495         if (mContext.checkCallingOrSelfPermission(
7496                 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY)
7497                 != PackageManager.PERMISSION_GRANTED
7498                 && mContext.checkCallingOrSelfPermission(
7499                 Manifest.permission.UPGRADE_RUNTIME_PERMISSIONS)
7500                 != PackageManager.PERMISSION_GRANTED) {
7501             throw new SecurityException(message + " requires "
7502                     + Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY + " or "
7503                     + Manifest.permission.UPGRADE_RUNTIME_PERMISSIONS);
7504         }
7505     }
7506 
7507     // TODO: Remove
7508     @Deprecated
7509     @Nullable
7510     @GuardedBy("mLock")
getPackageSettingForMutation(String packageName)7511     PackageSetting getPackageSettingForMutation(String packageName) {
7512         return mSettings.getPackageLPr(packageName);
7513     }
7514 
7515     // TODO: Remove
7516     @Deprecated
7517     @Nullable
7518     @GuardedBy("mLock")
getDisabledPackageSettingForMutation(String packageName)7519     PackageSetting getDisabledPackageSettingForMutation(String packageName) {
7520         return mSettings.getDisabledSystemPkgLPr(packageName);
7521     }
7522 
7523     @Deprecated
forEachPackageSetting(Consumer<PackageSetting> actionLocked)7524     void forEachPackageSetting(Consumer<PackageSetting> actionLocked) {
7525         synchronized (mLock) {
7526             int size = mSettings.getPackagesLocked().size();
7527             for (int index = 0; index < size; index++) {
7528                 actionLocked.accept(mSettings.getPackagesLocked().valueAt(index));
7529             }
7530         }
7531     }
7532 
forEachPackageState(@onNull Computer snapshot, Consumer<PackageStateInternal> consumer)7533     void forEachPackageState(@NonNull Computer snapshot, Consumer<PackageStateInternal> consumer) {
7534         forEachPackageState(snapshot.getPackageStates(), consumer);
7535     }
7536 
forEachPackage(@onNull Computer snapshot, Consumer<AndroidPackage> consumer)7537     void forEachPackage(@NonNull Computer snapshot, Consumer<AndroidPackage> consumer) {
7538         final ArrayMap<String, ? extends PackageStateInternal> packageStates =
7539                 snapshot.getPackageStates();
7540         int size = packageStates.size();
7541         for (int index = 0; index < size; index++) {
7542             PackageStateInternal packageState = packageStates.valueAt(index);
7543             if (packageState.getPkg() != null) {
7544                 consumer.accept(packageState.getPkg());
7545             }
7546         }
7547     }
7548 
forEachPackageInternal(@onNull Computer snapshot, @NonNull Consumer<AndroidPackageInternal> consumer)7549     void forEachPackageInternal(@NonNull Computer snapshot,
7550             @NonNull Consumer<AndroidPackageInternal> consumer) {
7551         final ArrayMap<String, ? extends PackageStateInternal> packageStates =
7552                 snapshot.getPackageStates();
7553         int size = packageStates.size();
7554         for (int index = 0; index < size; index++) {
7555             PackageStateInternal packageState = packageStates.valueAt(index);
7556             if (packageState.getPkg() != null) {
7557                 consumer.accept(packageState.getPkg());
7558             }
7559         }
7560     }
7561 
forEachPackageState( @onNull ArrayMap<String, ? extends PackageStateInternal> packageStates, @NonNull Consumer<PackageStateInternal> consumer)7562     private void forEachPackageState(
7563             @NonNull ArrayMap<String, ? extends PackageStateInternal> packageStates,
7564             @NonNull Consumer<PackageStateInternal> consumer) {
7565         int size = packageStates.size();
7566         for (int index = 0; index < size; index++) {
7567             PackageStateInternal packageState = packageStates.valueAt(index);
7568             consumer.accept(packageState);
7569         }
7570     }
7571 
forEachInstalledPackage(@onNull Computer snapshot, @NonNull Consumer<AndroidPackage> action, @UserIdInt int userId)7572     void forEachInstalledPackage(@NonNull Computer snapshot, @NonNull Consumer<AndroidPackage> action,
7573             @UserIdInt int userId) {
7574         Consumer<PackageStateInternal> actionWrapped = packageState -> {
7575             if (packageState.getPkg() != null
7576                     && packageState.getUserStateOrDefault(userId).isInstalled()) {
7577                 action.accept(packageState.getPkg());
7578             }
7579         };
7580         forEachPackageState(snapshot.getPackageStates(), actionWrapped);
7581     }
7582 
isHistoricalPackageUsageAvailable()7583     boolean isHistoricalPackageUsageAvailable() {
7584         return mPackageUsage.isHistoricalPackageUsageAvailable();
7585     }
7586 
getOrCreateCompilerPackageStats(AndroidPackage pkg)7587     public CompilerStats.PackageStats getOrCreateCompilerPackageStats(AndroidPackage pkg) {
7588         return getOrCreateCompilerPackageStats(pkg.getPackageName());
7589     }
7590 
getOrCreateCompilerPackageStats(String pkgName)7591     public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
7592         return mCompilerStats.getOrCreatePackageStats(pkgName);
7593     }
7594 
grantImplicitAccess(@onNull Computer snapshot, @UserIdInt int userId, Intent intent, @AppIdInt int recipientAppId, int visibleUid, boolean direct, boolean retainOnUpdate)7595     void grantImplicitAccess(@NonNull Computer snapshot, @UserIdInt int userId,
7596             Intent intent, @AppIdInt int recipientAppId, int visibleUid, boolean direct,
7597             boolean retainOnUpdate) {
7598         final AndroidPackage visiblePackage = snapshot.getPackage(visibleUid);
7599         final int recipientUid = UserHandle.getUid(userId, recipientAppId);
7600         if (visiblePackage == null || snapshot.getPackage(recipientUid) == null) {
7601             return;
7602         }
7603 
7604         final boolean instantApp = snapshot.isInstantAppInternal(
7605                 visiblePackage.getPackageName(), userId, visibleUid);
7606         final boolean accessGranted;
7607         if (instantApp) {
7608             if (!direct) {
7609                 // if the interaction that lead to this granting access to an instant app
7610                 // was indirect (i.e.: URI permission grant), do not actually execute the
7611                 // grant.
7612                 return;
7613             }
7614             accessGranted = mInstantAppRegistry.grantInstantAccess(userId, intent,
7615                     recipientAppId, UserHandle.getAppId(visibleUid) /*instantAppId*/);
7616         } else {
7617             accessGranted = mAppsFilter.grantImplicitAccess(recipientUid, visibleUid,
7618                     retainOnUpdate);
7619         }
7620 
7621         if (accessGranted) {
7622             ApplicationPackageManager.invalidateGetPackagesForUidCache();
7623         }
7624     }
7625 
canHaveOatDir(@onNull Computer snapshot, String packageName)7626     boolean canHaveOatDir(@NonNull Computer snapshot, String packageName) {
7627         final PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName);
7628         if (packageState == null || packageState.getPkg() == null) {
7629             return false;
7630         }
7631         return AndroidPackageUtils.canHaveOatDir(packageState, packageState.getPkg());
7632     }
7633 
deleteOatArtifactsOfPackage(@onNull Computer snapshot, String packageName)7634     long deleteOatArtifactsOfPackage(@NonNull Computer snapshot, String packageName) {
7635         PackageManagerServiceUtils.enforceSystemOrRootOrShell(
7636                 "Only the system or shell can delete oat artifacts");
7637 
7638         // TODO(chiuwinson): Retrieve filtered snapshot from Computer instance instead.
7639         try (PackageManagerLocal.FilteredSnapshot filteredSnapshot =
7640                         PackageManagerServiceUtils.getPackageManagerLocal()
7641                                 .withFilteredSnapshot()) {
7642             try {
7643                 DeleteResult res = DexOptHelper.getArtManagerLocal().deleteDexoptArtifacts(
7644                         filteredSnapshot, packageName);
7645                 return res.getFreedBytes();
7646             } catch (IllegalArgumentException e) {
7647                 Log.e(TAG, e.toString());
7648                 return -1;
7649             } catch (IllegalStateException e) {
7650                 Slog.wtfStack(TAG, e.toString());
7651                 return -1;
7652             }
7653         }
7654     }
7655 
getMimeGroupInternal(@onNull Computer snapshot, String packageName, String mimeGroup)7656     List<String> getMimeGroupInternal(@NonNull Computer snapshot, String packageName,
7657             String mimeGroup) {
7658         final PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName);
7659         if (packageState == null) {
7660             return Collections.emptyList();
7661         }
7662 
7663         final Map<String, Set<String>> mimeGroups = packageState.getMimeGroups();
7664         Set<String> mimeTypes = mimeGroups != null ? mimeGroups.get(mimeGroup) : null;
7665         if (mimeTypes == null) {
7666             throw new IllegalArgumentException("Unknown MIME group " + mimeGroup
7667                     + " for package " + packageName);
7668         }
7669         return new ArrayList<>(mimeTypes);
7670     }
7671 
7672     /**
7673      * Temporary method that wraps mSettings.writeLPr() and calls mPermissionManager's
7674      * writeLegacyPermissionsTEMP() beforehand.
7675      *
7676      * TODO: In the meantime, can this be moved to a schedule call?
7677      * TODO(b/182523293): This should be removed once we finish migration of permission storage.
7678      */
7679     @SuppressWarnings("GuardedBy")
writeSettingsLPrTEMP(boolean sync)7680     void writeSettingsLPrTEMP(boolean sync) {
7681         snapshotComputer(false);
7682         mPermissionManager.writeLegacyPermissionsTEMP(mSettings.mPermissions);
7683         mSettings.writeLPr(mLiveComputer, sync);
7684     }
7685 
7686     // Default async version.
writeSettingsLPrTEMP()7687     void writeSettingsLPrTEMP() {
7688         writeSettingsLPrTEMP(/*sync=*/false);
7689     }
7690 
7691     @Override
verifyHoldLockToken(IBinder token)7692     public void verifyHoldLockToken(IBinder token) {
7693         if (!Build.IS_DEBUGGABLE) {
7694             throw new SecurityException("holdLock requires a debuggable build");
7695         }
7696 
7697         if (token == null) {
7698             throw new SecurityException("null holdLockToken");
7699         }
7700 
7701         if (token.queryLocalInterface("holdLock:" + Binder.getCallingUid()) != this) {
7702             throw new SecurityException("Invalid holdLock() token");
7703         }
7704     }
7705 
getDefaultTimeouts()7706     static String getDefaultTimeouts() {
7707         final long token = Binder.clearCallingIdentity();
7708         try {
7709             return DeviceConfig.getString(NAMESPACE_PACKAGE_MANAGER_SERVICE,
7710                     PROPERTY_INCFS_DEFAULT_TIMEOUTS, "");
7711         } finally {
7712             Binder.restoreCallingIdentity(token);
7713         }
7714     }
7715 
getKnownDigestersList()7716     static String getKnownDigestersList() {
7717         final long token = Binder.clearCallingIdentity();
7718         try {
7719             return DeviceConfig.getString(NAMESPACE_PACKAGE_MANAGER_SERVICE,
7720                     PROPERTY_KNOWN_DIGESTERS_LIST, "");
7721         } finally {
7722             Binder.restoreCallingIdentity(token);
7723         }
7724     }
7725 
isPreapprovalRequestAvailable()7726     static boolean isPreapprovalRequestAvailable() {
7727         final long token = Binder.clearCallingIdentity();
7728         try {
7729             if (!Resources.getSystem().getBoolean(
7730                     com.android.internal.R.bool.config_isPreApprovalRequestAvailable)) {
7731                 return false;
7732             }
7733             return DeviceConfig.getBoolean(NAMESPACE_PACKAGE_MANAGER_SERVICE,
7734                     PROPERTY_IS_PRE_APPROVAL_REQUEST_AVAILABLE, true /* defaultValue */);
7735         } finally {
7736             Binder.restoreCallingIdentity(token);
7737         }
7738     }
7739 
isUpdateOwnershipEnforcementAvailable()7740     static boolean isUpdateOwnershipEnforcementAvailable() {
7741         final long token = Binder.clearCallingIdentity();
7742         try {
7743             return DeviceConfig.getBoolean(NAMESPACE_PACKAGE_MANAGER_SERVICE,
7744                     PROPERTY_IS_UPDATE_OWNERSHIP_ENFORCEMENT_AVAILABLE, true /* defaultValue */);
7745         } finally {
7746             Binder.restoreCallingIdentity(token);
7747         }
7748     }
7749 
7750     /**
7751      * Returns the array containing per-uid timeout configuration.
7752      * This is derived from DeviceConfig flags.
7753      */
getPerUidReadTimeouts(@onNull Computer snapshot)7754     public @NonNull PerUidReadTimeouts[] getPerUidReadTimeouts(@NonNull Computer snapshot) {
7755         PerUidReadTimeouts[] result = mPerUidReadTimeoutsCache;
7756         if (result == null) {
7757             result = parsePerUidReadTimeouts(snapshot);
7758             mPerUidReadTimeoutsCache = result;
7759         }
7760         return result;
7761     }
7762 
parsePerUidReadTimeouts(@onNull Computer snapshot)7763     private @NonNull PerUidReadTimeouts[] parsePerUidReadTimeouts(@NonNull Computer snapshot) {
7764         final String defaultTimeouts = getDefaultTimeouts();
7765         final String knownDigestersList = getKnownDigestersList();
7766         final List<PerPackageReadTimeouts> perPackageReadTimeouts =
7767                 PerPackageReadTimeouts.parseDigestersList(defaultTimeouts, knownDigestersList);
7768 
7769         if (perPackageReadTimeouts.size() == 0) {
7770             return EMPTY_PER_UID_READ_TIMEOUTS_ARRAY;
7771         }
7772 
7773         final int[] allUsers = mInjector.getUserManagerService().getUserIds();
7774         final List<PerUidReadTimeouts> result = new ArrayList<>(perPackageReadTimeouts.size());
7775         for (int i = 0, size = perPackageReadTimeouts.size(); i < size; ++i) {
7776             final PerPackageReadTimeouts perPackage = perPackageReadTimeouts.get(i);
7777             final PackageStateInternal ps =
7778                     snapshot.getPackageStateInternal(perPackage.packageName);
7779             if (ps == null) {
7780                 if (DEBUG_PER_UID_READ_TIMEOUTS) {
7781                     Slog.i(TAG, "PerUidReadTimeouts: package not found = "
7782                             + perPackage.packageName);
7783                 }
7784                 continue;
7785             }
7786             if (ps.getAppId() < Process.FIRST_APPLICATION_UID) {
7787                 if (DEBUG_PER_UID_READ_TIMEOUTS) {
7788                     Slog.i(TAG, "PerUidReadTimeouts: package is system, appId="
7789                             + ps.getAppId());
7790                 }
7791                 continue;
7792             }
7793 
7794             final AndroidPackage pkg = ps.getPkg();
7795             if (pkg.getLongVersionCode() < perPackage.versionCodes.minVersionCode
7796                     || pkg.getLongVersionCode() > perPackage.versionCodes.maxVersionCode) {
7797                 if (DEBUG_PER_UID_READ_TIMEOUTS) {
7798                     Slog.i(TAG, "PerUidReadTimeouts: version code is not in range = "
7799                             + perPackage.packageName + ":" + pkg.getLongVersionCode());
7800                 }
7801                 continue;
7802             }
7803             if (perPackage.sha256certificate != null
7804                     && !pkg.getSigningDetails().hasSha256Certificate(
7805                     perPackage.sha256certificate)) {
7806                 if (DEBUG_PER_UID_READ_TIMEOUTS) {
7807                     Slog.i(TAG, "PerUidReadTimeouts: invalid certificate = "
7808                             + perPackage.packageName + ":" + pkg.getLongVersionCode());
7809                 }
7810                 continue;
7811             }
7812             for (int userId : allUsers) {
7813                 if (!ps.getUserStateOrDefault(userId).isInstalled()) {
7814                     continue;
7815                 }
7816                 final int uid = UserHandle.getUid(userId, ps.getAppId());
7817                 final PerUidReadTimeouts perUid = new PerUidReadTimeouts();
7818                 perUid.uid = uid;
7819                 perUid.minTimeUs = perPackage.timeouts.minTimeUs;
7820                 perUid.minPendingTimeUs = perPackage.timeouts.minPendingTimeUs;
7821                 perUid.maxPendingTimeUs = perPackage.timeouts.maxPendingTimeUs;
7822                 result.add(perUid);
7823             }
7824         }
7825         return result.toArray(new PerUidReadTimeouts[result.size()]);
7826     }
7827 
setKeepUninstalledPackagesInternal(@onNull Computer snapshot, List<String> packageList)7828     void setKeepUninstalledPackagesInternal(@NonNull Computer snapshot, List<String> packageList) {
7829         Preconditions.checkNotNull(packageList);
7830         synchronized (mKeepUninstalledPackages) {
7831             List<String> toRemove = new ArrayList<>(mKeepUninstalledPackages);
7832             toRemove.removeAll(packageList); // Do not remove anything still in the list
7833 
7834             mKeepUninstalledPackages.clear();
7835             mKeepUninstalledPackages.addAll(packageList);
7836 
7837             for (int i = 0; i < toRemove.size(); i++) {
7838                 deletePackageIfUnused(snapshot, toRemove.get(i));
7839             }
7840         }
7841     }
7842 
shouldKeepUninstalledPackageLPr(String packageName)7843     boolean shouldKeepUninstalledPackageLPr(String packageName) {
7844         synchronized (mKeepUninstalledPackages) {
7845             return mKeepUninstalledPackages.contains(packageName);
7846         }
7847     }
7848 
getSafeMode()7849     boolean getSafeMode() {
7850         return mSafeMode;
7851     }
7852 
getResolveComponentName()7853     ComponentName getResolveComponentName() {
7854         return mResolveComponentName;
7855     }
7856 
getDefaultAppProvider()7857     DefaultAppProvider getDefaultAppProvider() {
7858         return mDefaultAppProvider;
7859     }
7860 
getCacheDir()7861     File getCacheDir() {
7862         return mCacheDir;
7863     }
7864 
getPackageProperty()7865     PackageProperty getPackageProperty() {
7866         return mPackageProperty;
7867     }
7868 
getInstrumentation()7869     WatchedArrayMap<ComponentName, ParsedInstrumentation> getInstrumentation() {
7870         return mInstrumentation;
7871     }
7872 
getSdkVersion()7873     int getSdkVersion() {
7874         return mSdkVersion;
7875     }
7876 
addAllPackageProperties(@onNull AndroidPackage pkg)7877     void addAllPackageProperties(@NonNull AndroidPackage pkg) {
7878         mPackageProperty.addAllProperties(pkg);
7879     }
7880 
addInstrumentation(ComponentName name, ParsedInstrumentation instrumentation)7881     void addInstrumentation(ComponentName name, ParsedInstrumentation instrumentation) {
7882         mInstrumentation.put(name, instrumentation);
7883     }
7884 
getKnownPackageNamesInternal(@onNull Computer snapshot, int knownPackage, int userId)7885     String[] getKnownPackageNamesInternal(@NonNull Computer snapshot, int knownPackage,
7886             int userId) {
7887         return new KnownPackages(
7888                 mDefaultAppProvider,
7889                 mRequiredInstallerPackage,
7890                 mRequiredUninstallerPackage,
7891                 mSetupWizardPackage,
7892                 mRequiredVerifierPackages,
7893                 mDefaultTextClassifierPackage,
7894                 mSystemTextClassifierPackageName,
7895                 mRequiredPermissionControllerPackage,
7896                 mConfiguratorPackage,
7897                 mIncidentReportApproverPackage,
7898                 mAmbientContextDetectionPackage,
7899                 mWearableSensingPackage,
7900                 mAppPredictionServicePackage,
7901                 COMPANION_PACKAGE_NAME,
7902                 mRetailDemoPackage,
7903                 mOverlayConfigSignaturePackage,
7904                 mRecentsPackage)
7905                 .getKnownPackageNames(snapshot, knownPackage, userId);
7906     }
7907 
getActiveLauncherPackageName(int userId)7908     String getActiveLauncherPackageName(int userId) {
7909         return mDefaultAppProvider.getDefaultHome(userId);
7910     }
7911 
setActiveLauncherPackage(@onNull String packageName, @UserIdInt int userId, @NonNull Consumer<Boolean> callback)7912     boolean setActiveLauncherPackage(@NonNull String packageName, @UserIdInt int userId,
7913             @NonNull Consumer<Boolean> callback) {
7914         return mDefaultAppProvider.setDefaultHome(packageName, userId, mContext.getMainExecutor(),
7915                 callback);
7916     }
7917 
7918     @Nullable
getDefaultBrowser(@serIdInt int userId)7919     String getDefaultBrowser(@UserIdInt int userId) {
7920         return mDefaultAppProvider.getDefaultBrowser(userId);
7921     }
7922 
setDefaultBrowser(@ullable String packageName, @UserIdInt int userId)7923     void setDefaultBrowser(@Nullable String packageName, @UserIdInt int userId) {
7924         mDefaultAppProvider.setDefaultBrowser(packageName, userId);
7925     }
7926 
getPackageUsage()7927     PackageUsage getPackageUsage() {
7928         return mPackageUsage;
7929     }
7930 
getModuleMetadataPackageName()7931     String getModuleMetadataPackageName() {
7932         return mModuleInfoProvider.getPackageName();
7933     }
7934 
getAppInstallDir()7935     File getAppInstallDir() {
7936         return mAppInstallDir;
7937     }
7938 
isExpectingBetter(String packageName)7939     boolean isExpectingBetter(String packageName) {
7940         return mInitAppsHelper.isExpectingBetter(packageName);
7941     }
7942 
getDefParseFlags()7943     int getDefParseFlags() {
7944         return mDefParseFlags;
7945     }
7946 
setUpCustomResolverActivity(AndroidPackage pkg, PackageSetting pkgSetting)7947     void setUpCustomResolverActivity(AndroidPackage pkg, PackageSetting pkgSetting) {
7948         synchronized (mLock) {
7949             mResolverReplaced = true;
7950 
7951             // The instance created in PackageManagerService is special cased to be non-user
7952             // specific, so initialize all the needed fields here.
7953             ApplicationInfo appInfo = PackageInfoUtils.generateApplicationInfo(pkg, 0,
7954                     PackageUserStateInternal.DEFAULT, UserHandle.USER_SYSTEM, pkgSetting);
7955 
7956             // Set up information for custom user intent resolution activity.
7957             mResolveActivity.applicationInfo = appInfo;
7958             mResolveActivity.name = mCustomResolverComponentName.getClassName();
7959             mResolveActivity.packageName = pkg.getPackageName();
7960             mResolveActivity.processName = pkg.getProcessName();
7961             mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7962             mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
7963                     | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS
7964                     | ActivityInfo.FLAG_CAN_DISPLAY_ON_REMOTE_DEVICES
7965                     | ActivityInfo.FLAG_HARDWARE_ACCELERATED;
7966             mResolveActivity.theme = 0;
7967             mResolveActivity.exported = true;
7968             mResolveActivity.enabled = true;
7969             mResolveInfo.activityInfo = mResolveActivity;
7970             mResolveInfo.priority = 0;
7971             mResolveInfo.preferredOrder = 0;
7972             mResolveInfo.match = 0;
7973             mResolveComponentName = mCustomResolverComponentName;
7974             PackageManagerService.onChanged();
7975             Slog.i(TAG, "Replacing default ResolverActivity with custom activity: "
7976                     + mResolveComponentName);
7977         }
7978     }
7979 
setPlatformPackage(AndroidPackage pkg, PackageSetting pkgSetting)7980     void setPlatformPackage(AndroidPackage pkg, PackageSetting pkgSetting) {
7981         synchronized (mLock) {
7982             // Set up information for our fall-back user intent resolution activity.
7983             mPlatformPackage = pkg;
7984 
7985             // The instance stored in PackageManagerService is special cased to be non-user
7986             // specific, so initialize all the needed fields here.
7987             mAndroidApplication = PackageInfoUtils.generateApplicationInfo(pkg, 0,
7988                     PackageUserStateInternal.DEFAULT, UserHandle.USER_SYSTEM, pkgSetting);
7989 
7990             if (!mResolverReplaced) {
7991                 mResolveActivity.applicationInfo = mAndroidApplication;
7992                 mResolveActivity.name = ResolverActivity.class.getName();
7993                 mResolveActivity.packageName = mAndroidApplication.packageName;
7994                 mResolveActivity.processName = "system:ui";
7995                 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7996                 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
7997                 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
7998                         | ActivityInfo.FLAG_RELINQUISH_TASK_IDENTITY
7999                         | ActivityInfo.FLAG_CAN_DISPLAY_ON_REMOTE_DEVICES
8000                         | ActivityInfo.FLAG_HARDWARE_ACCELERATED;
8001                 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
8002                 mResolveActivity.exported = true;
8003                 mResolveActivity.enabled = true;
8004                 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
8005                 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
8006                         | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
8007                         | ActivityInfo.CONFIG_SCREEN_LAYOUT
8008                         | ActivityInfo.CONFIG_ORIENTATION
8009                         | ActivityInfo.CONFIG_KEYBOARD
8010                         | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
8011                 mResolveInfo.activityInfo = mResolveActivity;
8012                 mResolveInfo.priority = 0;
8013                 mResolveInfo.preferredOrder = 0;
8014                 mResolveInfo.match = 0;
8015                 mResolveComponentName = new ComponentName(
8016                         mAndroidApplication.packageName, mResolveActivity.name);
8017             }
8018             PackageManagerService.onChanged();
8019         }
8020         applyUpdatedSystemOverlayPaths();
8021     }
8022 
getCoreAndroidApplication()8023     ApplicationInfo getCoreAndroidApplication() {
8024         return mAndroidApplication;
8025     }
8026 
isSystemReady()8027     boolean isSystemReady() {
8028         return mSystemReady;
8029     }
8030 
getPlatformPackage()8031     AndroidPackage getPlatformPackage() {
8032         return mPlatformPackage;
8033     }
8034 
isPreNMR1Upgrade()8035     boolean isPreNMR1Upgrade() {
8036         return mIsPreNMR1Upgrade;
8037     }
8038 
isOverlayMutable(String packageName)8039     boolean isOverlayMutable(String packageName) {
8040         return mOverlayConfig.isMutable(packageName);
8041     }
8042 
getSystemPackageScanFlags(File codePath)8043     @ScanFlags int getSystemPackageScanFlags(File codePath) {
8044         List<ScanPartition> dirsToScanAsSystem =
8045                 mInitAppsHelper.getDirsToScanAsSystem();
8046         @PackageManagerService.ScanFlags int scanFlags = SCAN_AS_SYSTEM;
8047         for (int i = dirsToScanAsSystem.size() - 1; i >= 0; i--) {
8048             ScanPartition partition = dirsToScanAsSystem.get(i);
8049             if (partition.containsFile(codePath)) {
8050                 scanFlags |= partition.scanFlag;
8051                 if (partition.containsPrivApp(codePath)) {
8052                     scanFlags |= SCAN_AS_PRIVILEGED;
8053                 }
8054                 break;
8055             }
8056         }
8057         return scanFlags;
8058     }
8059 
getSystemPackageRescanFlagsAndReparseFlags(File scanFile, int systemScanFlags, int systemParseFlags)8060     Pair<Integer, Integer> getSystemPackageRescanFlagsAndReparseFlags(File scanFile,
8061             int systemScanFlags, int systemParseFlags) {
8062         List<ScanPartition> dirsToScanAsSystem =
8063                 mInitAppsHelper.getDirsToScanAsSystem();
8064         @ParsingPackageUtils.ParseFlags int reparseFlags = 0;
8065         @PackageManagerService.ScanFlags int rescanFlags = 0;
8066         for (int i1 = dirsToScanAsSystem.size() - 1; i1 >= 0; i1--) {
8067             final ScanPartition partition = dirsToScanAsSystem.get(i1);
8068             if (partition.containsPrivApp(scanFile)) {
8069                 reparseFlags = systemParseFlags;
8070                 rescanFlags = systemScanFlags | SCAN_AS_PRIVILEGED
8071                         | partition.scanFlag;
8072                 break;
8073             }
8074             if (partition.containsApp(scanFile)) {
8075                 reparseFlags = systemParseFlags;
8076                 rescanFlags = systemScanFlags | partition.scanFlag;
8077                 break;
8078             }
8079         }
8080         return new Pair<>(rescanFlags, reparseFlags);
8081     }
8082 
8083 
8084     /**
8085      * @see PackageManagerInternal#recordInitialState()
8086      */
8087     @NonNull
recordInitialState()8088     public PackageStateMutator.InitialState recordInitialState() {
8089         return mPackageStateMutator.initialState(mChangedPackagesTracker.getSequenceNumber());
8090     }
8091 
8092     /**
8093      * @see PackageManagerInternal#commitPackageStateMutation(PackageStateMutator.InitialState,
8094      * Consumer)
8095      */
8096     @NonNull
commitPackageStateMutation( @ullable PackageStateMutator.InitialState initialState, @NonNull Consumer<PackageStateMutator> consumer)8097     public PackageStateMutator.Result commitPackageStateMutation(
8098             @Nullable PackageStateMutator.InitialState initialState,
8099             @NonNull Consumer<PackageStateMutator> consumer) {
8100         synchronized (mPackageStateWriteLock) {
8101             final PackageStateMutator.Result result = mPackageStateMutator.generateResult(
8102                     initialState, mChangedPackagesTracker.getSequenceNumber());
8103             if (result != PackageStateMutator.Result.SUCCESS) {
8104                 return result;
8105             }
8106 
8107             consumer.accept(mPackageStateMutator);
8108             mPackageStateMutator.onFinished();
8109         }
8110 
8111         return PackageStateMutator.Result.SUCCESS;
8112     }
8113 
8114     /**
8115      * @see PackageManagerInternal#commitPackageStateMutation(PackageStateMutator.InitialState,
8116      * Consumer)
8117      */
8118     @NonNull
commitPackageStateMutation( @ullable PackageStateMutator.InitialState initialState, @NonNull String packageName, @NonNull Consumer<PackageStateWrite> consumer)8119     public PackageStateMutator.Result commitPackageStateMutation(
8120             @Nullable PackageStateMutator.InitialState initialState, @NonNull String packageName,
8121             @NonNull Consumer<PackageStateWrite> consumer) {
8122         PackageStateMutator.Result result = null;
8123         if (Thread.holdsLock(mPackageStateWriteLock)) {
8124             // If the thread is already holding the lock, this is likely a retry based on a prior
8125             // failure, and re-calculating whether a state change occurred can be skipped.
8126             result = PackageStateMutator.Result.SUCCESS;
8127         }
8128         synchronized (mPackageStateWriteLock) {
8129             if (result == null) {
8130                 // If the thread wasn't previously holding, this is a first-try commit and so a
8131                 // state change may have happened.
8132                 result = mPackageStateMutator.generateResult(
8133                         initialState, mChangedPackagesTracker.getSequenceNumber());
8134             }
8135             if (result != PackageStateMutator.Result.SUCCESS) {
8136                 return result;
8137             }
8138 
8139             PackageStateWrite state = mPackageStateMutator.forPackage(packageName);
8140             if (state == null) {
8141                 return PackageStateMutator.Result.SPECIFIC_PACKAGE_NULL;
8142             } else {
8143                 consumer.accept(state);
8144             }
8145 
8146             state.onChanged();
8147         }
8148 
8149         return PackageStateMutator.Result.SUCCESS;
8150     }
8151 
notifyInstantAppPackageInstalled(String packageName, int[] newUsers)8152     void notifyInstantAppPackageInstalled(String packageName, int[] newUsers) {
8153         mInstantAppRegistry.onPackageInstalled(snapshotComputer(), packageName, newUsers);
8154     }
8155 
addInstallerPackageName(InstallSource installSource)8156     void addInstallerPackageName(InstallSource installSource) {
8157         synchronized (mLock) {
8158             mSettings.addInstallerPackageNames(installSource);
8159         }
8160     }
8161 
reconcileSdkData(@ullable String volumeUuid, @NonNull String packageName, @NonNull List<String> subDirNames, int userId, int appId, int previousAppId, @NonNull String seInfo, int flags)8162     public void reconcileSdkData(@Nullable String volumeUuid, @NonNull String packageName,
8163             @NonNull List<String> subDirNames, int userId, int appId, int previousAppId,
8164             @NonNull String seInfo, int flags) throws IOException {
8165         ReconcileSdkDataArgs args = mInstaller.buildReconcileSdkDataArgs(volumeUuid,
8166                 packageName, subDirNames, userId, appId, seInfo,
8167                 flags);
8168         args.previousAppId = previousAppId;
8169         try (PackageManagerTracedLock installLock = mInstallLock.acquireLock()) {
8170             mInstaller.reconcileSdkData(args);
8171         } catch (InstallerException e) {
8172             throw new IOException(e.getMessage());
8173         }
8174     }
8175 
removeCodePath(@ullable File codePath)8176     void removeCodePath(@Nullable File codePath) {
8177         mRemovePackageHelper.removeCodePath(codePath);
8178     }
8179 
cleanUpResources(@onNull String packageName, @NonNull File codeFile, @NonNull String[] instructionSets)8180     void cleanUpResources(@NonNull String packageName, @NonNull File codeFile,
8181                           @NonNull String[] instructionSets) {
8182         mRemovePackageHelper.cleanUpResources(packageName, codeFile, instructionSets);
8183     }
8184 
cleanUpForMoveInstall(String volumeUuid, String packageName, String fromCodePath)8185     void cleanUpForMoveInstall(String volumeUuid, String packageName, String fromCodePath) {
8186         mRemovePackageHelper.cleanUpForMoveInstall(volumeUuid, packageName, fromCodePath);
8187     }
8188 
sendPendingBroadcasts(String reasonForTrace, int callingUidForTrace)8189     void sendPendingBroadcasts(String reasonForTrace, int callingUidForTrace) {
8190         mInstallPackageHelper.sendPendingBroadcasts(reasonForTrace, callingUidForTrace);
8191     }
8192 
handlePackagePostInstall(@onNull InstallRequest request, boolean launchedForRestore)8193     void handlePackagePostInstall(@NonNull InstallRequest request, boolean launchedForRestore) {
8194         mInstallPackageHelper.handlePackagePostInstall(request, launchedForRestore);
8195     }
8196 
installExistingPackageAsUser( @ullable String packageName, @UserIdInt int userId, @PackageManager.InstallFlags int installFlags, @PackageManager.InstallReason int installReason, @Nullable List<String> allowlistedRestrictedPermissions, @Nullable IntentSender intentSender)8197     Pair<Integer, IntentSender> installExistingPackageAsUser(
8198             @Nullable String packageName,
8199             @UserIdInt int userId, @PackageManager.InstallFlags int installFlags,
8200             @PackageManager.InstallReason int installReason,
8201             @Nullable List<String> allowlistedRestrictedPermissions,
8202             @Nullable IntentSender intentSender) {
8203         return mInstallPackageHelper.installExistingPackageAsUser(packageName, userId, installFlags,
8204                 installReason, allowlistedRestrictedPermissions, intentSender);
8205     }
initPackageTracedLI(File scanFile, final int parseFlags, int scanFlags)8206     AndroidPackage initPackageTracedLI(File scanFile, final int parseFlags, int scanFlags)
8207             throws PackageManagerException {
8208         return mInstallPackageHelper.initPackageTracedLI(scanFile, parseFlags, scanFlags);
8209     }
8210 
restoreDisabledSystemPackageLIF(@onNull DeletePackageAction action, @NonNull int[] allUserHandles, boolean writeSettings)8211     void restoreDisabledSystemPackageLIF(@NonNull DeletePackageAction action,
8212                                          @NonNull int[] allUserHandles,
8213                                          boolean writeSettings) throws SystemDeleteException {
8214         mInstallPackageHelper.restoreDisabledSystemPackageLIF(
8215                 action, allUserHandles, writeSettings);
8216     }
enableCompressedPackage(@onNull AndroidPackage stubPkg, @NonNull PackageSetting stubPs)8217     boolean enableCompressedPackage(@NonNull AndroidPackage stubPkg,
8218                                     @NonNull PackageSetting stubPs) {
8219         return mInstallPackageHelper.enableCompressedPackage(stubPkg, stubPs);
8220     }
8221 
installPackagesTraced(List<InstallRequest> requests, MoveInfo moveInfo)8222     void installPackagesTraced(List<InstallRequest> requests, MoveInfo moveInfo) {
8223         mInstallPackageHelper.installPackagesTraced(requests, moveInfo);
8224     }
8225 
restoreAndPostInstall(InstallRequest request)8226     void restoreAndPostInstall(InstallRequest request) {
8227         mInstallPackageHelper.restoreAndPostInstall(request);
8228     }
8229 
verifyReplacingVersionCode(@onNull PackageInfoLite pkgLite, long requiredInstalledVersionCode, int installFlags)8230     Pair<Integer, String> verifyReplacingVersionCode(@NonNull PackageInfoLite pkgLite,
8231                                     long requiredInstalledVersionCode,
8232                                     int installFlags) {
8233         return mInstallPackageHelper.verifyReplacingVersionCode(
8234                 pkgLite, requiredInstalledVersionCode, installFlags);
8235     }
8236 
getUidForVerifier(VerifierInfo verifierInfo)8237     int getUidForVerifier(VerifierInfo verifierInfo) {
8238         return mInstallPackageHelper.getUidForVerifier(verifierInfo);
8239     }
8240 
deletePackageX(String packageName, long versionCode, int userId, int deleteFlags, boolean removedBySystem)8241     int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags,
8242                         boolean removedBySystem) {
8243         return mDeletePackageHelper.deletePackageX(packageName,
8244                 PackageManager.VERSION_CODE_HIGHEST, UserHandle.USER_SYSTEM,
8245                 PackageManager.DELETE_ALL_USERS, true /*removedBySystem*/);
8246     }
8247 
isSystemOrPhone(int uid)8248     private static boolean isSystemOrPhone(int uid) {
8249         return UserHandle.isSameApp(uid, Process.SYSTEM_UID)
8250                 || UserHandle.isSameApp(uid, Process.PHONE_UID);
8251     }
8252 }
8253