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