OSDN Git Service

[automerger skipped] Merge "DO NOT MERGE back porting for fixing sysui direct reply...
[android-x86/frameworks-base.git] / services / core / java / com / android / server / pm / PackageManagerService.java
1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package com.android.server.pm;
18
19 import static android.Manifest.permission.DELETE_PACKAGES;
20 import static android.Manifest.permission.INSTALL_PACKAGES;
21 import static android.Manifest.permission.MANAGE_DEVICE_ADMINS;
22 import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS;
23 import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
24 import static android.Manifest.permission.REQUEST_DELETE_PACKAGES;
25 import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS;
26 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
27 import static android.content.Intent.ACTION_MAIN;
28 import static android.content.Intent.CATEGORY_DEFAULT;
29 import static android.content.Intent.CATEGORY_HOME;
30 import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509;
31 import static android.content.pm.PackageManager.CERT_INPUT_SHA256;
32 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
33 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
34 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
35 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
36 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
37 import static android.content.pm.PackageManager.DELETE_KEEP_DATA;
38 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
39 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED;
40 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED;
41 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE;
42 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED;
43 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED;
44 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET;
45 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
46 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
47 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
48 import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID;
49 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
50 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
51 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
52 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
53 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
54 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
55 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
56 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
57 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
58 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
59 import static android.content.pm.PackageManager.INSTALL_INTERNAL;
60 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
61 import static android.content.pm.PackageManager.INSTALL_SUCCEEDED;
62 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
63 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK;
64 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
65 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
66 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
67 import static android.content.pm.PackageManager.MATCH_ALL;
68 import static android.content.pm.PackageManager.MATCH_ANY_USER;
69 import static android.content.pm.PackageManager.MATCH_APEX;
70 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING;
71 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
72 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
73 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
74 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY;
75 import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES;
76 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY;
77 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
78 import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL;
79 import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN;
80 import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
81 import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
82 import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER;
83 import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
84 import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
85 import static android.content.pm.PackageManager.PERMISSION_DENIED;
86 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
87 import static android.content.pm.PackageManager.RESTRICTION_NONE;
88 import static android.content.pm.PackageParser.isApkFile;
89 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER;
90 import static android.os.storage.StorageManager.FLAG_STORAGE_CE;
91 import static android.os.storage.StorageManager.FLAG_STORAGE_DE;
92 import static android.os.storage.StorageManager.FLAG_STORAGE_EXTERNAL;
93
94 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
95 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT;
96 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
97 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
98 import static com.android.server.pm.ComponentResolver.RESOLVE_PRIORITY_SORTER;
99 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
100 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
101 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
102 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
103 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
104 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter;
105 import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures;
106 import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists;
107 import static com.android.server.pm.PackageManagerServiceUtils.decompressFile;
108 import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride;
109 import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo;
110 import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles;
111 import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime;
112 import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo;
113 import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures;
114
115 import android.Manifest;
116 import android.annotation.IntDef;
117 import android.annotation.NonNull;
118 import android.annotation.Nullable;
119 import android.annotation.UserIdInt;
120 import android.app.ActivityManager;
121 import android.app.ActivityManagerInternal;
122 import android.app.AppOpsManager;
123 import android.app.BroadcastOptions;
124 import android.app.IActivityManager;
125 import android.app.ResourcesManager;
126 import android.app.admin.IDevicePolicyManager;
127 import android.app.admin.SecurityLog;
128 import android.app.backup.IBackupManager;
129 import android.content.BroadcastReceiver;
130 import android.content.ComponentName;
131 import android.content.ContentResolver;
132 import android.content.Context;
133 import android.content.IIntentReceiver;
134 import android.content.Intent;
135 import android.content.IntentFilter;
136 import android.content.IntentSender;
137 import android.content.IntentSender.SendIntentException;
138 import android.content.pm.ActivityInfo;
139 import android.content.pm.ApplicationInfo;
140 import android.content.pm.AppsQueryHelper;
141 import android.content.pm.AuxiliaryResolveInfo;
142 import android.content.pm.ChangedPackages;
143 import android.content.pm.ComponentInfo;
144 import android.content.pm.FallbackCategoryProvider;
145 import android.content.pm.FeatureInfo;
146 import android.content.pm.IDexModuleRegisterCallback;
147 import android.content.pm.IOnPermissionsChangeListener;
148 import android.content.pm.IPackageDataObserver;
149 import android.content.pm.IPackageDeleteObserver;
150 import android.content.pm.IPackageDeleteObserver2;
151 import android.content.pm.IPackageInstallObserver2;
152 import android.content.pm.IPackageInstaller;
153 import android.content.pm.IPackageManager;
154 import android.content.pm.IPackageManagerNative;
155 import android.content.pm.IPackageMoveObserver;
156 import android.content.pm.IPackageStatsObserver;
157 import android.content.pm.InstantAppInfo;
158 import android.content.pm.InstantAppRequest;
159 import android.content.pm.InstrumentationInfo;
160 import android.content.pm.IntentFilterVerificationInfo;
161 import android.content.pm.KeySet;
162 import android.content.pm.ModuleInfo;
163 import android.content.pm.PackageBackwardCompatibility;
164 import android.content.pm.PackageInfo;
165 import android.content.pm.PackageInfoLite;
166 import android.content.pm.PackageInstaller;
167 import android.content.pm.PackageList;
168 import android.content.pm.PackageManager;
169 import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
170 import android.content.pm.PackageManager.ModuleInfoFlags;
171 import android.content.pm.PackageManager.PermissionWhitelistFlags;
172 import android.content.pm.PackageManagerInternal;
173 import android.content.pm.PackageManagerInternal.CheckPermissionDelegate;
174 import android.content.pm.PackageManagerInternal.PackageListObserver;
175 import android.content.pm.PackageParser;
176 import android.content.pm.PackageParser.ActivityIntentInfo;
177 import android.content.pm.PackageParser.PackageLite;
178 import android.content.pm.PackageParser.PackageParserException;
179 import android.content.pm.PackageParser.ParseFlags;
180 import android.content.pm.PackageParser.SigningDetails;
181 import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion;
182 import android.content.pm.PackageStats;
183 import android.content.pm.PackageUserState;
184 import android.content.pm.ParceledListSlice;
185 import android.content.pm.PermissionGroupInfo;
186 import android.content.pm.PermissionInfo;
187 import android.content.pm.ProviderInfo;
188 import android.content.pm.ResolveInfo;
189 import android.content.pm.SELinuxUtil;
190 import android.content.pm.ServiceInfo;
191 import android.content.pm.SharedLibraryInfo;
192 import android.content.pm.Signature;
193 import android.content.pm.SuspendDialogInfo;
194 import android.content.pm.UserInfo;
195 import android.content.pm.VerifierDeviceIdentity;
196 import android.content.pm.VerifierInfo;
197 import android.content.pm.VersionedPackage;
198 import android.content.pm.dex.ArtManager;
199 import android.content.pm.dex.DexMetadataHelper;
200 import android.content.pm.dex.IArtManager;
201 import android.content.res.Resources;
202 import android.content.rollback.IRollbackManager;
203 import android.database.ContentObserver;
204 import android.graphics.Bitmap;
205 import android.hardware.display.DisplayManager;
206 import android.net.Uri;
207 import android.os.AsyncTask;
208 import android.os.Binder;
209 import android.os.Build;
210 import android.os.Bundle;
211 import android.os.Debug;
212 import android.os.Environment;
213 import android.os.FileUtils;
214 import android.os.Handler;
215 import android.os.IBinder;
216 import android.os.Looper;
217 import android.os.Message;
218 import android.os.Parcel;
219 import android.os.PatternMatcher;
220 import android.os.PersistableBundle;
221 import android.os.Process;
222 import android.os.RemoteCallbackList;
223 import android.os.RemoteException;
224 import android.os.ResultReceiver;
225 import android.os.SELinux;
226 import android.os.ServiceManager;
227 import android.os.ShellCallback;
228 import android.os.SystemClock;
229 import android.os.SystemProperties;
230 import android.os.Trace;
231 import android.os.UserHandle;
232 import android.os.UserManager;
233 import android.os.UserManagerInternal;
234 import android.os.storage.DiskInfo;
235 import android.os.storage.IStorageManager;
236 import android.os.storage.StorageEventListener;
237 import android.os.storage.StorageManager;
238 import android.os.storage.StorageManagerInternal;
239 import android.os.storage.VolumeInfo;
240 import android.os.storage.VolumeRecord;
241 import android.provider.DeviceConfig;
242 import android.provider.MediaStore;
243 import android.provider.Settings.Global;
244 import android.provider.Settings.Secure;
245 import android.security.KeyStore;
246 import android.security.SystemKeyStore;
247 import android.service.pm.PackageServiceDumpProto;
248 import android.stats.storage.StorageEnums;
249 import android.system.ErrnoException;
250 import android.system.Os;
251 import android.text.TextUtils;
252 import android.text.format.DateUtils;
253 import android.util.ArrayMap;
254 import android.util.ArraySet;
255 import android.util.Base64;
256 import android.util.ByteStringUtils;
257 import android.util.DisplayMetrics;
258 import android.util.EventLog;
259 import android.util.ExceptionUtils;
260 import android.util.IntArray;
261 import android.util.Log;
262 import android.util.LogPrinter;
263 import android.util.LongSparseArray;
264 import android.util.LongSparseLongArray;
265 import android.util.MathUtils;
266 import android.util.PackageUtils;
267 import android.util.Pair;
268 import android.util.PrintStreamPrinter;
269 import android.util.Slog;
270 import android.util.SparseArray;
271 import android.util.SparseBooleanArray;
272 import android.util.SparseIntArray;
273 import android.util.StatsLog;
274 import android.util.TimingsTraceLog;
275 import android.util.Xml;
276 import android.util.jar.StrictJarFile;
277 import android.util.proto.ProtoOutputStream;
278 import android.view.Display;
279
280 import com.android.internal.R;
281 import com.android.internal.annotations.GuardedBy;
282 import com.android.internal.app.ResolverActivity;
283 import com.android.internal.content.NativeLibraryHelper;
284 import com.android.internal.content.PackageHelper;
285 import com.android.internal.logging.MetricsLogger;
286 import com.android.internal.os.SomeArgs;
287 import com.android.internal.os.Zygote;
288 import com.android.internal.telephony.CarrierAppUtils;
289 import com.android.internal.util.ArrayUtils;
290 import com.android.internal.util.ConcurrentUtils;
291 import com.android.internal.util.DumpUtils;
292 import com.android.internal.util.FastXmlSerializer;
293 import com.android.internal.util.IndentingPrintWriter;
294 import com.android.internal.util.IntPair;
295 import com.android.internal.util.Preconditions;
296 import com.android.server.AttributeCache;
297 import com.android.server.DeviceIdleController;
298 import com.android.server.EventLogTags;
299 import com.android.server.FgThread;
300 import com.android.server.LocalServices;
301 import com.android.server.LockGuard;
302 import com.android.server.PackageWatchdog;
303 import com.android.server.ServiceThread;
304 import com.android.server.SystemConfig;
305 import com.android.server.SystemServerInitThreadPool;
306 import com.android.server.Watchdog;
307 import com.android.server.net.NetworkPolicyManagerInternal;
308 import com.android.server.pm.Installer.InstallerException;
309 import com.android.server.pm.Settings.DatabaseVersion;
310 import com.android.server.pm.Settings.VersionInfo;
311 import com.android.server.pm.dex.ArtManagerService;
312 import com.android.server.pm.dex.DexManager;
313 import com.android.server.pm.dex.DexoptOptions;
314 import com.android.server.pm.dex.PackageDexUsage;
315 import com.android.server.pm.dex.ViewCompiler;
316 import com.android.server.pm.permission.BasePermission;
317 import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
318 import com.android.server.pm.permission.PermissionManagerService;
319 import com.android.server.pm.permission.PermissionManagerServiceInternal;
320 import com.android.server.pm.permission.PermissionManagerServiceInternal.PermissionCallback;
321 import com.android.server.pm.permission.PermissionsState;
322 import com.android.server.policy.PermissionPolicyInternal;
323 import com.android.server.security.VerityUtils;
324 import com.android.server.storage.DeviceStorageMonitorInternal;
325 import com.android.server.wm.ActivityTaskManagerInternal;
326
327 import dalvik.system.CloseGuard;
328 import dalvik.system.VMRuntime;
329
330 import libcore.io.IoUtils;
331 import libcore.util.EmptyArray;
332
333 import org.xmlpull.v1.XmlPullParser;
334 import org.xmlpull.v1.XmlPullParserException;
335 import org.xmlpull.v1.XmlSerializer;
336
337 import java.io.BufferedOutputStream;
338 import java.io.ByteArrayInputStream;
339 import java.io.ByteArrayOutputStream;
340 import java.io.File;
341 import java.io.FileDescriptor;
342 import java.io.FileInputStream;
343 import java.io.FileOutputStream;
344 import java.io.FilenameFilter;
345 import java.io.IOException;
346 import java.io.PrintWriter;
347 import java.lang.annotation.Retention;
348 import java.lang.annotation.RetentionPolicy;
349 import java.nio.charset.StandardCharsets;
350 import java.security.DigestException;
351 import java.security.DigestInputStream;
352 import java.security.MessageDigest;
353 import java.security.NoSuchAlgorithmException;
354 import java.security.PublicKey;
355 import java.security.SecureRandom;
356 import java.security.cert.CertificateException;
357 import java.util.ArrayList;
358 import java.util.Arrays;
359 import java.util.Collection;
360 import java.util.Collections;
361 import java.util.Comparator;
362 import java.util.HashMap;
363 import java.util.HashSet;
364 import java.util.Iterator;
365 import java.util.LinkedHashSet;
366 import java.util.List;
367 import java.util.Map;
368 import java.util.Objects;
369 import java.util.Set;
370 import java.util.concurrent.CountDownLatch;
371 import java.util.concurrent.Future;
372 import java.util.concurrent.TimeUnit;
373 import java.util.concurrent.atomic.AtomicBoolean;
374 import java.util.concurrent.atomic.AtomicInteger;
375 import java.util.function.BiConsumer;
376 import java.util.function.Consumer;
377 import java.util.function.Predicate;
378
379 /**
380  * Keep track of all those APKs everywhere.
381  * <p>
382  * Internally there are two important locks:
383  * <ul>
384  * <li>{@link #mPackages} is used to guard all in-memory parsed package details
385  * and other related state. It is a fine-grained lock that should only be held
386  * momentarily, as it's one of the most contended locks in the system.
387  * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose
388  * operations typically involve heavy lifting of application data on disk. Since
389  * {@code installd} is single-threaded, and it's operations can often be slow,
390  * this lock should never be acquired while already holding {@link #mPackages}.
391  * Conversely, it's safe to acquire {@link #mPackages} momentarily while already
392  * holding {@link #mInstallLock}.
393  * </ul>
394  * Many internal methods rely on the caller to hold the appropriate locks, and
395  * this contract is expressed through method name suffixes:
396  * <ul>
397  * <li>fooLI(): the caller must hold {@link #mInstallLock}
398  * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package
399  * being modified must be frozen
400  * <li>fooLPr(): the caller must hold {@link #mPackages} for reading
401  * <li>fooLPw(): the caller must hold {@link #mPackages} for writing
402  * </ul>
403  * <p>
404  * Because this class is very central to the platform's security; please run all
405  * CTS and unit tests whenever making modifications:
406  *
407  * <pre>
408  * $ runtest -c android.content.pm.PackageManagerTests frameworks-core
409  * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases
410  * </pre>
411  */
412 public class PackageManagerService extends IPackageManager.Stub
413         implements PackageSender {
414     static final String TAG = "PackageManager";
415     public static final boolean DEBUG_SETTINGS = false;
416     static final boolean DEBUG_PREFERRED = false;
417     static final boolean DEBUG_UPGRADE = false;
418     static final boolean DEBUG_DOMAIN_VERIFICATION = false;
419     private static final boolean DEBUG_BACKUP = false;
420     public static final boolean DEBUG_INSTALL = false;
421     public static final boolean DEBUG_REMOVE = false;
422     private static final boolean DEBUG_BROADCASTS = false;
423     private static final boolean DEBUG_PACKAGE_INFO = false;
424     private static final boolean DEBUG_INTENT_MATCHING = false;
425     public static final boolean DEBUG_PACKAGE_SCANNING = false;
426     private static final boolean DEBUG_VERIFY = false;
427     public static final boolean DEBUG_PERMISSIONS = false;
428     private static final boolean DEBUG_SHARED_LIBRARIES = false;
429     public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE;
430
431     // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService
432     // and PackageDexOptimizer. All these classes have their own flag to allow switching a single
433     // user, but by default initialize to this.
434     public static final boolean DEBUG_DEXOPT = false;
435
436     private static final boolean DEBUG_ABI_SELECTION = false;
437     private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE;
438     private static final boolean DEBUG_APP_DATA = false;
439
440     /** REMOVE. According to Svet, this was only used to reset permissions during development. */
441     static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false;
442
443     private static final boolean HIDE_EPHEMERAL_APIS = false;
444
445     private static final boolean ENABLE_FREE_CACHE_V2 =
446             SystemProperties.getBoolean("fw.free_cache_v2", true);
447
448     private static final String PRECOMPILE_LAYOUTS = "pm.precompile_layouts";
449
450     private static final int RADIO_UID = Process.PHONE_UID;
451     private static final int LOG_UID = Process.LOG_UID;
452     private static final int NFC_UID = Process.NFC_UID;
453     private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
454     private static final int SHELL_UID = Process.SHELL_UID;
455     private static final int SE_UID = Process.SE_UID;
456     private static final int NETWORKSTACK_UID = Process.NETWORK_STACK_UID;
457
458     static final int SCAN_NO_DEX = 1 << 0;
459     static final int SCAN_UPDATE_SIGNATURE = 1 << 1;
460     static final int SCAN_NEW_INSTALL = 1 << 2;
461     static final int SCAN_UPDATE_TIME = 1 << 3;
462     static final int SCAN_BOOTING = 1 << 4;
463     static final int SCAN_REQUIRE_KNOWN = 1 << 7;
464     static final int SCAN_MOVE = 1 << 8;
465     static final int SCAN_INITIAL = 1 << 9;
466     static final int SCAN_CHECK_ONLY = 1 << 10;
467     static final int SCAN_DONT_KILL_APP = 1 << 11;
468     static final int SCAN_IGNORE_FROZEN = 1 << 12;
469     static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1 << 13;
470     static final int SCAN_AS_INSTANT_APP = 1 << 14;
471     static final int SCAN_AS_FULL_APP = 1 << 15;
472     static final int SCAN_AS_VIRTUAL_PRELOAD = 1 << 16;
473     static final int SCAN_AS_SYSTEM = 1 << 17;
474     static final int SCAN_AS_PRIVILEGED = 1 << 18;
475     static final int SCAN_AS_OEM = 1 << 19;
476     static final int SCAN_AS_VENDOR = 1 << 20;
477     static final int SCAN_AS_PRODUCT = 1 << 21;
478     static final int SCAN_AS_PRODUCT_SERVICES = 1 << 22;
479     static final int SCAN_AS_ODM = 1 << 23;
480
481     @IntDef(flag = true, prefix = { "SCAN_" }, value = {
482             SCAN_NO_DEX,
483             SCAN_UPDATE_SIGNATURE,
484             SCAN_NEW_INSTALL,
485             SCAN_UPDATE_TIME,
486             SCAN_BOOTING,
487             SCAN_REQUIRE_KNOWN,
488             SCAN_MOVE,
489             SCAN_INITIAL,
490             SCAN_CHECK_ONLY,
491             SCAN_DONT_KILL_APP,
492             SCAN_IGNORE_FROZEN,
493             SCAN_FIRST_BOOT_OR_UPGRADE,
494             SCAN_AS_INSTANT_APP,
495             SCAN_AS_FULL_APP,
496             SCAN_AS_VIRTUAL_PRELOAD,
497     })
498     @Retention(RetentionPolicy.SOURCE)
499     public @interface ScanFlags {}
500
501     private static final String STATIC_SHARED_LIB_DELIMITER = "_";
502     /** Extension of the compressed packages */
503     public final static String COMPRESSED_EXTENSION = ".gz";
504     /** Suffix of stub packages on the system partition */
505     public final static String STUB_SUFFIX = "-Stub";
506
507     private static final int[] EMPTY_INT_ARRAY = new int[0];
508
509     private static final int TYPE_UNKNOWN = 0;
510     private static final int TYPE_ACTIVITY = 1;
511     private static final int TYPE_RECEIVER = 2;
512     private static final int TYPE_SERVICE = 3;
513     private static final int TYPE_PROVIDER = 4;
514     @IntDef(prefix = { "TYPE_" }, value = {
515             TYPE_UNKNOWN,
516             TYPE_ACTIVITY,
517             TYPE_RECEIVER,
518             TYPE_SERVICE,
519             TYPE_PROVIDER,
520     })
521     @Retention(RetentionPolicy.SOURCE)
522     public @interface ComponentType {}
523
524     /**
525      * Timeout (in milliseconds) after which the watchdog should declare that
526      * our handler thread is wedged.  The usual default for such things is one
527      * minute but we sometimes do very lengthy I/O operations on this thread,
528      * such as installing multi-gigabyte applications, so ours needs to be longer.
529      */
530     static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
531
532     /**
533      * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
534      * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
535      * settings entry if available, otherwise we use the hardcoded default.  If it's been
536      * more than this long since the last fstrim, we force one during the boot sequence.
537      *
538      * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
539      * one gets run at the next available charging+idle time.  This final mandatory
540      * no-fstrim check kicks in only of the other scheduling criteria is never met.
541      */
542     private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
543
544     /**
545      * Whether verification is enabled by default.
546      */
547     private static final boolean DEFAULT_VERIFY_ENABLE = true;
548
549     /**
550      * The default maximum time to wait for the verification agent to return in
551      * milliseconds.
552      */
553     private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
554
555     /**
556      * Timeout duration in milliseconds for enabling package rollback. If we fail to enable
557      * rollback within that period, the install will proceed without rollback enabled.
558      *
559      * <p>If flag value is negative, the default value will be assigned.
560      *
561      * Flag type: {@code long}
562      * Namespace: NAMESPACE_ROLLBACK
563      */
564     private static final String PROPERTY_ENABLE_ROLLBACK_TIMEOUT_MILLIS = "enable_rollback_timeout";
565
566     /**
567      * The default duration to wait for rollback to be enabled in
568      * milliseconds.
569      */
570     private static final long DEFAULT_ENABLE_ROLLBACK_TIMEOUT_MILLIS = 10 * 1000;
571
572     /**
573      * The default response for package verification timeout.
574      *
575      * This can be either PackageManager.VERIFICATION_ALLOW or
576      * PackageManager.VERIFICATION_REJECT.
577      */
578     private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
579
580     public static final String PLATFORM_PACKAGE_NAME = "android";
581
582     private static final String KILL_APP_REASON_GIDS_CHANGED =
583             "permission grant or revoke changed gids";
584
585     private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
586             "permissions revoked";
587
588     private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
589
590     private static final String PACKAGE_SCHEME = "package";
591
592     private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
593
594     private static final String PRODUCT_OVERLAY_DIR = "/product/overlay";
595
596     private static final String PRODUCT_SERVICES_OVERLAY_DIR = "/product_services/overlay";
597
598     private static final String ODM_OVERLAY_DIR = "/odm/overlay";
599
600     private static final String OEM_OVERLAY_DIR = "/oem/overlay";
601
602     /** Canonical intent used to identify what counts as a "web browser" app */
603     private static final Intent sBrowserIntent;
604     static {
605         sBrowserIntent = new Intent();
606         sBrowserIntent.setAction(Intent.ACTION_VIEW);
607         sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE);
608         sBrowserIntent.setData(Uri.parse("http:"));
609         sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL);
610     }
611
612     // Compilation reasons.
613     public static final int REASON_UNKNOWN = -1;
614     public static final int REASON_FIRST_BOOT = 0;
615     public static final int REASON_BOOT = 1;
616     public static final int REASON_INSTALL = 2;
617     public static final int REASON_BACKGROUND_DEXOPT = 3;
618     public static final int REASON_AB_OTA = 4;
619     public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5;
620     public static final int REASON_SHARED = 6;
621
622     public static final int REASON_LAST = REASON_SHARED;
623
624     /**
625      * Whether the package parser cache is enabled.
626      */
627     private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true;
628
629     /**
630      * Permissions required in order to receive instant application lifecycle broadcasts.
631      */
632     private static final String[] INSTANT_APP_BROADCAST_PERMISSION =
633             new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS };
634
635     final ServiceThread mHandlerThread;
636
637     final PackageHandler mHandler;
638
639     private final ProcessLoggingHandler mProcessLoggingHandler;
640
641     final int mSdkVersion = Build.VERSION.SDK_INT;
642
643     final Context mContext;
644     final boolean mFactoryTest;
645     final boolean mOnlyCore;
646     final DisplayMetrics mMetrics;
647     final int mDefParseFlags;
648     final String[] mSeparateProcesses;
649     final boolean mIsUpgrade;
650     final boolean mIsPreNUpgrade;
651     final boolean mIsPreNMR1Upgrade;
652     final boolean mIsPreQUpgrade;
653
654     @GuardedBy("mPackages")
655     private boolean mDexOptDialogShown;
656
657     // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
658     // LOCK HELD.  Can be called with mInstallLock held.
659     @GuardedBy("mInstallLock")
660     final Installer mInstaller;
661
662     /** Directory where installed applications are stored */
663     private static final File sAppInstallDir =
664             new File(Environment.getDataDirectory(), "app");
665     /** Directory where installed application's 32-bit native libraries are copied. */
666     private static final File sAppLib32InstallDir =
667             new File(Environment.getDataDirectory(), "app-lib");
668
669     // ----------------------------------------------------------------
670
671     // Lock for state used when installing and doing other long running
672     // operations.  Methods that must be called with this lock held have
673     // the suffix "LI".
674     final Object mInstallLock = new Object();
675
676     // ----------------------------------------------------------------
677
678     // Keys are String (package name), values are Package.  This also serves
679     // as the lock for the global state.  Methods that must be called with
680     // this lock held have the prefix "LP".
681     @GuardedBy("mPackages")
682     final ArrayMap<String, PackageParser.Package> mPackages = new ArrayMap<>();
683
684     // Keys are isolated uids and values are the uid of the application
685     // that created the isolated proccess.
686     @GuardedBy("mPackages")
687     final SparseIntArray mIsolatedOwners = new SparseIntArray();
688
689     /**
690      * Tracks new system packages [received in an OTA] that we expect to
691      * find updated user-installed versions. Keys are package name, values
692      * are package location.
693      */
694     final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>();
695
696     /**
697      * Tracks existing system packages prior to receiving an OTA. Keys are package name.
698      */
699     final private ArraySet<String> mExistingSystemPackages = new ArraySet<>();
700     /**
701      * Whether or not system app permissions should be promoted from install to runtime.
702      */
703     boolean mPromoteSystemApps;
704
705     @GuardedBy("mPackages")
706     final Settings mSettings;
707
708     /**
709      * Set of package names that are currently "frozen", which means active
710      * surgery is being done on the code/data for that package. The platform
711      * will refuse to launch frozen packages to avoid race conditions.
712      *
713      * @see PackageFreezer
714      */
715     @GuardedBy("mPackages")
716     final ArraySet<String> mFrozenPackages = new ArraySet<>();
717
718     final ProtectedPackages mProtectedPackages;
719
720     @GuardedBy("mLoadedVolumes")
721     final ArraySet<String> mLoadedVolumes = new ArraySet<>();
722
723     boolean mFirstBoot;
724
725     PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy;
726
727     @GuardedBy("mAvailableFeatures")
728     final ArrayMap<String, FeatureInfo> mAvailableFeatures;
729
730     private final InstantAppRegistry mInstantAppRegistry;
731
732     @GuardedBy("mPackages")
733     int mChangedPackagesSequenceNumber;
734     /**
735      * List of changed [installed, removed or updated] packages.
736      * mapping from user id -> sequence number -> package name
737      */
738     @GuardedBy("mPackages")
739     final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>();
740     /**
741      * The sequence number of the last change to a package.
742      * mapping from user id -> package name -> sequence number
743      */
744     @GuardedBy("mPackages")
745     final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>();
746
747     @GuardedBy("mPackages")
748     final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
749
750     @GuardedBy("mPackages")
751     private final SparseIntArray mDefaultPermissionsGrantedUsers = new SparseIntArray();
752
753     private final ModuleInfoProvider mModuleInfoProvider;
754
755     private final ApexManager mApexManager;
756
757     class PackageParserCallback implements PackageParser.Callback {
758         @Override public final boolean hasFeature(String feature) {
759             return PackageManagerService.this.hasSystemFeature(feature, 0);
760         }
761
762         final List<PackageParser.Package> getStaticOverlayPackages(
763                 Collection<PackageParser.Package> allPackages, String targetPackageName) {
764             if ("android".equals(targetPackageName)) {
765                 // Static RROs targeting to "android", ie framework-res.apk, are already applied by
766                 // native AssetManager.
767                 return null;
768             }
769
770             List<PackageParser.Package> overlayPackages = null;
771             for (PackageParser.Package p : allPackages) {
772                 if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) {
773                     if (overlayPackages == null) {
774                         overlayPackages = new ArrayList<>();
775                     }
776                     overlayPackages.add(p);
777                 }
778             }
779             if (overlayPackages != null) {
780                 Comparator<PackageParser.Package> cmp =
781                         Comparator.comparingInt(p -> p.mOverlayPriority);
782                 overlayPackages.sort(cmp);
783             }
784             return overlayPackages;
785         }
786
787         final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages,
788                 String targetPath) {
789             if (overlayPackages == null || overlayPackages.isEmpty()) {
790                 return null;
791             }
792             List<String> overlayPathList = null;
793             for (PackageParser.Package overlayPackage : overlayPackages) {
794                 if (targetPath == null) {
795                     if (overlayPathList == null) {
796                         overlayPathList = new ArrayList<>();
797                     }
798                     overlayPathList.add(overlayPackage.baseCodePath);
799                     continue;
800                 }
801
802                 try {
803                     // Creates idmaps for system to parse correctly the Android manifest of the
804                     // target package.
805                     //
806                     // OverlayManagerService will update each of them with a correct gid from its
807                     // target package app id.
808                     mInstaller.idmap(targetPath, overlayPackage.baseCodePath,
809                             UserHandle.getSharedAppGid(
810                                     UserHandle.getUserGid(UserHandle.USER_SYSTEM)));
811                     if (overlayPathList == null) {
812                         overlayPathList = new ArrayList<>();
813                     }
814                     overlayPathList.add(overlayPackage.baseCodePath);
815                 } catch (InstallerException e) {
816                     Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " +
817                             overlayPackage.baseCodePath);
818                 }
819             }
820             return overlayPathList == null ? null : overlayPathList.toArray(new String[0]);
821         }
822
823         String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
824             List<PackageParser.Package> overlayPackages;
825             synchronized (mInstallLock) {
826                 synchronized (mPackages) {
827                     overlayPackages = getStaticOverlayPackages(
828                             mPackages.values(), targetPackageName);
829                 }
830                 // It is safe to keep overlayPackages without holding mPackages because static overlay
831                 // packages can't be uninstalled or disabled.
832                 return getStaticOverlayPaths(overlayPackages, targetPath);
833             }
834         }
835
836         @Override public final String[] getOverlayApks(String targetPackageName) {
837             return getStaticOverlayPaths(targetPackageName, null);
838         }
839
840         @Override public final String[] getOverlayPaths(String targetPackageName,
841                 String targetPath) {
842             return getStaticOverlayPaths(targetPackageName, targetPath);
843         }
844     }
845
846     class ParallelPackageParserCallback extends PackageParserCallback {
847         List<PackageParser.Package> mOverlayPackages = null;
848
849         void findStaticOverlayPackages() {
850             synchronized (mPackages) {
851                 for (PackageParser.Package p : mPackages.values()) {
852                     if (p.mOverlayIsStatic) {
853                         if (mOverlayPackages == null) {
854                             mOverlayPackages = new ArrayList<>();
855                         }
856                         mOverlayPackages.add(p);
857                     }
858                 }
859             }
860         }
861
862         @Override
863         synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) {
864             // We can trust mOverlayPackages without holding mPackages because package uninstall
865             // can't happen while running parallel parsing.
866             // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock
867             // because mInstallLock is held before running parallel parsing.
868             // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock.
869             return mOverlayPackages == null ? null :
870                     getStaticOverlayPaths(
871                             getStaticOverlayPackages(mOverlayPackages, targetPackageName),
872                             targetPath);
873         }
874     }
875
876     final PackageParser.Callback mPackageParserCallback = new PackageParserCallback();
877     final ParallelPackageParserCallback mParallelPackageParserCallback =
878             new ParallelPackageParserCallback();
879
880     // Currently known shared libraries.
881     final ArrayMap<String, LongSparseArray<SharedLibraryInfo>> mSharedLibraries = new ArrayMap<>();
882     final ArrayMap<String, LongSparseArray<SharedLibraryInfo>> mStaticLibsByDeclaringPackage =
883             new ArrayMap<>();
884
885     // Mapping from instrumentation class names to info about them.
886     final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
887             new ArrayMap<>();
888
889     // Packages whose data we have transfered into another package, thus
890     // should no longer exist.
891     final ArraySet<String> mTransferedPackages = new ArraySet<>();
892
893     // Broadcast actions that are only available to the system.
894     @GuardedBy("mProtectedBroadcasts")
895     final ArraySet<String> mProtectedBroadcasts = new ArraySet<>();
896
897     /** List of packages waiting for verification. */
898     final SparseArray<PackageVerificationState> mPendingVerification = new SparseArray<>();
899
900     /** List of packages waiting for rollback to be enabled. */
901     final SparseArray<InstallParams> mPendingEnableRollback = new SparseArray<>();
902
903     final PackageInstallerService mInstallerService;
904
905     final ArtManagerService mArtManagerService;
906
907     private final PackageDexOptimizer mPackageDexOptimizer;
908     // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package
909     // is used by other apps).
910     private final DexManager mDexManager;
911
912     private final ViewCompiler mViewCompiler;
913
914     private AtomicInteger mNextMoveId = new AtomicInteger();
915     private final MoveCallbacks mMoveCallbacks;
916
917     private final OnPermissionChangeListeners mOnPermissionChangeListeners;
918
919     // Cache of users who need badging.
920     private final SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
921
922     /** Token for keys in mPendingVerification. */
923     private int mPendingVerificationToken = 0;
924
925     /** Token for keys in mPendingEnableRollback. */
926     private int mPendingEnableRollbackToken = 0;
927
928     volatile boolean mSystemReady;
929     volatile boolean mSafeMode;
930     volatile boolean mHasSystemUidErrors;
931     private volatile SparseBooleanArray mWebInstantAppsDisabled = new SparseBooleanArray();
932
933     ApplicationInfo mAndroidApplication;
934     final ActivityInfo mResolveActivity = new ActivityInfo();
935     final ResolveInfo mResolveInfo = new ResolveInfo();
936     ComponentName mResolveComponentName;
937     PackageParser.Package mPlatformPackage;
938     ComponentName mCustomResolverComponentName;
939
940     boolean mResolverReplaced = false;
941
942     private final @Nullable ComponentName mIntentFilterVerifierComponent;
943     private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier;
944
945     private int mIntentFilterVerificationToken = 0;
946
947     /** The service connection to the ephemeral resolver */
948     final InstantAppResolverConnection mInstantAppResolverConnection;
949     /** Component used to show resolver settings for Instant Apps */
950     final ComponentName mInstantAppResolverSettingsComponent;
951
952     /** Activity used to install instant applications */
953     ActivityInfo mInstantAppInstallerActivity;
954     final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo();
955
956     private final Map<String, Pair<PackageInstalledInfo, IPackageInstallObserver2>>
957             mNoKillInstallObservers = Collections.synchronizedMap(new HashMap<>());
958
959     final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
960             = new SparseArray<>();
961
962     // TODO remove this and go through mPermissonManager directly
963     final DefaultPermissionGrantPolicy mDefaultPermissionPolicy;
964     private final PermissionManagerServiceInternal mPermissionManager;
965
966     private final ComponentResolver mComponentResolver;
967     // List of packages names to keep cached, even if they are uninstalled for all users
968     private List<String> mKeepUninstalledPackages;
969
970     private UserManagerInternal mUserManagerInternal;
971     private ActivityManagerInternal mActivityManagerInternal;
972     private ActivityTaskManagerInternal mActivityTaskManagerInternal;
973     private StorageManagerInternal mStorageManagerInternal;
974
975     private DeviceIdleController.LocalService mDeviceIdleController;
976
977     private File mCacheDir;
978
979     private Future<?> mPrepareAppDataFuture;
980
981     private static class IFVerificationParams {
982         PackageParser.Package pkg;
983         boolean replacing;
984         int userId;
985         int verifierUid;
986
987         public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing,
988                 int _userId, int _verifierUid) {
989             pkg = _pkg;
990             replacing = _replacing;
991             userId = _userId;
992             verifierUid = _verifierUid;
993         }
994     }
995
996     private interface IntentFilterVerifier<T extends IntentFilter> {
997         boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
998                                                T filter, String packageName);
999         void startVerifications(int userId);
1000         void receiveVerificationResponse(int verificationId);
1001     }
1002
1003     @GuardedBy("mPackages")
1004     private CheckPermissionDelegate mCheckPermissionDelegate;
1005
1006     @GuardedBy("mPackages")
1007     private PackageManagerInternal.DefaultBrowserProvider mDefaultBrowserProvider;
1008
1009     @GuardedBy("mPackages")
1010     private PackageManagerInternal.DefaultDialerProvider mDefaultDialerProvider;
1011
1012     @GuardedBy("mPackages")
1013     private PackageManagerInternal.DefaultHomeProvider mDefaultHomeProvider;
1014
1015     private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
1016         private Context mContext;
1017         private ComponentName mIntentFilterVerifierComponent;
1018         private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<>();
1019
1020         public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
1021             mContext = context;
1022             mIntentFilterVerifierComponent = verifierComponent;
1023         }
1024
1025         private String getDefaultScheme() {
1026             return IntentFilter.SCHEME_HTTPS;
1027         }
1028
1029         @Override
1030         public void startVerifications(int userId) {
1031             // Launch verifications requests
1032             int count = mCurrentIntentFilterVerifications.size();
1033             for (int n=0; n<count; n++) {
1034                 int verificationId = mCurrentIntentFilterVerifications.get(n);
1035                 final IntentFilterVerificationState ivs =
1036                         mIntentFilterVerificationStates.get(verificationId);
1037
1038                 String packageName = ivs.getPackageName();
1039
1040                 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1041                 final int filterCount = filters.size();
1042                 ArraySet<String> domainsSet = new ArraySet<>();
1043                 for (int m=0; m<filterCount; m++) {
1044                     PackageParser.ActivityIntentInfo filter = filters.get(m);
1045                     domainsSet.addAll(filter.getHostsList());
1046                 }
1047                 synchronized (mPackages) {
1048                     if (mSettings.createIntentFilterVerificationIfNeededLPw(
1049                             packageName, domainsSet) != null) {
1050                         scheduleWriteSettingsLocked();
1051                     }
1052                 }
1053                 sendVerificationRequest(verificationId, ivs);
1054             }
1055             mCurrentIntentFilterVerifications.clear();
1056         }
1057
1058         private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) {
1059             Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
1060             verificationIntent.putExtra(
1061                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
1062                     verificationId);
1063             verificationIntent.putExtra(
1064                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
1065                     getDefaultScheme());
1066             verificationIntent.putExtra(
1067                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
1068                     ivs.getHostsString());
1069             verificationIntent.putExtra(
1070                     PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
1071                     ivs.getPackageName());
1072             verificationIntent.setComponent(mIntentFilterVerifierComponent);
1073             verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1074
1075             final long whitelistTimeout = getVerificationTimeout();
1076             final BroadcastOptions options = BroadcastOptions.makeBasic();
1077             options.setTemporaryAppWhitelistDuration(whitelistTimeout);
1078
1079             DeviceIdleController.LocalService idleController = getDeviceIdleController();
1080             idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
1081                     mIntentFilterVerifierComponent.getPackageName(), whitelistTimeout,
1082                     UserHandle.USER_SYSTEM, true, "intent filter verifier");
1083
1084             mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM,
1085                     null, options.toBundle());
1086             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1087                     "Sending IntentFilter verification broadcast");
1088         }
1089
1090         public void receiveVerificationResponse(int verificationId) {
1091             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1092
1093             final boolean verified = ivs.isVerified();
1094
1095             ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
1096             final int count = filters.size();
1097             if (DEBUG_DOMAIN_VERIFICATION) {
1098                 Slog.i(TAG, "Received verification response " + verificationId
1099                         + " for " + count + " filters, verified=" + verified);
1100             }
1101             for (int n=0; n<count; n++) {
1102                 PackageParser.ActivityIntentInfo filter = filters.get(n);
1103                 filter.setVerified(verified);
1104
1105                 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString()
1106                         + " verified with result:" + verified + " and hosts:"
1107                         + ivs.getHostsString());
1108             }
1109
1110             mIntentFilterVerificationStates.remove(verificationId);
1111
1112             final String packageName = ivs.getPackageName();
1113             IntentFilterVerificationInfo ivi;
1114
1115             synchronized (mPackages) {
1116                 ivi = mSettings.getIntentFilterVerificationLPr(packageName);
1117             }
1118             if (ivi == null) {
1119                 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
1120                         + verificationId + " packageName:" + packageName);
1121                 return;
1122             }
1123
1124             synchronized (mPackages) {
1125                 if (verified) {
1126                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
1127                 } else {
1128                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
1129                 }
1130                 scheduleWriteSettingsLocked();
1131
1132                 final int userId = ivs.getUserId();
1133                 if (userId != UserHandle.USER_ALL) {
1134                     final int userStatus =
1135                             mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
1136
1137                     int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
1138                     boolean needUpdate = false;
1139
1140                     if (DEBUG_DOMAIN_VERIFICATION) {
1141                         Slog.d(TAG,
1142                                 "Updating IntentFilterVerificationInfo for package " + packageName
1143                                 + " verificationId:" + verificationId
1144                                 + " verified=" + verified);
1145                     }
1146
1147                     // In a success case, we promote from undefined or ASK to ALWAYS.  This
1148                     // supports a flow where the app fails validation but then ships an updated
1149                     // APK that passes, and therefore deserves to be in ALWAYS.
1150                     //
1151                     // If validation failed, the undefined state winds up in the basic ASK behavior,
1152                     // but apps that previously passed and became ALWAYS are *demoted* out of
1153                     // that state, since they would not deserve the ALWAYS behavior in case of a
1154                     // clean install.
1155                     switch (userStatus) {
1156                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS:
1157                             if (!verified) {
1158                                 // Don't demote if sysconfig says 'always'
1159                                 SystemConfig systemConfig = SystemConfig.getInstance();
1160                                 ArraySet<String> packages = systemConfig.getLinkedApps();
1161                                 if (!packages.contains(packageName)) {
1162                                     // updatedStatus is already UNDEFINED
1163                                     needUpdate = true;
1164
1165                                     if (DEBUG_DOMAIN_VERIFICATION) {
1166                                         Slog.d(TAG, "Formerly validated but now failing; demoting");
1167                                     }
1168                                 } else {
1169                                     if (DEBUG_DOMAIN_VERIFICATION) {
1170                                         Slog.d(TAG, "Updating bundled package " + packageName
1171                                                 + " failed autoVerify, but sysconfig supersedes");
1172                                     }
1173                                     // leave needUpdate == false here intentionally
1174                                 }
1175                             }
1176                             break;
1177
1178                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
1179                             // Stay in 'undefined' on verification failure
1180                             if (verified) {
1181                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1182                             }
1183                             needUpdate = true;
1184                             if (DEBUG_DOMAIN_VERIFICATION) {
1185                                 Slog.d(TAG, "Applying update; old=" + userStatus
1186                                         + " new=" + updatedStatus);
1187                             }
1188                             break;
1189
1190                         case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
1191                             // Keep in 'ask' on failure
1192                             if (verified) {
1193                                 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
1194                                 needUpdate = true;
1195                             }
1196                             break;
1197
1198                         default:
1199                             // Nothing to do
1200                     }
1201
1202                     if (needUpdate) {
1203                         mSettings.updateIntentFilterVerificationStatusLPw(
1204                                 packageName, updatedStatus, userId);
1205                         scheduleWritePackageRestrictionsLocked(userId);
1206                     }
1207                 } else {
1208                     Slog.i(TAG, "autoVerify ignored when installing for all users");
1209                 }
1210             }
1211         }
1212
1213         @Override
1214         public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId,
1215                     ActivityIntentInfo filter, String packageName) {
1216             if (!hasValidDomains(filter)) {
1217                 return false;
1218             }
1219             IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
1220             if (ivs == null) {
1221                 ivs = createDomainVerificationState(verifierUid, userId, verificationId,
1222                         packageName);
1223             }
1224             if (DEBUG_DOMAIN_VERIFICATION) {
1225                 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter);
1226             }
1227             ivs.addFilter(filter);
1228             return true;
1229         }
1230
1231         private IntentFilterVerificationState createDomainVerificationState(int verifierUid,
1232                 int userId, int verificationId, String packageName) {
1233             IntentFilterVerificationState ivs = new IntentFilterVerificationState(
1234                     verifierUid, userId, packageName);
1235             ivs.setPendingState();
1236             synchronized (mPackages) {
1237                 mIntentFilterVerificationStates.append(verificationId, ivs);
1238                 mCurrentIntentFilterVerifications.add(verificationId);
1239             }
1240             return ivs;
1241         }
1242     }
1243
1244     private static boolean hasValidDomains(ActivityIntentInfo filter) {
1245         return filter.hasCategory(Intent.CATEGORY_BROWSABLE)
1246                 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
1247                         filter.hasDataScheme(IntentFilter.SCHEME_HTTPS));
1248     }
1249
1250     // Set of pending broadcasts for aggregating enable/disable of components.
1251     static class PendingPackageBroadcasts {
1252         // for each user id, a map of <package name -> components within that package>
1253         final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
1254
1255         public PendingPackageBroadcasts() {
1256             mUidMap = new SparseArray<>(2);
1257         }
1258
1259         public ArrayList<String> get(int userId, String packageName) {
1260             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1261             return packages.get(packageName);
1262         }
1263
1264         public void put(int userId, String packageName, ArrayList<String> components) {
1265             ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
1266             packages.put(packageName, components);
1267         }
1268
1269         public void remove(int userId, String packageName) {
1270             ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
1271             if (packages != null) {
1272                 packages.remove(packageName);
1273             }
1274         }
1275
1276         public void remove(int userId) {
1277             mUidMap.remove(userId);
1278         }
1279
1280         public int userIdCount() {
1281             return mUidMap.size();
1282         }
1283
1284         public int userIdAt(int n) {
1285             return mUidMap.keyAt(n);
1286         }
1287
1288         public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
1289             return mUidMap.get(userId);
1290         }
1291
1292         public int size() {
1293             // total number of pending broadcast entries across all userIds
1294             int num = 0;
1295             for (int i = 0; i< mUidMap.size(); i++) {
1296                 num += mUidMap.valueAt(i).size();
1297             }
1298             return num;
1299         }
1300
1301         public void clear() {
1302             mUidMap.clear();
1303         }
1304
1305         private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
1306             ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
1307             if (map == null) {
1308                 map = new ArrayMap<>();
1309                 mUidMap.put(userId, map);
1310             }
1311             return map;
1312         }
1313     }
1314     final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
1315
1316     static final int SEND_PENDING_BROADCAST = 1;
1317     static final int INIT_COPY = 5;
1318     static final int POST_INSTALL = 9;
1319     static final int WRITE_SETTINGS = 13;
1320     static final int WRITE_PACKAGE_RESTRICTIONS = 14;
1321     static final int PACKAGE_VERIFIED = 15;
1322     static final int CHECK_PENDING_VERIFICATION = 16;
1323     static final int START_INTENT_FILTER_VERIFICATIONS = 17;
1324     static final int INTENT_FILTER_VERIFIED = 18;
1325     static final int WRITE_PACKAGE_LIST = 19;
1326     static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20;
1327     static final int ENABLE_ROLLBACK_STATUS = 21;
1328     static final int ENABLE_ROLLBACK_TIMEOUT = 22;
1329     static final int DEFERRED_NO_KILL_POST_DELETE = 23;
1330     static final int DEFERRED_NO_KILL_INSTALL_OBSERVER = 24;
1331
1332     static final int DEFERRED_NO_KILL_POST_DELETE_DELAY_MS = 3 * 1000;
1333     static final int DEFERRED_NO_KILL_INSTALL_OBSERVER_DELAY_MS = 500;
1334
1335     static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
1336
1337     private static final long BROADCAST_DELAY_DURING_STARTUP = 10 * 1000L; // 10 seconds (in millis)
1338     private static final long BROADCAST_DELAY = 1 * 1000L; // 1 second (in millis)
1339
1340     // When the service constructor finished plus a delay (used for broadcast delay computation)
1341     private long mServiceStartWithDelay;
1342
1343     private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD =
1344             2 * 60 * 60 * 1000L; /* two hours */
1345
1346     static UserManagerService sUserManager;
1347
1348     // Stores a list of users whose package restrictions file needs to be updated
1349     private ArraySet<Integer> mDirtyUsers = new ArraySet<>();
1350
1351     // Recordkeeping of restore-after-install operations that are currently in flight
1352     // between the Package Manager and the Backup Manager
1353     static class PostInstallData {
1354         public final InstallArgs args;
1355         public final PackageInstalledInfo res;
1356         public final Runnable mPostInstallRunnable;
1357
1358         PostInstallData(InstallArgs _a, PackageInstalledInfo _r, Runnable postInstallRunnable) {
1359             args = _a;
1360             res = _r;
1361             mPostInstallRunnable = postInstallRunnable;
1362         }
1363     }
1364
1365     final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<>();
1366     int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
1367
1368     // XML tags for backup/restore of various bits of state
1369     private static final String TAG_PREFERRED_BACKUP = "pa";
1370     private static final String TAG_DEFAULT_APPS = "da";
1371     private static final String TAG_INTENT_FILTER_VERIFICATION = "iv";
1372
1373     private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup";
1374     private static final String TAG_ALL_GRANTS = "rt-grants";
1375     private static final String TAG_GRANT = "grant";
1376     private static final String ATTR_PACKAGE_NAME = "pkg";
1377
1378     private static final String TAG_PERMISSION = "perm";
1379     private static final String ATTR_PERMISSION_NAME = "name";
1380     private static final String ATTR_IS_GRANTED = "g";
1381     private static final String ATTR_USER_SET = "set";
1382     private static final String ATTR_USER_FIXED = "fixed";
1383     private static final String ATTR_REVOKE_ON_UPGRADE = "rou";
1384
1385     // System/policy permission grants are not backed up
1386     private static final int SYSTEM_RUNTIME_GRANT_MASK =
1387             FLAG_PERMISSION_POLICY_FIXED
1388             | FLAG_PERMISSION_SYSTEM_FIXED
1389             | FLAG_PERMISSION_GRANTED_BY_DEFAULT;
1390
1391     // And we back up these user-adjusted states
1392     private static final int USER_RUNTIME_GRANT_MASK =
1393             FLAG_PERMISSION_USER_SET
1394             | FLAG_PERMISSION_USER_FIXED
1395             | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
1396
1397     final @Nullable String mRequiredVerifierPackage;
1398     final @NonNull String mRequiredInstallerPackage;
1399     final @NonNull String mRequiredUninstallerPackage;
1400     final @NonNull String mRequiredPermissionControllerPackage;
1401     final @Nullable String mSetupWizardPackage;
1402     final @Nullable String mStorageManagerPackage;
1403     final @Nullable String mSystemTextClassifierPackage;
1404     final @Nullable String mWellbeingPackage;
1405     final @Nullable String mDocumenterPackage;
1406     final @Nullable String mConfiguratorPackage;
1407     final @Nullable String mAppPredictionServicePackage;
1408     final @Nullable String mIncidentReportApproverPackage;
1409     final @NonNull String mServicesSystemSharedLibraryPackageName;
1410     final @NonNull String mSharedSystemSharedLibraryPackageName;
1411
1412     private final PackageUsage mPackageUsage = new PackageUsage();
1413     private final CompilerStats mCompilerStats = new CompilerStats();
1414
1415     class PackageHandler extends Handler {
1416
1417         PackageHandler(Looper looper) {
1418             super(looper);
1419         }
1420
1421         public void handleMessage(Message msg) {
1422             try {
1423                 doHandleMessage(msg);
1424             } finally {
1425                 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1426             }
1427         }
1428
1429         void doHandleMessage(Message msg) {
1430             switch (msg.what) {
1431                 case INIT_COPY: {
1432                     HandlerParams params = (HandlerParams) msg.obj;
1433                     if (params != null) {
1434                         if (DEBUG_INSTALL) Slog.i(TAG, "init_copy: " + params);
1435                         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
1436                                 System.identityHashCode(params));
1437                         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
1438                         params.startCopy();
1439                         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
1440                     }
1441                     break;
1442                 }
1443                 case SEND_PENDING_BROADCAST: {
1444                     String packages[];
1445                     ArrayList<String> components[];
1446                     int size = 0;
1447                     int uids[];
1448                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1449                     synchronized (mPackages) {
1450                         size = mPendingBroadcasts.size();
1451                         if (size <= 0) {
1452                             // Nothing to be done. Just return
1453                             return;
1454                         }
1455                         packages = new String[size];
1456                         components = new ArrayList[size];
1457                         uids = new int[size];
1458                         int i = 0;  // filling out the above arrays
1459
1460                         for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1461                             int packageUserId = mPendingBroadcasts.userIdAt(n);
1462                             Iterator<Map.Entry<String, ArrayList<String>>> it
1463                                     = mPendingBroadcasts.packagesForUserId(packageUserId)
1464                                             .entrySet().iterator();
1465                             while (it.hasNext() && i < size) {
1466                                 Map.Entry<String, ArrayList<String>> ent = it.next();
1467                                 packages[i] = ent.getKey();
1468                                 components[i] = ent.getValue();
1469                                 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1470                                 uids[i] = (ps != null)
1471                                         ? UserHandle.getUid(packageUserId, ps.appId)
1472                                         : -1;
1473                                 i++;
1474                             }
1475                         }
1476                         size = i;
1477                         mPendingBroadcasts.clear();
1478                     }
1479                     // Send broadcasts
1480                     for (int i = 0; i < size; i++) {
1481                         sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1482                     }
1483                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1484                     break;
1485                 }
1486                 case POST_INSTALL: {
1487                     if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1488
1489                     PostInstallData data = mRunningInstalls.get(msg.arg1);
1490                     final boolean didRestore = (msg.arg2 != 0);
1491                     mRunningInstalls.delete(msg.arg1);
1492
1493                     if (data != null && data.mPostInstallRunnable != null) {
1494                         data.mPostInstallRunnable.run();
1495                     } else if (data != null) {
1496                         InstallArgs args = data.args;
1497                         PackageInstalledInfo parentRes = data.res;
1498
1499                         final boolean grantPermissions = (args.installFlags
1500                                 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0;
1501                         final boolean killApp = (args.installFlags
1502                                 & PackageManager.INSTALL_DONT_KILL_APP) == 0;
1503                         final boolean virtualPreload = ((args.installFlags
1504                                 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
1505                         final String[] grantedPermissions = args.installGrantPermissions;
1506                         final List<String> whitelistedRestrictedPermissions = ((args.installFlags
1507                                 & PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS) != 0
1508                                     && parentRes.pkg != null)
1509                                 ? parentRes.pkg.requestedPermissions
1510                                 : args.whitelistedRestrictedPermissions;
1511
1512                         // Handle the parent package
1513                         handlePackagePostInstall(parentRes, grantPermissions,
1514                                 killApp, virtualPreload, grantedPermissions,
1515                                 whitelistedRestrictedPermissions, didRestore,
1516                                 args.installerPackageName, args.observer);
1517
1518                         // Handle the child packages
1519                         final int childCount = (parentRes.addedChildPackages != null)
1520                                 ? parentRes.addedChildPackages.size() : 0;
1521                         for (int i = 0; i < childCount; i++) {
1522                             PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i);
1523                             handlePackagePostInstall(childRes, grantPermissions,
1524                                     killApp, virtualPreload, grantedPermissions,
1525                                     whitelistedRestrictedPermissions, false /*didRestore*/,
1526                                     args.installerPackageName, args.observer);
1527                         }
1528
1529                         // Log tracing if needed
1530                         if (args.traceMethod != null) {
1531                             Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod,
1532                                     args.traceCookie);
1533                         }
1534                     } else if (DEBUG_INSTALL) {
1535                         // No post-install when we run restore from installExistingPackageForUser
1536                         Slog.i(TAG, "Nothing to do for post-install token " + msg.arg1);
1537                     }
1538
1539                     Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1);
1540                 } break;
1541                 case DEFERRED_NO_KILL_POST_DELETE: {
1542                     synchronized (mInstallLock) {
1543                         InstallArgs args = (InstallArgs) msg.obj;
1544                         if (args != null) {
1545                             args.doPostDeleteLI(true);
1546                         }
1547                     }
1548                 } break;
1549                 case DEFERRED_NO_KILL_INSTALL_OBSERVER: {
1550                     String packageName = (String) msg.obj;
1551                     if (packageName != null) {
1552                         notifyInstallObserver(packageName);
1553                     }
1554                 } break;
1555                 case WRITE_SETTINGS: {
1556                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1557                     synchronized (mPackages) {
1558                         removeMessages(WRITE_SETTINGS);
1559                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1560                         mSettings.writeLPr();
1561                         mDirtyUsers.clear();
1562                     }
1563                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1564                 } break;
1565                 case WRITE_PACKAGE_RESTRICTIONS: {
1566                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1567                     synchronized (mPackages) {
1568                         removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1569                         for (int userId : mDirtyUsers) {
1570                             mSettings.writePackageRestrictionsLPr(userId);
1571                         }
1572                         mDirtyUsers.clear();
1573                     }
1574                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1575                 } break;
1576                 case WRITE_PACKAGE_LIST: {
1577                     Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1578                     synchronized (mPackages) {
1579                         removeMessages(WRITE_PACKAGE_LIST);
1580                         mSettings.writePackageListLPr(msg.arg1);
1581                     }
1582                     Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1583                 } break;
1584                 case CHECK_PENDING_VERIFICATION: {
1585                     final int verificationId = msg.arg1;
1586                     final PackageVerificationState state = mPendingVerification.get(verificationId);
1587
1588                     if ((state != null) && !state.timeoutExtended()) {
1589                         final InstallParams params = state.getInstallParams();
1590                         final InstallArgs args = params.mArgs;
1591                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1592
1593                         Slog.i(TAG, "Verification timed out for " + originUri);
1594                         mPendingVerification.remove(verificationId);
1595
1596                         final UserHandle user = args.getUser();
1597                         if (getDefaultVerificationResponse(user)
1598                                 == PackageManager.VERIFICATION_ALLOW) {
1599                             Slog.i(TAG, "Continuing with installation of " + originUri);
1600                             state.setVerifierResponse(Binder.getCallingUid(),
1601                                     PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1602                             broadcastPackageVerified(verificationId, originUri,
1603                                     PackageManager.VERIFICATION_ALLOW, user);
1604                         } else {
1605                             broadcastPackageVerified(verificationId, originUri,
1606                                     PackageManager.VERIFICATION_REJECT, user);
1607                             params.setReturnCode(
1608                                     PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE);
1609                         }
1610
1611                         Trace.asyncTraceEnd(
1612                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1613                         params.handleVerificationFinished();
1614                     }
1615                     break;
1616                 }
1617                 case PACKAGE_VERIFIED: {
1618                     final int verificationId = msg.arg1;
1619
1620                     final PackageVerificationState state = mPendingVerification.get(verificationId);
1621                     if (state == null) {
1622                         Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1623                         break;
1624                     }
1625
1626                     final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1627
1628                     state.setVerifierResponse(response.callerUid, response.code);
1629
1630                     if (state.isVerificationComplete()) {
1631                         mPendingVerification.remove(verificationId);
1632
1633                         final InstallParams params = state.getInstallParams();
1634                         final InstallArgs args = params.mArgs;
1635                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1636
1637                         if (state.isInstallAllowed()) {
1638                             broadcastPackageVerified(verificationId, originUri,
1639                                     response.code, args.getUser());
1640                         } else {
1641                             params.setReturnCode(
1642                                     PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE);
1643                         }
1644
1645                         Trace.asyncTraceEnd(
1646                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
1647
1648                         params.handleVerificationFinished();
1649                     }
1650
1651                     break;
1652                 }
1653                 case START_INTENT_FILTER_VERIFICATIONS: {
1654                     IFVerificationParams params = (IFVerificationParams) msg.obj;
1655                     verifyIntentFiltersIfNeeded(params.userId, params.verifierUid,
1656                             params.replacing, params.pkg);
1657                     break;
1658                 }
1659                 case INTENT_FILTER_VERIFIED: {
1660                     final int verificationId = msg.arg1;
1661
1662                     final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1663                             verificationId);
1664                     if (state == null) {
1665                         Slog.w(TAG, "Invalid IntentFilter verification token "
1666                                 + verificationId + " received");
1667                         break;
1668                     }
1669
1670                     final int userId = state.getUserId();
1671
1672                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1673                             "Processing IntentFilter verification with token:"
1674                             + verificationId + " and userId:" + userId);
1675
1676                     final IntentFilterVerificationResponse response =
1677                             (IntentFilterVerificationResponse) msg.obj;
1678
1679                     state.setVerifierResponse(response.callerUid, response.code);
1680
1681                     if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1682                             "IntentFilter verification with token:" + verificationId
1683                             + " and userId:" + userId
1684                             + " is settings verifier response with response code:"
1685                             + response.code);
1686
1687                     if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1688                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: "
1689                                 + response.getFailedDomainsString());
1690                     }
1691
1692                     if (state.isVerificationComplete()) {
1693                         mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1694                     } else {
1695                         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
1696                                 "IntentFilter verification with token:" + verificationId
1697                                 + " was not said to be complete");
1698                     }
1699
1700                     break;
1701                 }
1702                 case INSTANT_APP_RESOLUTION_PHASE_TWO: {
1703                     InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext,
1704                             mInstantAppResolverConnection,
1705                             (InstantAppRequest) msg.obj,
1706                             mInstantAppInstallerActivity,
1707                             mHandler);
1708                     break;
1709                 }
1710                 case ENABLE_ROLLBACK_STATUS: {
1711                     final int enableRollbackToken = msg.arg1;
1712                     final int enableRollbackCode = msg.arg2;
1713                     InstallParams params = mPendingEnableRollback.get(enableRollbackToken);
1714                     if (params == null) {
1715                         Slog.w(TAG, "Invalid rollback enabled token "
1716                                 + enableRollbackToken + " received");
1717                         break;
1718                     }
1719
1720                     mPendingEnableRollback.remove(enableRollbackToken);
1721
1722                     if (enableRollbackCode != PackageManagerInternal.ENABLE_ROLLBACK_SUCCEEDED) {
1723                         final InstallArgs args = params.mArgs;
1724                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1725                         Slog.w(TAG, "Failed to enable rollback for " + originUri);
1726                         Slog.w(TAG, "Continuing with installation of " + originUri);
1727                     }
1728
1729                     Trace.asyncTraceEnd(
1730                             TRACE_TAG_PACKAGE_MANAGER, "enable_rollback", enableRollbackToken);
1731
1732                     params.handleRollbackEnabled();
1733                     break;
1734                 }
1735                 case ENABLE_ROLLBACK_TIMEOUT: {
1736                     final int enableRollbackToken = msg.arg1;
1737                     final InstallParams params = mPendingEnableRollback.get(enableRollbackToken);
1738                     if (params != null) {
1739                         final InstallArgs args = params.mArgs;
1740                         final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1741
1742                         Slog.w(TAG, "Enable rollback timed out for " + originUri);
1743                         mPendingEnableRollback.remove(enableRollbackToken);
1744
1745                         Slog.w(TAG, "Continuing with installation of " + originUri);
1746                         Trace.asyncTraceEnd(
1747                                 TRACE_TAG_PACKAGE_MANAGER, "enable_rollback", enableRollbackToken);
1748                         params.handleRollbackEnabled();
1749                         Intent rollbackTimeoutIntent = new Intent(
1750                                 Intent.ACTION_CANCEL_ENABLE_ROLLBACK);
1751                         rollbackTimeoutIntent.putExtra(
1752                                 PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_TOKEN,
1753                                 enableRollbackToken);
1754                         rollbackTimeoutIntent.addFlags(
1755                                 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1756                         mContext.sendBroadcastAsUser(rollbackTimeoutIntent, UserHandle.SYSTEM,
1757                                 android.Manifest.permission.PACKAGE_ROLLBACK_AGENT);
1758                     }
1759                     break;
1760                 }
1761             }
1762         }
1763     }
1764
1765     private PermissionCallback mPermissionCallback = new PermissionCallback() {
1766         @Override
1767         public void onGidsChanged(int appId, int userId) {
1768             mHandler.post(() -> killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED));
1769         }
1770         @Override
1771         public void onPermissionGranted(int uid, int userId) {
1772             mOnPermissionChangeListeners.onPermissionsChanged(uid);
1773
1774             // Not critical; if this is lost, the application has to request again.
1775             synchronized (mPackages) {
1776                 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
1777             }
1778         }
1779         @Override
1780         public void onInstallPermissionGranted() {
1781             synchronized (mPackages) {
1782                 scheduleWriteSettingsLocked();
1783             }
1784         }
1785         @Override
1786         public void onPermissionRevoked(int uid, int userId) {
1787             mOnPermissionChangeListeners.onPermissionsChanged(uid);
1788
1789             synchronized (mPackages) {
1790                 // Critical; after this call the application should never have the permission
1791                 mSettings.writeRuntimePermissionsForUserLPr(userId, true);
1792             }
1793
1794             final int appId = UserHandle.getAppId(uid);
1795             killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
1796         }
1797         @Override
1798         public void onInstallPermissionRevoked() {
1799             synchronized (mPackages) {
1800                 scheduleWriteSettingsLocked();
1801             }
1802         }
1803         @Override
1804         public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
1805             synchronized (mPackages) {
1806                 for (int userId : updatedUserIds) {
1807                     mSettings.writeRuntimePermissionsForUserLPr(userId, sync);
1808                 }
1809             }
1810         }
1811         @Override
1812         public void onInstallPermissionUpdated() {
1813             synchronized (mPackages) {
1814                 scheduleWriteSettingsLocked();
1815             }
1816         }
1817         @Override
1818         public void onPermissionRemoved() {
1819             synchronized (mPackages) {
1820                 mSettings.writeLPr();
1821             }
1822         }
1823     };
1824
1825     private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
1826             boolean killApp, boolean virtualPreload,
1827             String[] grantedPermissions, List<String> whitelistedRestrictedPermissions,
1828             boolean launchedForRestore, String installerPackage,
1829             IPackageInstallObserver2 installObserver) {
1830         final boolean succeeded = res.returnCode == PackageManager.INSTALL_SUCCEEDED;
1831         final boolean update = res.removedInfo != null && res.removedInfo.removedPackage != null;
1832
1833         if (succeeded) {
1834             // Send the removed broadcasts
1835             if (res.removedInfo != null) {
1836                 res.removedInfo.sendPackageRemovedBroadcasts(killApp);
1837             }
1838
1839             // Whitelist any restricted permissions first as some may be runtime
1840             // that the installer requested to be granted at install time.
1841             if (whitelistedRestrictedPermissions != null
1842                     && !whitelistedRestrictedPermissions.isEmpty()) {
1843                 mPermissionManager.setWhitelistedRestrictedPermissions(
1844                         res.pkg, res.newUsers, whitelistedRestrictedPermissions,
1845                         Process.myUid(), PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER,
1846                         mPermissionCallback);
1847             }
1848
1849             // Now that we successfully installed the package, grant runtime
1850             // permissions if requested before broadcasting the install. Also
1851             // for legacy apps in permission review mode we clear the permission
1852             // review flag which is used to emulate runtime permissions for
1853             // legacy apps.
1854             if (grantPermissions) {
1855                 final int callingUid = Binder.getCallingUid();
1856                 mPermissionManager.grantRequestedRuntimePermissions(
1857                         res.pkg, res.newUsers, grantedPermissions, callingUid,
1858                         mPermissionCallback);
1859             }
1860
1861             final String installerPackageName =
1862                     res.installerPackageName != null
1863                             ? res.installerPackageName
1864                             : res.removedInfo != null
1865                                     ? res.removedInfo.installerPackageName
1866                                     : null;
1867
1868             // If this is the first time we have child packages for a disabled privileged
1869             // app that had no children, we grant requested runtime permissions to the new
1870             // children if the parent on the system image had them already granted.
1871             if (res.pkg.parentPackage != null) {
1872                 final int callingUid = Binder.getCallingUid();
1873                 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage(
1874                         res.pkg, callingUid, mPermissionCallback);
1875             }
1876
1877             synchronized (mPackages) {
1878                 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers);
1879             }
1880
1881             final String packageName = res.pkg.applicationInfo.packageName;
1882
1883             // Determine the set of users who are adding this package for
1884             // the first time vs. those who are seeing an update.
1885             int[] firstUserIds = EMPTY_INT_ARRAY;
1886             int[] firstInstantUserIds = EMPTY_INT_ARRAY;
1887             int[] updateUserIds = EMPTY_INT_ARRAY;
1888             int[] instantUserIds = EMPTY_INT_ARRAY;
1889             final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0;
1890             final PackageSetting ps = (PackageSetting) res.pkg.mExtras;
1891             for (int newUser : res.newUsers) {
1892                 final boolean isInstantApp = ps.getInstantApp(newUser);
1893                 if (allNewUsers) {
1894                     if (isInstantApp) {
1895                         firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1896                     } else {
1897                         firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
1898                     }
1899                     continue;
1900                 }
1901                 boolean isNew = true;
1902                 for (int origUser : res.origUsers) {
1903                     if (origUser == newUser) {
1904                         isNew = false;
1905                         break;
1906                     }
1907                 }
1908                 if (isNew) {
1909                     if (isInstantApp) {
1910                         firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser);
1911                     } else {
1912                         firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser);
1913                     }
1914                 } else {
1915                     if (isInstantApp) {
1916                         instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser);
1917                     } else {
1918                         updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser);
1919                     }
1920                 }
1921             }
1922
1923             // Send installed broadcasts if the package is not a static shared lib.
1924             if (res.pkg.staticSharedLibName == null) {
1925                 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath);
1926
1927                 // Send added for users that see the package for the first time
1928                 // sendPackageAddedForNewUsers also deals with system apps
1929                 int appId = UserHandle.getAppId(res.uid);
1930                 boolean isSystem = res.pkg.applicationInfo.isSystemApp();
1931                 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload,
1932                         virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds);
1933
1934                 // Send added for users that don't see the package for the first time
1935                 Bundle extras = new Bundle(1);
1936                 extras.putInt(Intent.EXTRA_UID, res.uid);
1937                 if (update) {
1938                     extras.putBoolean(Intent.EXTRA_REPLACING, true);
1939                 }
1940                 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1941                         extras, 0 /*flags*/,
1942                         null /*targetPackage*/, null /*finishedReceiver*/,
1943                         updateUserIds, instantUserIds);
1944                 if (installerPackageName != null) {
1945                     sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1946                             extras, 0 /*flags*/,
1947                             installerPackageName, null /*finishedReceiver*/,
1948                             updateUserIds, instantUserIds);
1949                 }
1950                 // if the required verifier is defined, but, is not the installer of record
1951                 // for the package, it gets notified
1952                 final boolean notifyVerifier = mRequiredVerifierPackage != null
1953                         && !mRequiredVerifierPackage.equals(installerPackageName);
1954                 if (notifyVerifier) {
1955                     sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1956                             extras, 0 /*flags*/,
1957                             mRequiredVerifierPackage, null /*finishedReceiver*/,
1958                             updateUserIds, instantUserIds);
1959                 }
1960                 // If package installer is defined, notify package installer about new
1961                 // app installed
1962                 if (mRequiredInstallerPackage != null) {
1963                     sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
1964                             extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND /*flags*/,
1965                             mRequiredInstallerPackage, null /*finishedReceiver*/,
1966                             firstUserIds, instantUserIds);
1967                 }
1968
1969                 // Send replaced for users that don't see the package for the first time
1970                 if (update) {
1971                     sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1972                             packageName, extras, 0 /*flags*/,
1973                             null /*targetPackage*/, null /*finishedReceiver*/,
1974                             updateUserIds, instantUserIds);
1975                     if (installerPackageName != null) {
1976                         sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1977                                 extras, 0 /*flags*/,
1978                                 installerPackageName, null /*finishedReceiver*/,
1979                                 updateUserIds, instantUserIds);
1980                     }
1981                     if (notifyVerifier) {
1982                         sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
1983                                 extras, 0 /*flags*/,
1984                                 mRequiredVerifierPackage, null /*finishedReceiver*/,
1985                                 updateUserIds, instantUserIds);
1986                     }
1987                     sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1988                             null /*package*/, null /*extras*/, 0 /*flags*/,
1989                             packageName /*targetPackage*/,
1990                             null /*finishedReceiver*/, updateUserIds, instantUserIds);
1991                 } else if (launchedForRestore && !isSystemApp(res.pkg)) {
1992                     // First-install and we did a restore, so we're responsible for the
1993                     // first-launch broadcast.
1994                     if (DEBUG_BACKUP) {
1995                         Slog.i(TAG, "Post-restore of " + packageName
1996                                 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds));
1997                     }
1998                     sendFirstLaunchBroadcast(packageName, installerPackage,
1999                             firstUserIds, firstInstantUserIds);
2000                 }
2001
2002                 // Send broadcast package appeared if external for all users
2003                 if (isExternal(res.pkg)) {
2004                     if (!update) {
2005                         final StorageManager storage =
2006                                 mContext.getSystemService(StorageManager.class);
2007                         VolumeInfo volume =
2008                                 storage.findVolumeByUuid(
2009                                         res.pkg.applicationInfo.storageUuid.toString());
2010                         int packageExternalStorageType =
2011                                 getPackageExternalStorageType(volume, isExternal(res.pkg));
2012                         // If the package was installed externally, log it.
2013                         if (packageExternalStorageType != StorageEnums.UNKNOWN) {
2014                             StatsLog.write(StatsLog.APP_INSTALL_ON_EXTERNAL_STORAGE_REPORTED,
2015                                     packageExternalStorageType, res.pkg.packageName);
2016                         }
2017                     }
2018                     if (DEBUG_INSTALL) {
2019                         Slog.i(TAG, "upgrading pkg " + res.pkg + " is external");
2020                     }
2021                     final int[] uidArray = new int[]{res.pkg.applicationInfo.uid};
2022                     ArrayList<String> pkgList = new ArrayList<>(1);
2023                     pkgList.add(packageName);
2024                     sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null);
2025                 }
2026             }
2027
2028             // Work that needs to happen on first install within each user
2029             if (firstUserIds != null && firstUserIds.length > 0) {
2030                 for (int userId : firstUserIds) {
2031                     // If this app is a browser and it's newly-installed for some
2032                     // users, clear any default-browser state in those users. The
2033                     // app's nature doesn't depend on the user, so we can just check
2034                     // its browser nature in any user and generalize.
2035                     if (packageIsBrowser(packageName, userId)) {
2036                         // If this browser is restored from user's backup, do not clear
2037                         // default-browser state for this user
2038                         synchronized (mPackages) {
2039                             final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
2040                             if (pkgSetting.getInstallReason(userId)
2041                                     != PackageManager.INSTALL_REASON_DEVICE_RESTORE) {
2042                                 setDefaultBrowserAsyncLPw(null, userId);
2043                             }
2044                         }
2045                     }
2046
2047                     // We may also need to apply pending (restored) runtime permission grants
2048                     // within these users.
2049                     mPermissionManager.restoreDelayedRuntimePermissions(packageName,
2050                             UserHandle.of(userId));
2051
2052                     // Persistent preferred activity might have came into effect due to this
2053                     // install.
2054                     updateDefaultHomeNotLocked(userId);
2055                 }
2056             }
2057
2058             if (allNewUsers && !update) {
2059                 notifyPackageAdded(packageName, res.uid);
2060             } else {
2061                 notifyPackageChanged(packageName, res.uid);
2062             }
2063
2064             // Log current value of "unknown sources" setting
2065             EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
2066                     getUnknownSourcesSettings());
2067
2068             // Remove the replaced package's older resources safely now
2069             InstallArgs args = res.removedInfo != null ? res.removedInfo.args : null;
2070             if (args != null) {
2071                 if (!killApp) {
2072                     // If we didn't kill the app, defer the deletion of code/resource files, since
2073                     // they may still be in use by the running application. This mitigates problems
2074                     // in cases where resources or code is loaded by a new Activity before
2075                     // ApplicationInfo changes have propagated to all application threads.
2076                     scheduleDeferredNoKillPostDelete(args);
2077                 } else {
2078                     synchronized (mInstallLock) {
2079                         args.doPostDeleteLI(true);
2080                     }
2081                 }
2082             } else {
2083                 // Force a gc to clear up things. Ask for a background one, it's fine to go on
2084                 // and not block here.
2085                 VMRuntime.getRuntime().requestConcurrentGC();
2086             }
2087
2088             // Notify DexManager that the package was installed for new users.
2089             // The updated users should already be indexed and the package code paths
2090             // should not change.
2091             // Don't notify the manager for ephemeral apps as they are not expected to
2092             // survive long enough to benefit of background optimizations.
2093             for (int userId : firstUserIds) {
2094                 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId);
2095                 // There's a race currently where some install events may interleave with an uninstall.
2096                 // This can lead to package info being null (b/36642664).
2097                 if (info != null) {
2098                     mDexManager.notifyPackageInstalled(info, userId);
2099                 }
2100             }
2101         }
2102
2103         final boolean deferInstallObserver = succeeded && update && !killApp;
2104         if (deferInstallObserver) {
2105             scheduleDeferredNoKillInstallObserver(res, installObserver);
2106         } else {
2107             notifyInstallObserver(res, installObserver);
2108         }
2109     }
2110
2111     @Override
2112     public void notifyPackagesReplacedReceived(String[] packages) {
2113         final int callingUid = Binder.getCallingUid();
2114         final int callingUserId = UserHandle.getUserId(callingUid);
2115
2116         for (String packageName : packages) {
2117             PackageSetting setting = mSettings.mPackages.get(packageName);
2118             if (setting != null && filterAppAccessLPr(setting, callingUid, callingUserId)) {
2119                 notifyInstallObserver(packageName);
2120             }
2121         }
2122     }
2123
2124     private void notifyInstallObserver(String packageName) {
2125         Pair<PackageInstalledInfo, IPackageInstallObserver2> pair =
2126                 mNoKillInstallObservers.remove(packageName);
2127
2128         if (pair != null) {
2129             notifyInstallObserver(pair.first, pair.second);
2130         }
2131     }
2132
2133     private void notifyInstallObserver(PackageInstalledInfo info,
2134             IPackageInstallObserver2 installObserver) {
2135         if (installObserver != null) {
2136             try {
2137                 Bundle extras = extrasForInstallResult(info);
2138                 installObserver.onPackageInstalled(info.name, info.returnCode,
2139                         info.returnMsg, extras);
2140             } catch (RemoteException e) {
2141                 Slog.i(TAG, "Observer no longer exists.");
2142             }
2143         }
2144     }
2145
2146     private void scheduleDeferredNoKillPostDelete(InstallArgs args) {
2147         Message message = mHandler.obtainMessage(DEFERRED_NO_KILL_POST_DELETE, args);
2148         mHandler.sendMessageDelayed(message, DEFERRED_NO_KILL_POST_DELETE_DELAY_MS);
2149     }
2150
2151     private void scheduleDeferredNoKillInstallObserver(PackageInstalledInfo info,
2152             IPackageInstallObserver2 observer) {
2153         String packageName = info.pkg.packageName;
2154         mNoKillInstallObservers.put(packageName, Pair.create(info, observer));
2155         Message message = mHandler.obtainMessage(DEFERRED_NO_KILL_INSTALL_OBSERVER, packageName);
2156         mHandler.sendMessageDelayed(message, DEFERRED_NO_KILL_INSTALL_OBSERVER_DELAY_MS);
2157     }
2158
2159     /**
2160      * Gets the type of the external storage a package is installed on.
2161      * @param packageVolume The storage volume of the package.
2162      * @param packageIsExternal true if the package is currently installed on
2163      * external/removable/unprotected storage.
2164      * @return {@link StorageEnum#TYPE_UNKNOWN} if the package is not stored externally or the
2165      * corresponding {@link StorageEnum} storage type value if it is.
2166      */
2167     private static int getPackageExternalStorageType(VolumeInfo packageVolume,
2168             boolean packageIsExternal) {
2169         if (packageVolume != null) {
2170             DiskInfo disk = packageVolume.getDisk();
2171             if (disk != null) {
2172                 if (disk.isSd()) {
2173                     return StorageEnums.SD_CARD;
2174                 }
2175                 if (disk.isUsb()) {
2176                     return StorageEnums.USB;
2177                 }
2178                 if (packageIsExternal) {
2179                     return StorageEnums.OTHER;
2180                 }
2181             }
2182         }
2183         return StorageEnums.UNKNOWN;
2184     }
2185
2186     private StorageEventListener mStorageListener = new StorageEventListener() {
2187         @Override
2188         public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
2189             if (vol.type == VolumeInfo.TYPE_PRIVATE) {
2190                 if (vol.state == VolumeInfo.STATE_MOUNTED) {
2191                     final String volumeUuid = vol.getFsUuid();
2192
2193                     // Clean up any users or apps that were removed or recreated
2194                     // while this volume was missing
2195                     sUserManager.reconcileUsers(volumeUuid);
2196                     reconcileApps(volumeUuid);
2197
2198                     // Clean up any install sessions that expired or were
2199                     // cancelled while this volume was missing
2200                     mInstallerService.onPrivateVolumeMounted(volumeUuid);
2201
2202                     loadPrivatePackages(vol);
2203
2204                 } else if (vol.state == VolumeInfo.STATE_EJECTING) {
2205                     unloadPrivatePackages(vol);
2206                 }
2207             }
2208         }
2209
2210         @Override
2211         public void onVolumeForgotten(String fsUuid) {
2212             if (TextUtils.isEmpty(fsUuid)) {
2213                 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring");
2214                 return;
2215             }
2216
2217             // Remove any apps installed on the forgotten volume
2218             synchronized (mPackages) {
2219                 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid);
2220                 for (PackageSetting ps : packages) {
2221                     Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten");
2222                     deletePackageVersioned(new VersionedPackage(ps.name,
2223                             PackageManager.VERSION_CODE_HIGHEST),
2224                             new LegacyPackageDeleteObserver(null).getBinder(),
2225                             UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS);
2226                     // Try very hard to release any references to this package
2227                     // so we don't risk the system server being killed due to
2228                     // open FDs
2229                     AttributeCache.instance().removePackage(ps.name);
2230                 }
2231
2232                 mSettings.onVolumeForgotten(fsUuid);
2233                 mSettings.writeLPr();
2234             }
2235         }
2236     };
2237
2238     Bundle extrasForInstallResult(PackageInstalledInfo res) {
2239         Bundle extras = null;
2240         switch (res.returnCode) {
2241             case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
2242                 extras = new Bundle();
2243                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
2244                         res.origPermission);
2245                 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
2246                         res.origPackage);
2247                 break;
2248             }
2249             case PackageManager.INSTALL_SUCCEEDED: {
2250                 extras = new Bundle();
2251                 extras.putBoolean(Intent.EXTRA_REPLACING,
2252                         res.removedInfo != null && res.removedInfo.removedPackage != null);
2253                 break;
2254             }
2255         }
2256         return extras;
2257     }
2258
2259     void scheduleWriteSettingsLocked() {
2260         if (!mHandler.hasMessages(WRITE_SETTINGS)) {
2261             mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
2262         }
2263     }
2264
2265     void scheduleWritePackageListLocked(int userId) {
2266         if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) {
2267             Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST);
2268             msg.arg1 = userId;
2269             mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY);
2270         }
2271     }
2272
2273     void scheduleWritePackageRestrictionsLocked(UserHandle user) {
2274         final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
2275         scheduleWritePackageRestrictionsLocked(userId);
2276     }
2277
2278     void scheduleWritePackageRestrictionsLocked(int userId) {
2279         final int[] userIds = (userId == UserHandle.USER_ALL)
2280                 ? sUserManager.getUserIds() : new int[]{userId};
2281         for (int nextUserId : userIds) {
2282             if (!sUserManager.exists(nextUserId)) return;
2283             mDirtyUsers.add(nextUserId);
2284             if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
2285                 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
2286             }
2287         }
2288     }
2289
2290     public static PackageManagerService main(Context context, Installer installer,
2291             boolean factoryTest, boolean onlyCore) {
2292         // Self-check for initial settings.
2293         PackageManagerServiceCompilerMapping.checkProperties();
2294
2295         PackageManagerService m = new PackageManagerService(context, installer,
2296                 factoryTest, onlyCore);
2297         m.enableSystemUserPackages();
2298         ServiceManager.addService("package", m);
2299         final PackageManagerNative pmn = m.new PackageManagerNative();
2300         ServiceManager.addService("package_native", pmn);
2301         return m;
2302     }
2303
2304     private void enableSystemUserPackages() {
2305         if (!UserManager.isSplitSystemUser()) {
2306             return;
2307         }
2308         // For system user, enable apps based on the following conditions:
2309         // - app is whitelisted or belong to one of these groups:
2310         //   -- system app which has no launcher icons
2311         //   -- system app which has INTERACT_ACROSS_USERS permission
2312         //   -- system IME app
2313         // - app is not in the blacklist
2314         AppsQueryHelper queryHelper = new AppsQueryHelper(this);
2315         Set<String> enableApps = new ArraySet<>();
2316         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS
2317                 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM
2318                 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM));
2319         ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps();
2320         enableApps.addAll(wlApps);
2321         enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER,
2322                 /* systemAppsOnly */ false, UserHandle.SYSTEM));
2323         ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps();
2324         enableApps.removeAll(blApps);
2325         Log.i(TAG, "Applications installed for system user: " + enableApps);
2326         List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false,
2327                 UserHandle.SYSTEM);
2328         final int allAppsSize = allAps.size();
2329         synchronized (mPackages) {
2330             for (int i = 0; i < allAppsSize; i++) {
2331                 String pName = allAps.get(i);
2332                 PackageSetting pkgSetting = mSettings.mPackages.get(pName);
2333                 // Should not happen, but we shouldn't be failing if it does
2334                 if (pkgSetting == null) {
2335                     continue;
2336                 }
2337                 boolean install = enableApps.contains(pName);
2338                 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) {
2339                     Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName
2340                             + " for system user");
2341                     pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM);
2342                 }
2343             }
2344             scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM);
2345         }
2346     }
2347
2348     private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
2349         DisplayManager displayManager = (DisplayManager) context.getSystemService(
2350                 Context.DISPLAY_SERVICE);
2351         displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
2352     }
2353
2354     /**
2355      * Requests that files preopted on a secondary system partition be copied to the data partition
2356      * if possible.  Note that the actual copying of the files is accomplished by init for security
2357      * reasons. This simply requests that the copy takes place and awaits confirmation of its
2358      * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy.
2359      */
2360     private static void requestCopyPreoptedFiles() {
2361         final int WAIT_TIME_MS = 100;
2362         final String CP_PREOPT_PROPERTY = "sys.cppreopt";
2363         if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) {
2364             SystemProperties.set(CP_PREOPT_PROPERTY, "requested");
2365             // We will wait for up to 100 seconds.
2366             final long timeStart = SystemClock.uptimeMillis();
2367             final long timeEnd = timeStart + 100 * 1000;
2368             long timeNow = timeStart;
2369             while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) {
2370                 try {
2371                     Thread.sleep(WAIT_TIME_MS);
2372                 } catch (InterruptedException e) {
2373                     // Do nothing
2374                 }
2375                 timeNow = SystemClock.uptimeMillis();
2376                 if (timeNow > timeEnd) {
2377                     SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out");
2378                     Slog.wtf(TAG, "cppreopt did not finish!");
2379                     break;
2380                 }
2381             }
2382
2383             Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms");
2384         }
2385     }
2386
2387     public PackageManagerService(Context context, Installer installer,
2388             boolean factoryTest, boolean onlyCore) {
2389         LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES);
2390         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager");
2391         EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
2392                 SystemClock.uptimeMillis());
2393
2394         if (mSdkVersion <= 0) {
2395             Slog.w(TAG, "**** ro.build.version.sdk not set!");
2396         }
2397
2398         mContext = context;
2399
2400         mFactoryTest = factoryTest;
2401         mOnlyCore = onlyCore;
2402         mMetrics = new DisplayMetrics();
2403         mInstaller = installer;
2404
2405         // Create sub-components that provide services / data. Order here is important.
2406         synchronized (mInstallLock) {
2407         synchronized (mPackages) {
2408             // Expose private service for system components to use.
2409             LocalServices.addService(
2410                     PackageManagerInternal.class, new PackageManagerInternalImpl());
2411             sUserManager = new UserManagerService(context, this,
2412                     new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages);
2413             mComponentResolver = new ComponentResolver(sUserManager,
2414                     LocalServices.getService(PackageManagerInternal.class),
2415                     mPackages);
2416             mPermissionManager = PermissionManagerService.create(context,
2417                     mPackages /*externalLock*/);
2418             mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy();
2419             mSettings = new Settings(Environment.getDataDirectory(),
2420                     mPermissionManager.getPermissionSettings(), mPackages);
2421         }
2422         }
2423         mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
2424                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2425         mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
2426                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2427         mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
2428                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2429         mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
2430                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2431         mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
2432                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2433         mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
2434                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2435         mSettings.addSharedUserLPw("android.uid.se", SE_UID,
2436                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2437         mSettings.addSharedUserLPw("android.uid.networkstack", NETWORKSTACK_UID,
2438                 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
2439
2440         String separateProcesses = SystemProperties.get("debug.separate_processes");
2441         if (separateProcesses != null && separateProcesses.length() > 0) {
2442             if ("*".equals(separateProcesses)) {
2443                 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
2444                 mSeparateProcesses = null;
2445                 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
2446             } else {
2447                 mDefParseFlags = 0;
2448                 mSeparateProcesses = separateProcesses.split(",");
2449                 Slog.w(TAG, "Running with debug.separate_processes: "
2450                         + separateProcesses);
2451             }
2452         } else {
2453             mDefParseFlags = 0;
2454             mSeparateProcesses = null;
2455         }
2456
2457         mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context,
2458                 "*dexopt*");
2459         mDexManager = new DexManager(mContext, this, mPackageDexOptimizer, installer, mInstallLock);
2460         mArtManagerService = new ArtManagerService(mContext, this, installer, mInstallLock);
2461         mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
2462
2463         mViewCompiler = new ViewCompiler(mInstallLock, mInstaller);
2464
2465         mOnPermissionChangeListeners = new OnPermissionChangeListeners(
2466                 FgThread.get().getLooper());
2467
2468         getDefaultDisplayMetrics(context, mMetrics);
2469
2470         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config");
2471         SystemConfig systemConfig = SystemConfig.getInstance();
2472         mAvailableFeatures = systemConfig.getAvailableFeatures();
2473         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2474
2475         mProtectedPackages = new ProtectedPackages(mContext);
2476
2477         mApexManager = new ApexManager(context);
2478         synchronized (mInstallLock) {
2479         // writer
2480         synchronized (mPackages) {
2481             mHandlerThread = new ServiceThread(TAG,
2482                     Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
2483             mHandlerThread.start();
2484             mHandler = new PackageHandler(mHandlerThread.getLooper());
2485             mProcessLoggingHandler = new ProcessLoggingHandler();
2486             Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
2487             mInstantAppRegistry = new InstantAppRegistry(this);
2488
2489             ArrayMap<String, SystemConfig.SharedLibraryEntry> libConfig
2490                     = systemConfig.getSharedLibraries();
2491             final int builtInLibCount = libConfig.size();
2492             for (int i = 0; i < builtInLibCount; i++) {
2493                 String name = libConfig.keyAt(i);
2494                 SystemConfig.SharedLibraryEntry entry = libConfig.valueAt(i);
2495                 addBuiltInSharedLibraryLocked(entry.filename, name);
2496             }
2497
2498             // Now that we have added all the libraries, iterate again to add dependency
2499             // information IFF their dependencies are added.
2500             long undefinedVersion = SharedLibraryInfo.VERSION_UNDEFINED;
2501             for (int i = 0; i < builtInLibCount; i++) {
2502                 String name = libConfig.keyAt(i);
2503                 SystemConfig.SharedLibraryEntry entry = libConfig.valueAt(i);
2504                 final int dependencyCount = entry.dependencies.length;
2505                 for (int j = 0; j < dependencyCount; j++) {
2506                     final SharedLibraryInfo dependency =
2507                         getSharedLibraryInfoLPr(entry.dependencies[j], undefinedVersion);
2508                     if (dependency != null) {
2509                         getSharedLibraryInfoLPr(name, undefinedVersion).addDependency(dependency);
2510                     }
2511                 }
2512             }
2513
2514             SELinuxMMAC.readInstallPolicy();
2515
2516             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks");
2517             FallbackCategoryProvider.loadFallbacks();
2518             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2519
2520             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings");
2521             mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false));
2522             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
2523
2524             // Clean up orphaned packages for which the code path doesn't exist
2525             // and they are an update to a system app - caused by bug/32321269
2526             final int packageSettingCount = mSettings.mPackages.size();
2527             for (int i = packageSettingCount - 1; i >= 0; i--) {
2528                 PackageSetting ps = mSettings.mPackages.valueAt(i);
2529                 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
2530                         && mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
2531                     mSettings.mPackages.removeAt(i);
2532                     mSettings.enableSystemPackageLPw(ps.name);
2533                 }
2534             }
2535
2536             if (!mOnlyCore && mFirstBoot) {
2537                 requestCopyPreoptedFiles();
2538             }
2539
2540             String customResolverActivityName = Resources.getSystem().getString(
2541                     R.string.config_customResolverActivity);
2542             if (!TextUtils.isEmpty(customResolverActivityName)) {
2543                 mCustomResolverComponentName = ComponentName.unflattenFromString(
2544                         customResolverActivityName);
2545             }
2546
2547             long startTime = SystemClock.uptimeMillis();
2548
2549             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
2550                     startTime);
2551
2552             final String bootClassPath = System.getenv("BOOTCLASSPATH");
2553             final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
2554
2555             if (bootClassPath == null) {
2556                 Slog.w(TAG, "No BOOTCLASSPATH found!");
2557             }
2558
2559             if (systemServerClassPath == null) {
2560                 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
2561             }
2562
2563             File frameworkDir = new File(Environment.getRootDirectory(), "framework");
2564
2565             final VersionInfo ver = mSettings.getInternalVersion();
2566             mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
2567             if (mIsUpgrade) {
2568                 logCriticalInfo(Log.INFO,
2569                         "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
2570             }
2571
2572             // when upgrading from pre-M, promote system app permissions from install to runtime
2573             mPromoteSystemApps =
2574                     mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
2575
2576             // When upgrading from pre-N, we need to handle package extraction like first boot,
2577             // as there is no profiling data available.
2578             mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
2579
2580             mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
2581             mIsPreQUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.Q;
2582
2583             int preUpgradeSdkVersion = ver.sdkVersion;
2584
2585             // save off the names of pre-existing system packages prior to scanning; we don't
2586             // want to automatically grant runtime permissions for new system apps
2587             if (mPromoteSystemApps) {
2588                 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator();
2589                 while (pkgSettingIter.hasNext()) {
2590                     PackageSetting ps = pkgSettingIter.next();
2591                     if (isSystemApp(ps)) {
2592                         mExistingSystemPackages.add(ps.name);
2593                     }
2594                 }
2595             }
2596
2597             mCacheDir = preparePackageParserCache();
2598
2599             // Set flag to monitor and not change apk file paths when
2600             // scanning install directories.
2601             int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
2602
2603             if (mIsUpgrade || mFirstBoot) {
2604                 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
2605             }
2606
2607             // Collect vendor/product/product_services overlay packages. (Do this before scanning
2608             // any apps.)
2609             // For security and version matching reason, only consider overlay packages if they
2610             // reside in the right directory.
2611             scanDirTracedLI(new File(VENDOR_OVERLAY_DIR),
2612                     mDefParseFlags
2613                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2614                     scanFlags
2615                     | SCAN_AS_SYSTEM
2616                     | SCAN_AS_VENDOR,
2617                     0);
2618             scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR),
2619                     mDefParseFlags
2620                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2621                     scanFlags
2622                     | SCAN_AS_SYSTEM
2623                     | SCAN_AS_PRODUCT,
2624                     0);
2625             scanDirTracedLI(new File(PRODUCT_SERVICES_OVERLAY_DIR),
2626                     mDefParseFlags
2627                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2628                     scanFlags
2629                     | SCAN_AS_SYSTEM
2630                     | SCAN_AS_PRODUCT_SERVICES,
2631                     0);
2632             scanDirTracedLI(new File(ODM_OVERLAY_DIR),
2633                     mDefParseFlags
2634                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2635                     scanFlags
2636                     | SCAN_AS_SYSTEM
2637                     | SCAN_AS_ODM,
2638                     0);
2639             scanDirTracedLI(new File(OEM_OVERLAY_DIR),
2640                     mDefParseFlags
2641                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2642                     scanFlags
2643                     | SCAN_AS_SYSTEM
2644                     | SCAN_AS_OEM,
2645                     0);
2646
2647             mParallelPackageParserCallback.findStaticOverlayPackages();
2648
2649             // Find base frameworks (resource packages without code).
2650             scanDirTracedLI(frameworkDir,
2651                     mDefParseFlags
2652                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2653                     scanFlags
2654                     | SCAN_NO_DEX
2655                     | SCAN_AS_SYSTEM
2656                     | SCAN_AS_PRIVILEGED,
2657                     0);
2658             if (!mPackages.containsKey("android")) {
2659                 throw new IllegalStateException(
2660                         "Failed to load frameworks package; check log for warnings");
2661             }
2662
2663             // Collect privileged system packages.
2664             final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
2665             scanDirTracedLI(privilegedAppDir,
2666                     mDefParseFlags
2667                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2668                     scanFlags
2669                     | SCAN_AS_SYSTEM
2670                     | SCAN_AS_PRIVILEGED,
2671                     0);
2672
2673             // Collect ordinary system packages.
2674             final File systemAppDir = new File(Environment.getRootDirectory(), "app");
2675             scanDirTracedLI(systemAppDir,
2676                     mDefParseFlags
2677                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2678                     scanFlags
2679                     | SCAN_AS_SYSTEM,
2680                     0);
2681
2682             // Collect privileged vendor packages.
2683             File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
2684             try {
2685                 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile();
2686             } catch (IOException e) {
2687                 // failed to look up canonical path, continue with original one
2688             }
2689             scanDirTracedLI(privilegedVendorAppDir,
2690                     mDefParseFlags
2691                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2692                     scanFlags
2693                     | SCAN_AS_SYSTEM
2694                     | SCAN_AS_VENDOR
2695                     | SCAN_AS_PRIVILEGED,
2696                     0);
2697
2698             // Collect ordinary vendor packages.
2699             File vendorAppDir = new File(Environment.getVendorDirectory(), "app");
2700             try {
2701                 vendorAppDir = vendorAppDir.getCanonicalFile();
2702             } catch (IOException e) {
2703                 // failed to look up canonical path, continue with original one
2704             }
2705             scanDirTracedLI(vendorAppDir,
2706                     mDefParseFlags
2707                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2708                     scanFlags
2709                     | SCAN_AS_SYSTEM
2710                     | SCAN_AS_VENDOR,
2711                     0);
2712
2713             // Collect privileged odm packages. /odm is another vendor partition
2714             // other than /vendor.
2715             File privilegedOdmAppDir = new File(Environment.getOdmDirectory(),
2716                         "priv-app");
2717             try {
2718                 privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile();
2719             } catch (IOException e) {
2720                 // failed to look up canonical path, continue with original one
2721             }
2722             scanDirTracedLI(privilegedOdmAppDir,
2723                     mDefParseFlags
2724                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2725                     scanFlags
2726                     | SCAN_AS_SYSTEM
2727                     | SCAN_AS_VENDOR
2728                     | SCAN_AS_PRIVILEGED,
2729                     0);
2730
2731             // Collect ordinary odm packages. /odm is another vendor partition
2732             // other than /vendor.
2733             File odmAppDir = new File(Environment.getOdmDirectory(), "app");
2734             try {
2735                 odmAppDir = odmAppDir.getCanonicalFile();
2736             } catch (IOException e) {
2737                 // failed to look up canonical path, continue with original one
2738             }
2739             scanDirTracedLI(odmAppDir,
2740                     mDefParseFlags
2741                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2742                     scanFlags
2743                     | SCAN_AS_SYSTEM
2744                     | SCAN_AS_VENDOR,
2745                     0);
2746
2747             // Collect all OEM packages.
2748             final File oemAppDir = new File(Environment.getOemDirectory(), "app");
2749             scanDirTracedLI(oemAppDir,
2750                     mDefParseFlags
2751                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2752                     scanFlags
2753                     | SCAN_AS_SYSTEM
2754                     | SCAN_AS_OEM,
2755                     0);
2756
2757             // Collected privileged /product packages.
2758             File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
2759             try {
2760                 privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile();
2761             } catch (IOException e) {
2762                 // failed to look up canonical path, continue with original one
2763             }
2764             scanDirTracedLI(privilegedProductAppDir,
2765                     mDefParseFlags
2766                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2767                     scanFlags
2768                     | SCAN_AS_SYSTEM
2769                     | SCAN_AS_PRODUCT
2770                     | SCAN_AS_PRIVILEGED,
2771                     0);
2772
2773             // Collect ordinary /product packages.
2774             File productAppDir = new File(Environment.getProductDirectory(), "app");
2775             try {
2776                 productAppDir = productAppDir.getCanonicalFile();
2777             } catch (IOException e) {
2778                 // failed to look up canonical path, continue with original one
2779             }
2780             scanDirTracedLI(productAppDir,
2781                     mDefParseFlags
2782                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2783                     scanFlags
2784                     | SCAN_AS_SYSTEM
2785                     | SCAN_AS_PRODUCT,
2786                     0);
2787
2788             // Collected privileged /product_services packages.
2789             File privilegedProductServicesAppDir =
2790                     new File(Environment.getProductServicesDirectory(), "priv-app");
2791             try {
2792                 privilegedProductServicesAppDir =
2793                         privilegedProductServicesAppDir.getCanonicalFile();
2794             } catch (IOException e) {
2795                 // failed to look up canonical path, continue with original one
2796             }
2797             scanDirTracedLI(privilegedProductServicesAppDir,
2798                     mDefParseFlags
2799                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2800                     scanFlags
2801                     | SCAN_AS_SYSTEM
2802                     | SCAN_AS_PRODUCT_SERVICES
2803                     | SCAN_AS_PRIVILEGED,
2804                     0);
2805
2806             // Collect ordinary /product_services packages.
2807             File productServicesAppDir = new File(Environment.getProductServicesDirectory(), "app");
2808             try {
2809                 productServicesAppDir = productServicesAppDir.getCanonicalFile();
2810             } catch (IOException e) {
2811                 // failed to look up canonical path, continue with original one
2812             }
2813             scanDirTracedLI(productServicesAppDir,
2814                     mDefParseFlags
2815                     | PackageParser.PARSE_IS_SYSTEM_DIR,
2816                     scanFlags
2817                     | SCAN_AS_SYSTEM
2818                     | SCAN_AS_PRODUCT_SERVICES,
2819                     0);
2820
2821             // Prune any system packages that no longer exist.
2822             final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
2823             // Stub packages must either be replaced with full versions in the /data
2824             // partition or be disabled.
2825             final List<String> stubSystemApps = new ArrayList<>();
2826             if (!mOnlyCore) {
2827                 // do this first before mucking with mPackages for the "expecting better" case
2828                 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator();
2829                 while (pkgIterator.hasNext()) {
2830                     final PackageParser.Package pkg = pkgIterator.next();
2831                     if (pkg.isStub) {
2832                         stubSystemApps.add(pkg.packageName);
2833                     }
2834                 }
2835
2836                 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
2837                 while (psit.hasNext()) {
2838                     PackageSetting ps = psit.next();
2839
2840                     /*
2841                      * If this is not a system app, it can't be a
2842                      * disable system app.
2843                      */
2844                     if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
2845                         continue;
2846                     }
2847
2848                     /*
2849                      * If the package is scanned, it's not erased.
2850                      */
2851                     final PackageParser.Package scannedPkg = mPackages.get(ps.name);
2852                     if (scannedPkg != null) {
2853                         /*
2854                          * If the system app is both scanned and in the
2855                          * disabled packages list, then it must have been
2856                          * added via OTA. Remove it from the currently
2857                          * scanned package so the previously user-installed
2858                          * application can be scanned.
2859                          */
2860                         if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
2861                             logCriticalInfo(Log.WARN,
2862                                     "Expecting better updated system app for " + ps.name
2863                                     + "; removing system app.  Last known"
2864                                     + " codePath=" + ps.codePathString
2865                                     + ", versionCode=" + ps.versionCode
2866                                     + "; scanned versionCode=" + scannedPkg.getLongVersionCode());
2867                             removePackageLI(scannedPkg, true);
2868                             mExpectingBetter.put(ps.name, ps.codePath);
2869                         }
2870
2871                         continue;
2872                     }
2873
2874                     if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
2875                         psit.remove();
2876                         logCriticalInfo(Log.WARN, "System package " + ps.name
2877                                 + " no longer exists; it's data will be wiped");
2878                         // Actual deletion of code and data will be handled by later
2879                         // reconciliation step
2880                     } else {
2881                         // we still have a disabled system package, but, it still might have
2882                         // been removed. check the code path still exists and check there's
2883                         // still a package. the latter can happen if an OTA keeps the same
2884                         // code path, but, changes the package name.
2885                         final PackageSetting disabledPs =
2886                                 mSettings.getDisabledSystemPkgLPr(ps.name);
2887                         if (disabledPs.codePath == null || !disabledPs.codePath.exists()
2888                                 || disabledPs.pkg == null) {
2889                             possiblyDeletedUpdatedSystemApps.add(ps.name);
2890                         } else {
2891                             // We're expecting that the system app should remain disabled, but add
2892                             // it to expecting better to recover in case the data version cannot
2893                             // be scanned.
2894                             mExpectingBetter.put(disabledPs.name, disabledPs.codePath);
2895                         }
2896                     }
2897                 }
2898             }
2899
2900             //delete tmp files
2901             deleteTempPackageFiles();
2902
2903             final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get();
2904
2905             // Remove any shared userIDs that have no associated packages
2906             mSettings.pruneSharedUsersLPw();
2907             final long systemScanTime = SystemClock.uptimeMillis() - startTime;
2908             final int systemPackagesCount = mPackages.size();
2909             Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime
2910                     + " ms, packageCount: " + systemPackagesCount
2911                     + " , timePerPackage: "
2912                     + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount)
2913                     + " , cached: " + cachedSystemApps);
2914             if (mIsUpgrade && systemPackagesCount > 0) {
2915                 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time",
2916                         ((int) systemScanTime) / systemPackagesCount);
2917             }
2918             if (!mOnlyCore) {
2919                 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2920                         SystemClock.uptimeMillis());
2921                 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2922
2923                 // Remove disable package settings for updated system apps that were
2924                 // removed via an OTA. If the update is no longer present, remove the
2925                 // app completely. Otherwise, revoke their system privileges.
2926                 for (int i = possiblyDeletedUpdatedSystemApps.size() - 1; i >= 0; --i) {
2927                     final String packageName = possiblyDeletedUpdatedSystemApps.get(i);
2928                     final PackageParser.Package pkg = mPackages.get(packageName);
2929                     final String msg;
2930
2931                     // remove from the disabled system list; do this first so any future
2932                     // scans of this package are performed without this state
2933                     mSettings.removeDisabledSystemPackageLPw(packageName);
2934
2935                     if (pkg == null) {
2936                         // should have found an update, but, we didn't; remove everything
2937                         msg = "Updated system package " + packageName
2938                                 + " no longer exists; removing its data";
2939                         // Actual deletion of code and data will be handled by later
2940                         // reconciliation step
2941                     } else {
2942                         // found an update; revoke system privileges
2943                         msg = "Updated system package " + packageName
2944                                 + " no longer exists; rescanning package on data";
2945
2946                         // NOTE: We don't do anything special if a stub is removed from the
2947                         // system image. But, if we were [like removing the uncompressed
2948                         // version from the /data partition], this is where it'd be done.
2949
2950                         // remove the package from the system and re-scan it without any
2951                         // special privileges
2952                         removePackageLI(pkg, true);
2953                         try {
2954                             final File codePath = new File(pkg.applicationInfo.getCodePath());
2955                             scanPackageTracedLI(codePath, 0, scanFlags, 0, null);
2956                         } catch (PackageManagerException e) {
2957                             Slog.e(TAG, "Failed to parse updated, ex-system package: "
2958                                     + e.getMessage());
2959                         }
2960                     }
2961
2962                     // one final check. if we still have a package setting [ie. it was
2963                     // previously scanned and known to the system], but, we don't have
2964                     // a package [ie. there was an error scanning it from the /data
2965                     // partition], completely remove the package data.
2966                     final PackageSetting ps = mSettings.mPackages.get(packageName);
2967                     if (ps != null && mPackages.get(packageName) == null) {
2968                         removePackageDataLIF(ps, null, null, 0, false);
2969
2970                     }
2971                     logCriticalInfo(Log.WARN, msg);
2972                 }
2973
2974                 /*
2975                  * Make sure all system apps that we expected to appear on
2976                  * the userdata partition actually showed up. If they never
2977                  * appeared, crawl back and revive the system version.
2978                  */
2979                 for (int i = 0; i < mExpectingBetter.size(); i++) {
2980                     final String packageName = mExpectingBetter.keyAt(i);
2981                     if (!mPackages.containsKey(packageName)) {
2982                         final File scanFile = mExpectingBetter.valueAt(i);
2983
2984                         logCriticalInfo(Log.WARN, "Expected better " + packageName
2985                                 + " but never showed up; reverting to system");
2986
2987                         final @ParseFlags int reparseFlags;
2988                         final @ScanFlags int rescanFlags;
2989                         if (FileUtils.contains(privilegedAppDir, scanFile)) {
2990                             reparseFlags =
2991                                     mDefParseFlags |
2992                                     PackageParser.PARSE_IS_SYSTEM_DIR;
2993                             rescanFlags =
2994                                     scanFlags
2995                                     | SCAN_AS_SYSTEM
2996                                     | SCAN_AS_PRIVILEGED;
2997                         } else if (FileUtils.contains(systemAppDir, scanFile)) {
2998                             reparseFlags =
2999                                     mDefParseFlags |
3000                                     PackageParser.PARSE_IS_SYSTEM_DIR;
3001                             rescanFlags =
3002                                     scanFlags
3003                                     | SCAN_AS_SYSTEM;
3004                         } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)
3005                                 || FileUtils.contains(privilegedOdmAppDir, scanFile)) {
3006                             reparseFlags =
3007                                     mDefParseFlags |
3008                                     PackageParser.PARSE_IS_SYSTEM_DIR;
3009                             rescanFlags =
3010                                     scanFlags
3011                                     | SCAN_AS_SYSTEM
3012                                     | SCAN_AS_VENDOR
3013                                     | SCAN_AS_PRIVILEGED;
3014                         } else if (FileUtils.contains(vendorAppDir, scanFile)
3015                                 || FileUtils.contains(odmAppDir, scanFile)) {
3016                             reparseFlags =
3017                                     mDefParseFlags |
3018                                     PackageParser.PARSE_IS_SYSTEM_DIR;
3019                             rescanFlags =
3020                                     scanFlags
3021                                     | SCAN_AS_SYSTEM
3022                                     | SCAN_AS_VENDOR;
3023                         } else if (FileUtils.contains(oemAppDir, scanFile)) {
3024                             reparseFlags =
3025                                     mDefParseFlags |
3026                                     PackageParser.PARSE_IS_SYSTEM_DIR;
3027                             rescanFlags =
3028                                     scanFlags
3029                                     | SCAN_AS_SYSTEM
3030                                     | SCAN_AS_OEM;
3031                         } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) {
3032                             reparseFlags =
3033                                     mDefParseFlags |
3034                                     PackageParser.PARSE_IS_SYSTEM_DIR;
3035                             rescanFlags =
3036                                     scanFlags
3037                                     | SCAN_AS_SYSTEM
3038                                     | SCAN_AS_PRODUCT
3039                                     | SCAN_AS_PRIVILEGED;
3040                         } else if (FileUtils.contains(productAppDir, scanFile)) {
3041                             reparseFlags =
3042                                     mDefParseFlags |
3043                                     PackageParser.PARSE_IS_SYSTEM_DIR;
3044                             rescanFlags =
3045                                     scanFlags
3046                                     | SCAN_AS_SYSTEM
3047                                     | SCAN_AS_PRODUCT;
3048                         } else if (FileUtils.contains(privilegedProductServicesAppDir, scanFile)) {
3049                             reparseFlags =
3050                                     mDefParseFlags |
3051                                     PackageParser.PARSE_IS_SYSTEM_DIR;
3052                             rescanFlags =
3053                                     scanFlags
3054                                     | SCAN_AS_SYSTEM
3055                                     | SCAN_AS_PRODUCT_SERVICES
3056                                     | SCAN_AS_PRIVILEGED;
3057                         } else if (FileUtils.contains(productServicesAppDir, scanFile)) {
3058                             reparseFlags =
3059                                     mDefParseFlags |
3060                                     PackageParser.PARSE_IS_SYSTEM_DIR;
3061                             rescanFlags =
3062                                     scanFlags
3063                                     | SCAN_AS_SYSTEM
3064                                     | SCAN_AS_PRODUCT_SERVICES;
3065                         } else {
3066                             Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
3067                             continue;
3068                         }
3069
3070                         mSettings.enableSystemPackageLPw(packageName);
3071
3072                         try {
3073                             scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
3074                         } catch (PackageManagerException e) {
3075                             Slog.e(TAG, "Failed to parse original system package: "
3076                                     + e.getMessage());
3077                         }
3078                     }
3079                 }
3080
3081                 // Uncompress and install any stubbed system applications.
3082                 // This must be done last to ensure all stubs are replaced or disabled.
3083                 installSystemStubPackages(stubSystemApps, scanFlags);
3084
3085                 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get()
3086                                 - cachedSystemApps;
3087
3088                 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime;
3089                 final int dataPackagesCount = mPackages.size() - systemPackagesCount;
3090                 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime
3091                         + " ms, packageCount: " + dataPackagesCount
3092                         + " , timePerPackage: "
3093                         + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount)
3094                         + " , cached: " + cachedNonSystemApps);
3095                 if (mIsUpgrade && dataPackagesCount > 0) {
3096                     MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time",
3097                             ((int) dataScanTime) / dataPackagesCount);
3098                 }
3099             }
3100             mExpectingBetter.clear();
3101
3102             // Resolve the storage manager.
3103             mStorageManagerPackage = getStorageManagerPackageName();
3104
3105             // Resolve protected action filters. Only the setup wizard is allowed to
3106             // have a high priority filter for these actions.
3107             mSetupWizardPackage = getSetupWizardPackageName();
3108             mComponentResolver.fixProtectedFilterPriorities();
3109
3110             mSystemTextClassifierPackage = getSystemTextClassifierPackageName();
3111
3112             mWellbeingPackage = getWellbeingPackageName();
3113             mDocumenterPackage = getDocumenterPackageName();
3114             mConfiguratorPackage =
3115                     mContext.getString(R.string.config_deviceConfiguratorPackageName);
3116             mAppPredictionServicePackage = getAppPredictionServicePackageName();
3117             mIncidentReportApproverPackage = getIncidentReportApproverPackageName();
3118
3119             // Now that we know all of the shared libraries, update all clients to have
3120             // the correct library paths.
3121             updateAllSharedLibrariesLocked(null, Collections.unmodifiableMap(mPackages));
3122
3123             for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
3124                 // NOTE: We ignore potential failures here during a system scan (like
3125                 // the rest of the commands above) because there's precious little we
3126                 // can do about it. A settings error is reported, though.
3127                 final List<String> changedAbiCodePath =
3128                         adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/);
3129                 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
3130                     for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
3131                         final String codePathString = changedAbiCodePath.get(i);
3132                         try {
3133                             mInstaller.rmdex(codePathString,
3134                                     getDexCodeInstructionSet(getPreferredInstructionSet()));
3135                         } catch (InstallerException ignored) {
3136                         }
3137                     }
3138                 }
3139                 // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same
3140                 // SELinux domain.
3141                 setting.fixSeInfoLocked();
3142             }
3143
3144             // Now that we know all the packages we are keeping,
3145             // read and update their last usage times.
3146             mPackageUsage.read(mPackages);
3147             mCompilerStats.read();
3148
3149             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
3150                     SystemClock.uptimeMillis());
3151             Slog.i(TAG, "Time to scan packages: "
3152                     + ((SystemClock.uptimeMillis()-startTime)/1000f)
3153                     + " seconds");
3154
3155             // If the platform SDK has changed since the last time we booted,
3156             // we need to re-grant app permission to catch any new ones that
3157             // appear.  This is really a hack, and means that apps can in some
3158             // cases get permissions that the user didn't initially explicitly
3159             // allow...  it would be nice to have some better way to handle
3160             // this situation.
3161             final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
3162             if (sdkUpdated) {
3163                 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
3164                         + mSdkVersion + "; regranting permissions for internal storage");
3165             }
3166             mPermissionManager.updateAllPermissions(
3167                     StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(),
3168                     mPermissionCallback);
3169             ver.sdkVersion = mSdkVersion;
3170
3171             // If this is the first boot or an update from pre-M, and it is a normal
3172             // boot, then we need to initialize the default preferred apps across
3173             // all defined users.
3174             if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) {
3175                 for (UserInfo user : sUserManager.getUsers(true)) {
3176                     mSettings.applyDefaultPreferredAppsLPw(user.id);
3177                     primeDomainVerificationsLPw(user.id);
3178                 }
3179             }
3180
3181             // Prepare storage for system user really early during boot,
3182             // since core system apps like SettingsProvider and SystemUI
3183             // can't wait for user to start
3184             final int storageFlags;
3185             if (StorageManager.isFileEncryptedNativeOrEmulated()) {
3186                 storageFlags = StorageManager.FLAG_STORAGE_DE;
3187             } else {
3188                 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
3189             }
3190             List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
3191                     UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
3192                     true /* onlyCoreApps */);
3193             mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> {
3194                 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
3195                         Trace.TRACE_TAG_PACKAGE_MANAGER);
3196                 traceLog.traceBegin("AppDataFixup");
3197                 try {
3198                     mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
3199                             StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
3200                 } catch (InstallerException e) {
3201                     Slog.w(TAG, "Trouble fixing GIDs", e);
3202                 }
3203                 traceLog.traceEnd();
3204
3205                 traceLog.traceBegin("AppDataPrepare");
3206                 if (deferPackages == null || deferPackages.isEmpty()) {
3207                     return;
3208                 }
3209                 int count = 0;
3210                 for (String pkgName : deferPackages) {
3211                     PackageParser.Package pkg = null;
3212                     synchronized (mPackages) {
3213                         PackageSetting ps = mSettings.getPackageLPr(pkgName);
3214                         if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) {
3215                             pkg = ps.pkg;
3216                         }
3217                     }
3218                     if (pkg != null) {
3219                         synchronized (mInstallLock) {
3220                             prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags,
3221                                     true /* maybeMigrateAppData */);
3222                         }
3223                         count++;
3224                     }
3225                 }
3226                 traceLog.traceEnd();
3227                 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages");
3228             }, "prepareAppData");
3229
3230             // If this is first boot after an OTA, and a normal boot, then
3231             // we need to clear code cache directories.
3232             // Note that we do *not* clear the application profiles. These remain valid
3233             // across OTAs and are used to drive profile verification (post OTA) and
3234             // profile compilation (without waiting to collect a fresh set of profiles).
3235             if (mIsUpgrade && !onlyCore) {
3236                 Slog.i(TAG, "Build fingerprint changed; clearing code caches");
3237                 for (int i = 0; i < mSettings.mPackages.size(); i++) {
3238                     final PackageSetting ps = mSettings.mPackages.valueAt(i);
3239                     if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
3240                         // No apps are running this early, so no need to freeze
3241                         clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
3242                                 FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL
3243                                         | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3244                     }
3245                 }
3246                 ver.fingerprint = Build.FINGERPRINT;
3247             }
3248
3249             // Grandfather existing (installed before Q) non-system apps to hide
3250             // their icons in launcher.
3251             if (!onlyCore && mIsPreQUpgrade) {
3252                 Slog.i(TAG, "Whitelisting all existing apps to hide their icons");
3253                 int size = mSettings.mPackages.size();
3254                 for (int i = 0; i < size; i++) {
3255                     final PackageSetting ps = mSettings.mPackages.valueAt(i);
3256                     if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
3257                         continue;
3258                     }
3259                     ps.disableComponentLPw(PackageManager.APP_DETAILS_ACTIVITY_CLASS_NAME,
3260                             UserHandle.USER_SYSTEM);
3261                 }
3262             }
3263
3264             // clear only after permissions and other defaults have been updated
3265             mExistingSystemPackages.clear();
3266             mPromoteSystemApps = false;
3267
3268             // All the changes are done during package scanning.
3269             ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
3270
3271             // can downgrade to reader
3272             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings");
3273             mSettings.writeLPr();
3274             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3275             EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
3276                     SystemClock.uptimeMillis());
3277
3278             if (!mOnlyCore) {
3279                 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
3280                 mRequiredInstallerPackage = getRequiredInstallerLPr();
3281                 mRequiredUninstallerPackage = getRequiredUninstallerLPr();
3282                 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
3283                 if (mIntentFilterVerifierComponent != null) {
3284                     mIntentFilterVerifier = new IntentVerifierProxy(mContext,
3285                             mIntentFilterVerifierComponent);
3286                 } else {
3287                     mIntentFilterVerifier = null;
3288                 }
3289                 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3290                         PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES,
3291                         SharedLibraryInfo.VERSION_UNDEFINED);
3292                 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
3293                         PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
3294                         SharedLibraryInfo.VERSION_UNDEFINED);
3295             } else {
3296                 mRequiredVerifierPackage = null;
3297                 mRequiredInstallerPackage = null;
3298                 mRequiredUninstallerPackage = null;
3299                 mIntentFilterVerifierComponent = null;
3300                 mIntentFilterVerifier = null;
3301                 mServicesSystemSharedLibraryPackageName = null;
3302                 mSharedSystemSharedLibraryPackageName = null;
3303             }
3304             // PermissionController hosts default permission granting and role management, so it's a
3305             // critical part of the core system.
3306             mRequiredPermissionControllerPackage = getRequiredPermissionControllerLPr();
3307
3308             // Initialize InstantAppRegistry's Instant App list for all users.
3309             final int[] userIds = UserManagerService.getInstance().getUserIds();
3310             for (PackageParser.Package pkg : mPackages.values()) {
3311                 if (pkg.isSystem()) {
3312                     continue;
3313                 }
3314                 for (int userId : userIds) {
3315                     final PackageSetting ps = (PackageSetting) pkg.mExtras;
3316                     if (ps == null || !ps.getInstantApp(userId) || !ps.getInstalled(userId)) {
3317                         continue;
3318                     }
3319                     mInstantAppRegistry.addInstantAppLPw(userId, ps.appId);
3320                 }
3321             }
3322
3323             mInstallerService = new PackageInstallerService(context, this, mApexManager);
3324             final Pair<ComponentName, String> instantAppResolverComponent =
3325                     getInstantAppResolverLPr();
3326             if (instantAppResolverComponent != null) {
3327                 if (DEBUG_INSTANT) {
3328                     Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent);
3329                 }
3330                 mInstantAppResolverConnection = new InstantAppResolverConnection(
3331                         mContext, instantAppResolverComponent.first,
3332                         instantAppResolverComponent.second);
3333                 mInstantAppResolverSettingsComponent =
3334                         getInstantAppResolverSettingsLPr(instantAppResolverComponent.first);
3335             } else {
3336                 mInstantAppResolverConnection = null;
3337                 mInstantAppResolverSettingsComponent = null;
3338             }
3339             updateInstantAppInstallerLocked(null);
3340
3341             // Read and update the usage of dex files.
3342             // Do this at the end of PM init so that all the packages have their
3343             // data directory reconciled.
3344             // At this point we know the code paths of the packages, so we can validate
3345             // the disk file and build the internal cache.
3346             // The usage file is expected to be small so loading and verifying it
3347             // should take a fairly small time compare to the other activities (e.g. package
3348             // scanning).
3349             final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
3350             for (int userId : userIds) {
3351                 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
3352             }
3353             mDexManager.load(userPackages);
3354             if (mIsUpgrade) {
3355                 MetricsLogger.histogram(null, "ota_package_manager_init_time",
3356                         (int) (SystemClock.uptimeMillis() - startTime));
3357             }
3358         } // synchronized (mPackages)
3359         } // synchronized (mInstallLock)
3360
3361         mModuleInfoProvider = new ModuleInfoProvider(mContext, this);
3362
3363         // Now after opening every single application zip, make sure they
3364         // are all flushed.  Not really needed, but keeps things nice and
3365         // tidy.
3366         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC");
3367         Runtime.getRuntime().gc();
3368         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3369
3370         // The initial scanning above does many calls into installd while
3371         // holding the mPackages lock, but we're mostly interested in yelling
3372         // once we have a booted system.
3373         mInstaller.setWarnIfHeld(mPackages);
3374
3375         PackageParser.readConfigUseRoundIcon(mContext.getResources());
3376
3377         mServiceStartWithDelay = SystemClock.uptimeMillis() + (60 * 1000L);
3378
3379         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
3380     }
3381
3382     /**
3383      * Uncompress and install stub applications.
3384      * <p>In order to save space on the system partition, some applications are shipped in a
3385      * compressed form. In addition the compressed bits for the full application, the
3386      * system image contains a tiny stub comprised of only the Android manifest.
3387      * <p>During the first boot, attempt to uncompress and install the full application. If
3388      * the application can't be installed for any reason, disable the stub and prevent
3389      * uncompressing the full application during future boots.
3390      * <p>In order to forcefully attempt an installation of a full application, go to app
3391      * settings and enable the application.
3392      */
3393     private void installSystemStubPackages(@NonNull List<String> systemStubPackageNames,
3394             @ScanFlags int scanFlags) {
3395         for (int i = systemStubPackageNames.size() - 1; i >= 0; --i) {
3396             final String packageName = systemStubPackageNames.get(i);
3397             // skip if the system package is already disabled
3398             if (mSettings.isDisabledSystemPackageLPr(packageName)) {
3399                 systemStubPackageNames.remove(i);
3400                 continue;
3401             }
3402             // skip if the package isn't installed (?!); this should never happen
3403             final PackageParser.Package pkg = mPackages.get(packageName);
3404             if (pkg == null) {
3405                 systemStubPackageNames.remove(i);
3406                 continue;
3407             }
3408             // skip if the package has been disabled by the user
3409             final PackageSetting ps = mSettings.mPackages.get(packageName);
3410             if (ps != null) {
3411                 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM);
3412                 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) {
3413                     systemStubPackageNames.remove(i);
3414                     continue;
3415                 }
3416             }
3417
3418             // install the package to replace the stub on /system
3419             try {
3420                 installStubPackageLI(pkg, 0, scanFlags);
3421                 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
3422                         UserHandle.USER_SYSTEM, "android");
3423                 systemStubPackageNames.remove(i);
3424             } catch (PackageManagerException e) {
3425                 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage());
3426             }
3427
3428             // any failed attempt to install the package will be cleaned up later
3429         }
3430
3431         // disable any stub still left; these failed to install the full application
3432         for (int i = systemStubPackageNames.size() - 1; i >= 0; --i) {
3433             final String pkgName = systemStubPackageNames.get(i);
3434             final PackageSetting ps = mSettings.mPackages.get(pkgName);
3435             ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
3436                     UserHandle.USER_SYSTEM, "android");
3437             logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName);
3438         }
3439     }
3440
3441     /**
3442      * Extract, install and enable a stub package.
3443      * <p>If the compressed file can not be extracted / installed for any reason, the stub
3444      * APK will be installed and the package will be disabled. To recover from this situation,
3445      * the user will need to go into system settings and re-enable the package.
3446      */
3447     private boolean enableCompressedPackage(PackageParser.Package stubPkg) {
3448         final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
3449                 | PackageParser.PARSE_ENFORCE_CODE;
3450         synchronized (mInstallLock) {
3451             final PackageParser.Package pkg;
3452             try (PackageFreezer freezer =
3453                     freezePackage(stubPkg.packageName, "setEnabledSetting")) {
3454                 pkg = installStubPackageLI(stubPkg, parseFlags, 0 /*scanFlags*/);
3455                 synchronized (mPackages) {
3456                     prepareAppDataAfterInstallLIF(pkg);
3457                     try {
3458                         updateSharedLibrariesLocked(pkg, null, mPackages);
3459                     } catch (PackageManagerException e) {
3460                         Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e);
3461                     }
3462                     mPermissionManager.updatePermissions(
3463                             pkg.packageName, pkg, true, mPackages.values(),
3464                             mPermissionCallback);
3465                     mSettings.writeLPr();
3466                 }
3467             } catch (PackageManagerException e) {
3468                 // Whoops! Something went very wrong; roll back to the stub and disable the package
3469                 try (PackageFreezer freezer =
3470                         freezePackage(stubPkg.packageName, "setEnabledSetting")) {
3471                     synchronized (mPackages) {
3472                         // NOTE: Ensure the system package is enabled; even for a compressed stub.
3473                         // If we don't, installing the system package fails during scan
3474                         enableSystemPackageLPw(stubPkg);
3475                     }
3476                     installPackageFromSystemLIF(stubPkg.codePath,
3477                             null /*allUserHandles*/, null /*origUserHandles*/,
3478                             null /*origPermissionsState*/, true /*writeSettings*/);
3479                 } catch (PackageManagerException pme) {
3480                     // Serious WTF; we have to be able to install the stub
3481                     Slog.wtf(TAG, "Failed to restore system package:" + stubPkg.packageName, pme);
3482                 } finally {
3483                     // Disable the package; the stub by itself is not runnable
3484                     synchronized (mPackages) {
3485                         final PackageSetting stubPs = mSettings.mPackages.get(stubPkg.packageName);
3486                         if (stubPs != null) {
3487                             stubPs.setEnabled(COMPONENT_ENABLED_STATE_DISABLED,
3488                                     UserHandle.USER_SYSTEM, "android");
3489                         }
3490                         mSettings.writeLPr();
3491                     }
3492                 }
3493                 return false;
3494             }
3495             clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE | FLAG_STORAGE_CE
3496                     | FLAG_STORAGE_EXTERNAL | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
3497             mDexManager.notifyPackageUpdated(pkg.packageName,
3498                     pkg.baseCodePath, pkg.splitCodePaths);
3499         }
3500         return true;
3501     }
3502
3503     private PackageParser.Package installStubPackageLI(PackageParser.Package stubPkg,
3504             @ParseFlags int parseFlags, @ScanFlags int scanFlags)
3505                     throws PackageManagerException {
3506         if (DEBUG_COMPRESSION) {
3507             Slog.i(TAG, "Uncompressing system stub; pkg: " + stubPkg.packageName);
3508         }
3509         // uncompress the binary to its eventual destination on /data
3510         final File scanFile = decompressPackage(stubPkg.packageName, stubPkg.codePath);
3511         if (scanFile == null) {
3512             throw new PackageManagerException("Unable to decompress stub at " + stubPkg.codePath);
3513         }
3514         synchronized (mPackages) {
3515             mSettings.disableSystemPackageLPw(stubPkg.packageName, true /*replaced*/);
3516         }
3517         removePackageLI(stubPkg, true /*chatty*/);
3518         try {
3519             return scanPackageTracedLI(scanFile, parseFlags, scanFlags, 0, null);
3520         } catch (PackageManagerException e) {
3521             Slog.w(TAG, "Failed to install compressed system package:" + stubPkg.packageName, e);
3522             // Remove the failed install
3523             removeCodePathLI(scanFile);
3524             throw e;
3525         }
3526     }
3527
3528     /**
3529      * Decompresses the given package on the system image onto
3530      * the /data partition.
3531      * @return The directory the package was decompressed into. Otherwise, {@code null}.
3532      */
3533     private File decompressPackage(String packageName, String codePath) {
3534         final File[] compressedFiles = getCompressedFiles(codePath);
3535         if (compressedFiles == null || compressedFiles.length == 0) {
3536             if (DEBUG_COMPRESSION) {
3537                 Slog.i(TAG, "No files to decompress: " + codePath);
3538             }
3539             return null;
3540         }
3541         final File dstCodePath =
3542                 getNextCodePath(Environment.getDataAppDirectory(null), packageName);
3543         int ret = PackageManager.INSTALL_SUCCEEDED;
3544         try {
3545             Os.mkdir(dstCodePath.getAbsolutePath(), 0755);
3546             Os.chmod(dstCodePath.getAbsolutePath(), 0755);
3547             for (File srcFile : compressedFiles) {
3548                 final String srcFileName = srcFile.getName();
3549                 final String dstFileName = srcFileName.substring(
3550                         0, srcFileName.length() - COMPRESSED_EXTENSION.length());
3551                 final File dstFile = new File(dstCodePath, dstFileName);
3552                 ret = decompressFile(srcFile, dstFile);
3553                 if (ret != PackageManager.INSTALL_SUCCEEDED) {
3554                     logCriticalInfo(Log.ERROR, "Failed to decompress"
3555                             + "; pkg: " + packageName
3556                             + ", file: " + dstFileName);
3557                     break;
3558                 }
3559             }
3560         } catch (ErrnoException e) {
3561             logCriticalInfo(Log.ERROR, "Failed to decompress"
3562                     + "; pkg: " + packageName
3563                     + ", err: " + e.errno);
3564         }
3565         if (ret == PackageManager.INSTALL_SUCCEEDED) {
3566             final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME);
3567             NativeLibraryHelper.Handle handle = null;
3568             try {
3569                 handle = NativeLibraryHelper.Handle.create(dstCodePath);
3570                 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
3571                         null /*abiOverride*/);
3572             } catch (IOException e) {
3573                 logCriticalInfo(Log.ERROR, "Failed to extract native libraries"
3574                         + "; pkg: " + packageName);
3575                 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
3576             } finally {
3577                 IoUtils.closeQuietly(handle);
3578             }
3579         }
3580         if (ret != PackageManager.INSTALL_SUCCEEDED) {
3581             if (!dstCodePath.exists()) {
3582                 return null;
3583             }
3584             removeCodePathLI(dstCodePath);
3585             return null;
3586         }
3587
3588         return dstCodePath;
3589     }
3590
3591     @GuardedBy("mPackages")
3592     private void updateInstantAppInstallerLocked(String modifiedPackage) {
3593         // we're only interested in updating the installer appliction when 1) it's not
3594         // already set or 2) the modified package is the installer
3595         if (mInstantAppInstallerActivity != null
3596                 && !mInstantAppInstallerActivity.getComponentName().getPackageName()
3597                         .equals(modifiedPackage)) {
3598             return;
3599         }
3600         setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr());
3601     }
3602
3603     private static @Nullable File preparePackageParserCache() {
3604         if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) {
3605             return null;
3606         }
3607
3608         // Disable package parsing on eng builds to allow for faster incremental development.
3609         if (Build.IS_ENG) {
3610             return null;
3611         }
3612
3613         if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) {
3614             Slog.i(TAG, "Disabling package parser cache due to system property.");
3615             return null;
3616         }
3617
3618         // The base directory for the package parser cache lives under /data/system/.
3619         final File cacheBaseDir = Environment.getPackageCacheDirectory();
3620         if (!FileUtils.createDir(cacheBaseDir)) {
3621             return null;
3622         }
3623
3624         // There are several items that need to be combined together to safely
3625         // identify cached items. In particular, changing the value of certain
3626         // feature flags should cause us to invalidate any caches.
3627         final String cacheName = SystemProperties.digestOf(
3628                 "ro.build.fingerprint",
3629                 StorageManager.PROP_ISOLATED_STORAGE,
3630                 StorageManager.PROP_ISOLATED_STORAGE_SNAPSHOT);
3631
3632         // Reconcile cache directories, keeping only what we'd actually use.
3633         for (File cacheDir : FileUtils.listFilesOrEmpty(cacheBaseDir)) {
3634             if (Objects.equals(cacheName, cacheDir.getName())) {
3635                 Slog.d(TAG, "Keeping known cache " + cacheDir.getName());
3636             } else {
3637                 Slog.d(TAG, "Destroying unknown cache " + cacheDir.getName());
3638                 FileUtils.deleteContentsAndDir(cacheDir);
3639             }
3640         }
3641
3642         // Return the versioned package cache directory.
3643         File cacheDir = FileUtils.createDir(cacheBaseDir, cacheName);
3644
3645         if (cacheDir == null) {
3646             // Something went wrong. Attempt to delete everything and return.
3647             Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir);
3648             FileUtils.deleteContentsAndDir(cacheBaseDir);
3649             return null;
3650         }
3651
3652         // The following is a workaround to aid development on non-numbered userdebug
3653         // builds or cases where "adb sync" is used on userdebug builds. If we detect that
3654         // the system partition is newer.
3655         //
3656         // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build
3657         // that starts with "eng." to signify that this is an engineering build and not
3658         // destined for release.
3659         if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) {
3660             Slog.w(TAG, "Wiping cache directory because the system partition changed.");
3661
3662             // Heuristic: If the /system directory has been modified recently due to an "adb sync"
3663             // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable
3664             // in general and should not be used for production changes. In this specific case,
3665             // we know that they will work.
3666             File frameworkDir = new File(Environment.getRootDirectory(), "framework");
3667             if (cacheDir.lastModified() < frameworkDir.lastModified()) {
3668                 FileUtils.deleteContents(cacheBaseDir);
3669                 cacheDir = FileUtils.createDir(cacheBaseDir, cacheName);
3670             }
3671         }
3672
3673         return cacheDir;
3674     }
3675
3676     @Override
3677     public boolean isFirstBoot() {
3678         // allow instant applications
3679         return mFirstBoot;
3680     }
3681
3682     @Override
3683     public boolean isOnlyCoreApps() {
3684         // allow instant applications
3685         return mOnlyCore;
3686     }
3687
3688     @Override
3689     public boolean isDeviceUpgrading() {
3690         // allow instant applications
3691         // The system property allows testing ota flow when upgraded to the same image.
3692         return mIsUpgrade || SystemProperties.getBoolean(
3693                 "persist.pm.mock-upgrade", false /* default */);
3694     }
3695
3696     private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() {
3697         final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
3698
3699         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3700                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3701                 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3702         if (matches.size() == 1) {
3703             return matches.get(0).getComponentInfo().packageName;
3704         } else if (matches.size() == 0) {
3705             Log.e(TAG, "There should probably be a verifier, but, none were found");
3706             return null;
3707         }
3708         throw new RuntimeException("There must be exactly one verifier; found " + matches);
3709     }
3710
3711     private @NonNull String getRequiredSharedLibraryLPr(String name, int version) {
3712         synchronized (mPackages) {
3713             SharedLibraryInfo libraryInfo = getSharedLibraryInfoLPr(name, version);
3714             if (libraryInfo == null) {
3715                 throw new IllegalStateException("Missing required shared library:" + name);
3716             }
3717             String packageName = libraryInfo.getPackageName();
3718             if (packageName == null) {
3719                 throw new IllegalStateException("Expected a package for shared library " + name);
3720             }
3721             return packageName;
3722         }
3723     }
3724
3725     private @NonNull String getRequiredInstallerLPr() {
3726         final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
3727         intent.addCategory(Intent.CATEGORY_DEFAULT);
3728         intent.setDataAndType(Uri.parse("content://com.example/foo.apk"), PACKAGE_MIME_TYPE);
3729
3730         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3731                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3732                 UserHandle.USER_SYSTEM);
3733         if (matches.size() == 1) {
3734             ResolveInfo resolveInfo = matches.get(0);
3735             if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3736                 throw new RuntimeException("The installer must be a privileged app");
3737             }
3738             return matches.get(0).getComponentInfo().packageName;
3739         } else {
3740             throw new RuntimeException("There must be exactly one installer; found " + matches);
3741         }
3742     }
3743
3744     private @NonNull String getRequiredUninstallerLPr() {
3745         final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
3746         intent.addCategory(Intent.CATEGORY_DEFAULT);
3747         intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null));
3748
3749         final ResolveInfo resolveInfo = resolveIntent(intent, null,
3750                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3751                 UserHandle.USER_SYSTEM);
3752         if (resolveInfo == null ||
3753                 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) {
3754             throw new RuntimeException("There must be exactly one uninstaller; found "
3755                     + resolveInfo);
3756         }
3757         return resolveInfo.getComponentInfo().packageName;
3758     }
3759
3760     private @NonNull String getRequiredPermissionControllerLPr() {
3761         final Intent intent = new Intent(Intent.ACTION_MANAGE_PERMISSIONS);
3762         intent.addCategory(Intent.CATEGORY_DEFAULT);
3763
3764         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
3765                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3766                 UserHandle.USER_SYSTEM);
3767         if (matches.size() == 1) {
3768             ResolveInfo resolveInfo = matches.get(0);
3769             if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) {
3770                 throw new RuntimeException("The permissions manager must be a privileged app");
3771             }
3772             return matches.get(0).getComponentInfo().packageName;
3773         } else {
3774             throw new RuntimeException("There must be exactly one permissions manager; found "
3775                     + matches);
3776         }
3777     }
3778
3779     private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() {
3780         final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
3781
3782         final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE,
3783                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
3784                 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/);
3785         ResolveInfo best = null;
3786         final int N = matches.size();
3787         for (int i = 0; i < N; i++) {
3788             final ResolveInfo cur = matches.get(i);
3789             final String packageName = cur.getComponentInfo().packageName;
3790             if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
3791                     packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) {
3792                 continue;
3793             }
3794
3795             if (best == null || cur.priority > best.priority) {
3796                 best = cur;
3797             }
3798         }
3799
3800         if (best != null) {
3801             return best.getComponentInfo().getComponentName();
3802         }
3803         Slog.w(TAG, "Intent filter verifier not found");
3804         return null;
3805     }
3806
3807     @Override
3808     public @Nullable ComponentName getInstantAppResolverComponent() {
3809         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
3810             return null;
3811         }
3812         synchronized (mPackages) {
3813             final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr();
3814             if (instantAppResolver == null) {
3815                 return null;
3816             }
3817             return instantAppResolver.first;
3818         }
3819     }
3820
3821     private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() {
3822         final String[] packageArray =
3823                 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage);
3824         if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) {
3825             if (DEBUG_INSTANT) {
3826                 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list");
3827             }
3828             return null;
3829         }
3830
3831         final int callingUid = Binder.getCallingUid();
3832         final int resolveFlags =
3833                 MATCH_DIRECT_BOOT_AWARE
3834                 | MATCH_DIRECT_BOOT_UNAWARE
3835                 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0);
3836         String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE;
3837         final Intent resolverIntent = new Intent(actionName);
3838         List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null,
3839                 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/);
3840         final int N = resolvers.size();
3841         if (N == 0) {
3842             if (DEBUG_INSTANT) {
3843                 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters");
3844             }
3845             return null;
3846         }
3847
3848         final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray));
3849         for (int i = 0; i < N; i++) {
3850             final ResolveInfo info = resolvers.get(i);
3851
3852             if (info.serviceInfo == null) {
3853                 continue;
3854             }
3855
3856             final String packageName = info.serviceInfo.packageName;
3857             if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) {
3858                 if (DEBUG_INSTANT) {
3859                     Slog.d(TAG, "Ephemeral resolver not in allowed package list;"
3860                             + " pkg: " + packageName + ", info:" + info);
3861                 }
3862                 continue;
3863             }
3864
3865             if (DEBUG_INSTANT) {
3866                 Slog.v(TAG, "Ephemeral resolver found;"
3867                         + " pkg: " + packageName + ", info:" + info);
3868             }
3869             return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName);
3870         }
3871         if (DEBUG_INSTANT) {
3872             Slog.v(TAG, "Ephemeral resolver NOT found");
3873         }
3874         return null;
3875     }
3876
3877     @GuardedBy("mPackages")
3878     private @Nullable ActivityInfo getInstantAppInstallerLPr() {
3879         String[] orderedActions = Build.IS_ENG
3880                 ? new String[]{
3881                         Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST",
3882                         Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}
3883                 : new String[]{
3884                         Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE};
3885
3886         final int resolveFlags =
3887                 MATCH_DIRECT_BOOT_AWARE
3888                         | MATCH_DIRECT_BOOT_UNAWARE
3889                         | Intent.FLAG_IGNORE_EPHEMERAL
3890                         | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0);
3891         final Intent intent = new Intent();
3892         intent.addCategory(Intent.CATEGORY_DEFAULT);
3893         intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE);
3894         List<ResolveInfo> matches = null;
3895         for (String action : orderedActions) {
3896             intent.setAction(action);
3897             matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE,
3898                     resolveFlags, UserHandle.USER_SYSTEM);
3899             if (matches.isEmpty()) {
3900                 if (DEBUG_INSTANT) {
3901                     Slog.d(TAG, "Instant App installer not found with " + action);
3902                 }
3903             } else {
3904                 break;
3905             }
3906         }
3907         Iterator<ResolveInfo> iter = matches.iterator();
3908         while (iter.hasNext()) {
3909             final ResolveInfo rInfo = iter.next();
3910             final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName);
3911             if (ps != null) {
3912                 final PermissionsState permissionsState = ps.getPermissionsState();
3913                 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)
3914                         || Build.IS_ENG) {
3915                     continue;
3916                 }
3917             }
3918             iter.remove();
3919         }
3920         if (matches.size() == 0) {
3921             return null;
3922         } else if (matches.size() == 1) {
3923             return (ActivityInfo) matches.get(0).getComponentInfo();
3924         } else {
3925             throw new RuntimeException(
3926                     "There must be at most one ephemeral installer; found " + matches);
3927         }
3928     }
3929
3930     private @Nullable ComponentName getInstantAppResolverSettingsLPr(
3931             @NonNull ComponentName resolver) {
3932         final Intent intent =  new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS)
3933                 .addCategory(Intent.CATEGORY_DEFAULT)
3934                 .setPackage(resolver.getPackageName());
3935         final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
3936         List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags,
3937                 UserHandle.USER_SYSTEM);
3938         if (matches.isEmpty()) {
3939             return null;
3940         }
3941         return matches.get(0).getComponentInfo().getComponentName();
3942     }
3943
3944     @GuardedBy("mPackages")
3945     private void primeDomainVerificationsLPw(int userId) {
3946         if (DEBUG_DOMAIN_VERIFICATION) {
3947             Slog.d(TAG, "Priming domain verifications in user " + userId);
3948         }
3949
3950         SystemConfig systemConfig = SystemConfig.getInstance();
3951         ArraySet<String> packages = systemConfig.getLinkedApps();
3952
3953         for (String packageName : packages) {
3954             PackageParser.Package pkg = mPackages.get(packageName);
3955             if (pkg != null) {
3956                 if (!pkg.isSystem()) {
3957                     Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>");
3958                     continue;
3959                 }
3960
3961                 ArraySet<String> domains = null;
3962                 for (PackageParser.Activity a : pkg.activities) {
3963                     for (ActivityIntentInfo filter : a.intents) {
3964                         if (hasValidDomains(filter)) {
3965                             if (domains == null) {
3966                                 domains = new ArraySet<>();
3967                             }
3968                             domains.addAll(filter.getHostsList());
3969                         }
3970                     }
3971                 }
3972
3973                 if (domains != null && domains.size() > 0) {
3974                     if (DEBUG_DOMAIN_VERIFICATION) {
3975                         Slog.v(TAG, "      + " + packageName);
3976                     }
3977                     // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual
3978                     // state w.r.t. the formal app-linkage "no verification attempted" state;
3979                     // and then 'always' in the per-user state actually used for intent resolution.
3980                     final IntentFilterVerificationInfo ivi;
3981                     ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains);
3982                     ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
3983                     mSettings.updateIntentFilterVerificationStatusLPw(packageName,
3984                             INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId);
3985                 } else {
3986                     Slog.w(TAG, "Sysconfig <app-link> package '" + packageName
3987                             + "' does not handle web links");
3988                 }
3989             } else {
3990                 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>");
3991             }
3992         }
3993
3994         scheduleWritePackageRestrictionsLocked(userId);
3995         scheduleWriteSettingsLocked();
3996     }
3997
3998     private boolean packageIsBrowser(String packageName, int userId) {
3999         List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null,
4000                 PackageManager.MATCH_ALL, userId);
4001         final int N = list.size();
4002         for (int i = 0; i < N; i++) {
4003             ResolveInfo info = list.get(i);
4004             if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) {
4005                 return true;
4006             }
4007         }
4008         return false;
4009     }
4010
4011     @Override
4012     public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
4013             throws RemoteException {
4014         try {
4015             return super.onTransact(code, data, reply, flags);
4016         } catch (RuntimeException e) {
4017             if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
4018                 Slog.wtf(TAG, "Package Manager Crash", e);
4019             }
4020             throw e;
4021         }
4022     }
4023
4024     /**
4025      * Returns whether or not a full application can see an instant application.
4026      * <p>
4027      * Currently, there are four cases in which this can occur:
4028      * <ol>
4029      * <li>The calling application is a "special" process. Special processes
4030      *     are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li>
4031      * <li>The calling application has the permission
4032      *     {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li>
4033      * <li>The calling application is the default launcher on the
4034      *     system partition.</li>
4035      * <li>The calling application is the default app prediction service.</li>
4036      * </ol>
4037      */
4038     private boolean canViewInstantApps(int callingUid, int userId) {
4039         if (callingUid < Process.FIRST_APPLICATION_UID) {
4040             return true;
4041         }
4042         if (mContext.checkCallingOrSelfPermission(
4043                 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) {
4044             return true;
4045         }
4046         if (mContext.checkCallingOrSelfPermission(
4047                 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) {
4048             final ComponentName homeComponent = getDefaultHomeActivity(userId);
4049             if (homeComponent != null
4050                     && isCallerSameApp(homeComponent.getPackageName(), callingUid)) {
4051                 return true;
4052             }
4053             // TODO(b/122900055) Change/Remove this and replace with new permission role.
4054             if (mAppPredictionServicePackage != null
4055                     && isCallerSameApp(mAppPredictionServicePackage, callingUid)) {
4056                 return true;
4057             }
4058         }
4059         return false;
4060     }
4061
4062     private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) {
4063         if (!sUserManager.exists(userId)) return null;
4064         if (ps == null) {
4065             return null;
4066         }
4067         final int callingUid = Binder.getCallingUid();
4068         // Filter out ephemeral app metadata:
4069         //   * The system/shell/root can see metadata for any app
4070         //   * An installed app can see metadata for 1) other installed apps
4071         //     and 2) ephemeral apps that have explicitly interacted with it
4072         //   * Ephemeral apps can only see their own data and exposed installed apps
4073         //   * Holding a signature permission allows seeing instant apps
4074         if (filterAppAccessLPr(ps, callingUid, userId)) {
4075             return null;
4076         }
4077
4078         if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0
4079                 && ps.isSystem()) {
4080             flags |= MATCH_ANY_USER;
4081         }
4082
4083         final PackageUserState state = ps.readUserState(userId);
4084         PackageParser.Package p = ps.pkg;
4085         if (p != null) {
4086             final PermissionsState permissionsState = ps.getPermissionsState();
4087
4088             // Compute GIDs only if requested
4089             final int[] gids = (flags & PackageManager.GET_GIDS) == 0
4090                     ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId);
4091             // Compute granted permissions only if package has requested permissions
4092             final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions)
4093                     ? Collections.emptySet() : permissionsState.getPermissions(userId);
4094
4095             PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags,
4096                     ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
4097
4098             if (packageInfo == null) {
4099                 return null;
4100             }
4101
4102             packageInfo.packageName = packageInfo.applicationInfo.packageName =
4103                     resolveExternalPackageNameLPr(p);
4104
4105             return packageInfo;
4106         } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) {
4107             PackageInfo pi = new PackageInfo();
4108             pi.packageName = ps.name;
4109             pi.setLongVersionCode(ps.versionCode);
4110             pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null;
4111             pi.firstInstallTime = ps.firstInstallTime;
4112             pi.lastUpdateTime = ps.lastUpdateTime;
4113
4114             ApplicationInfo ai = new ApplicationInfo();
4115             ai.packageName = ps.name;
4116             ai.uid = UserHandle.getUid(userId, ps.appId);
4117             ai.primaryCpuAbi = ps.primaryCpuAbiString;
4118             ai.secondaryCpuAbi = ps.secondaryCpuAbiString;
4119             ai.setVersionCode(ps.versionCode);
4120             ai.flags = ps.pkgFlags;
4121             ai.privateFlags = ps.pkgPrivateFlags;
4122             pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId);
4123
4124             if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for ["
4125                     + ps.name + "]. Provides a minimum info.");
4126             return pi;
4127         } else {
4128             return null;
4129         }
4130     }
4131
4132     @Override
4133     public void checkPackageStartable(String packageName, int userId) {
4134         final int callingUid = Binder.getCallingUid();
4135         if (getInstantAppPackageName(callingUid) != null) {
4136             throw new SecurityException("Instant applications don't have access to this method");
4137         }
4138         final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId);
4139         synchronized (mPackages) {
4140             final PackageSetting ps = mSettings.mPackages.get(packageName);
4141             if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
4142                 throw new SecurityException("Package " + packageName + " was not found!");
4143             }
4144
4145             if (!ps.getInstalled(userId)) {
4146                 throw new SecurityException(
4147                         "Package " + packageName + " was not installed for user " + userId + "!");
4148             }
4149
4150             if (mSafeMode && !ps.isSystem()) {
4151                 throw new SecurityException("Package " + packageName + " not a system app!");
4152             }
4153
4154             if (mFrozenPackages.contains(packageName)) {
4155                 throw new SecurityException("Package " + packageName + " is currently frozen!");
4156             }
4157
4158             if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) {
4159                 throw new SecurityException("Package " + packageName + " is not encryption aware!");
4160             }
4161         }
4162     }
4163
4164     @Override
4165     public boolean isPackageAvailable(String packageName, int userId) {
4166         if (!sUserManager.exists(userId)) return false;
4167         final int callingUid = Binder.getCallingUid();
4168         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4169                 false /*requireFullPermission*/, false /*checkShell*/, "is package available");
4170         synchronized (mPackages) {
4171             PackageParser.Package p = mPackages.get(packageName);
4172             if (p != null) {
4173                 final PackageSetting ps = (PackageSetting) p.mExtras;
4174                 if (filterAppAccessLPr(ps, callingUid, userId)) {
4175                     return false;
4176                 }
4177                 if (ps != null) {
4178                     final PackageUserState state = ps.readUserState(userId);
4179                     if (state != null) {
4180                         return PackageParser.isAvailable(state);
4181                     }
4182                 }
4183             }
4184         }
4185         return false;
4186     }
4187
4188     @Override
4189     public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
4190         return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
4191                 flags, Binder.getCallingUid(), userId);
4192     }
4193
4194     @Override
4195     public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage,
4196             int flags, int userId) {
4197         return getPackageInfoInternal(versionedPackage.getPackageName(),
4198                 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId);
4199     }
4200
4201     /**
4202      * Important: The provided filterCallingUid is used exclusively to filter out packages
4203      * that can be seen based on user state. It's typically the original caller uid prior
4204      * to clearing. Because it can only be provided by trusted code, it's value can be
4205      * trusted and will be used as-is; unlike userId which will be validated by this method.
4206      */
4207     private PackageInfo getPackageInfoInternal(String packageName, long versionCode,
4208             int flags, int filterCallingUid, int userId) {
4209         if (!sUserManager.exists(userId)) return null;
4210         flags = updateFlagsForPackage(flags, userId, packageName);
4211         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4212                 false /* requireFullPermission */, false /* checkShell */, "get package info");
4213
4214         // reader
4215         synchronized (mPackages) {
4216             // Normalize package name to handle renamed packages and static libs
4217             packageName = resolveInternalPackageNameLPr(packageName, versionCode);
4218
4219             final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0;
4220             if (matchFactoryOnly) {
4221                 // Instant app filtering for APEX modules is ignored
4222                 if ((flags & MATCH_APEX) != 0) {
4223                     return mApexManager.getPackageInfo(packageName,
4224                             ApexManager.MATCH_FACTORY_PACKAGE);
4225                 }
4226                 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
4227                 if (ps != null) {
4228                     if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4229                         return null;
4230                     }
4231                     if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4232                         return null;
4233                     }
4234                     return generatePackageInfo(ps, flags, userId);
4235                 }
4236             }
4237
4238             PackageParser.Package p = mPackages.get(packageName);
4239             if (matchFactoryOnly && p != null && !isSystemApp(p)) {
4240                 return null;
4241             }
4242             if (DEBUG_PACKAGE_INFO)
4243                 Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
4244             if (p != null) {
4245                 final PackageSetting ps = (PackageSetting) p.mExtras;
4246                 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4247                     return null;
4248                 }
4249                 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) {
4250                     return null;
4251                 }
4252                 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId);
4253             }
4254             if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) {
4255                 final PackageSetting ps = mSettings.mPackages.get(packageName);
4256                 if (ps == null) return null;
4257                 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4258                     return null;
4259                 }
4260                 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4261                     return null;
4262                 }
4263                 return generatePackageInfo(ps, flags, userId);
4264             }
4265             if (!matchFactoryOnly && (flags & MATCH_APEX) != 0) {
4266                 return mApexManager.getPackageInfo(packageName, ApexManager.MATCH_ACTIVE_PACKAGE);
4267             }
4268         }
4269         return null;
4270     }
4271
4272     private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) {
4273         if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) {
4274             return true;
4275         }
4276         if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) {
4277             return true;
4278         }
4279         if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) {
4280             return true;
4281         }
4282         return false;
4283     }
4284
4285     private boolean isComponentVisibleToInstantApp(
4286             @Nullable ComponentName component, @ComponentType int type) {
4287         if (type == TYPE_ACTIVITY) {
4288             final PackageParser.Activity activity = mComponentResolver.getActivity(component);
4289             if (activity == null) {
4290                 return false;
4291             }
4292             final boolean visibleToInstantApp =
4293                     (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4294             final boolean explicitlyVisibleToInstantApp =
4295                     (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4296             return visibleToInstantApp && explicitlyVisibleToInstantApp;
4297         } else if (type == TYPE_RECEIVER) {
4298             final PackageParser.Activity activity = mComponentResolver.getReceiver(component);
4299             if (activity == null) {
4300                 return false;
4301             }
4302             final boolean visibleToInstantApp =
4303                     (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
4304             final boolean explicitlyVisibleToInstantApp =
4305                     (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
4306             return visibleToInstantApp && !explicitlyVisibleToInstantApp;
4307         } else if (type == TYPE_SERVICE) {
4308             final PackageParser.Service service = mComponentResolver.getService(component);
4309             return service != null
4310                     ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4311                     : false;
4312         } else if (type == TYPE_PROVIDER) {
4313             final PackageParser.Provider provider = mComponentResolver.getProvider(component);
4314             return provider != null
4315                     ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0
4316                     : false;
4317         } else if (type == TYPE_UNKNOWN) {
4318             return isComponentVisibleToInstantApp(component);
4319         }
4320         return false;
4321     }
4322
4323     /**
4324      * Returns whether or not access to the application should be filtered.
4325      * <p>
4326      * Access may be limited based upon whether the calling or target applications
4327      * are instant applications.
4328      *
4329      * @see #canViewInstantApps(int, int)
4330      */
4331     @GuardedBy("mPackages")
4332     private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid,
4333             @Nullable ComponentName component, @ComponentType int componentType, int userId) {
4334         // if we're in an isolated process, get the real calling UID
4335         if (Process.isIsolated(callingUid)) {
4336             callingUid = mIsolatedOwners.get(callingUid);
4337         }
4338         final String instantAppPkgName = getInstantAppPackageName(callingUid);
4339         final boolean callerIsInstantApp = instantAppPkgName != null;
4340         if (ps == null) {
4341             if (callerIsInstantApp) {
4342                 // pretend the application exists, but, needs to be filtered
4343                 return true;
4344             }
4345             return false;
4346         }
4347         // if the target and caller are the same application, don't filter
4348         if (isCallerSameApp(ps.name, callingUid)) {
4349             return false;
4350         }
4351         if (callerIsInstantApp) {
4352             // both caller and target are both instant, but, different applications, filter
4353             if (ps.getInstantApp(userId)) {
4354                 return true;
4355             }
4356             // request for a specific component; if it hasn't been explicitly exposed through
4357             // property or instrumentation target, filter
4358             if (component != null) {
4359                 final PackageParser.Instrumentation instrumentation =
4360                         mInstrumentation.get(component);
4361                 if (instrumentation != null
4362                         && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) {
4363                     return false;
4364                 }
4365                 return !isComponentVisibleToInstantApp(component, componentType);
4366             }
4367             // request for application; if no components have been explicitly exposed, filter
4368             return !ps.pkg.visibleToInstantApps;
4369         }
4370         if (ps.getInstantApp(userId)) {
4371             // caller can see all components of all instant applications, don't filter
4372             if (canViewInstantApps(callingUid, userId)) {
4373                 return false;
4374             }
4375             // request for a specific instant application component, filter
4376             if (component != null) {
4377                 return true;
4378             }
4379             // request for an instant application; if the caller hasn't been granted access, filter
4380             return !mInstantAppRegistry.isInstantAccessGranted(
4381                     userId, UserHandle.getAppId(callingUid), ps.appId);
4382         }
4383         return false;
4384     }
4385
4386     /**
4387      * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, int, int)
4388      */
4389     @GuardedBy("mPackages")
4390     private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) {
4391         return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId);
4392     }
4393
4394     @GuardedBy("mPackages")
4395     private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId,
4396             int flags) {
4397         // Callers can access only the libs they depend on, otherwise they need to explicitly
4398         // ask for the shared libraries given the caller is allowed to access all static libs.
4399         if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) {
4400             // System/shell/root get to see all static libs
4401             final int appId = UserHandle.getAppId(uid);
4402             if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID
4403                     || appId == Process.ROOT_UID) {
4404                 return false;
4405             }
4406             // Installer gets to see all static libs.
4407             if (PackageManager.PERMISSION_GRANTED
4408                     == checkUidPermission(Manifest.permission.INSTALL_PACKAGES, uid)) {
4409                 return false;
4410             }
4411         }
4412
4413         // No package means no static lib as it is always on internal storage
4414         if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) {
4415             return false;
4416         }
4417
4418         final SharedLibraryInfo libraryInfo = getSharedLibraryInfoLPr(ps.pkg.staticSharedLibName,
4419                 ps.pkg.staticSharedLibVersion);
4420         if (libraryInfo == null) {
4421             return false;
4422         }
4423
4424         final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid));
4425         final String[] uidPackageNames = getPackagesForUid(resolvedUid);
4426         if (uidPackageNames == null) {
4427             return true;
4428         }
4429
4430         for (String uidPackageName : uidPackageNames) {
4431             if (ps.name.equals(uidPackageName)) {
4432                 return false;
4433             }
4434             PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName);
4435             if (uidPs != null) {
4436                 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries,
4437                         libraryInfo.getName());
4438                 if (index < 0) {
4439                     continue;
4440                 }
4441                 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libraryInfo.getLongVersion()) {
4442                     return false;
4443                 }
4444             }
4445         }
4446         return true;
4447     }
4448
4449     @Override
4450     public String[] currentToCanonicalPackageNames(String[] names) {
4451         final int callingUid = Binder.getCallingUid();
4452         if (getInstantAppPackageName(callingUid) != null) {
4453             return names;
4454         }
4455         final String[] out = new String[names.length];
4456         // reader
4457         synchronized (mPackages) {
4458             final int callingUserId = UserHandle.getUserId(callingUid);
4459             final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4460             for (int i=names.length-1; i>=0; i--) {
4461                 final PackageSetting ps = mSettings.mPackages.get(names[i]);
4462                 boolean translateName = false;
4463                 if (ps != null && ps.realName != null) {
4464                     final boolean targetIsInstantApp = ps.getInstantApp(callingUserId);
4465                     translateName = !targetIsInstantApp
4466                             || canViewInstantApps
4467                             || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4468                                     UserHandle.getAppId(callingUid), ps.appId);
4469                 }
4470                 out[i] = translateName ? ps.realName : names[i];
4471             }
4472         }
4473         return out;
4474     }
4475
4476     @Override
4477     public String[] canonicalToCurrentPackageNames(String[] names) {
4478         final int callingUid = Binder.getCallingUid();
4479         if (getInstantAppPackageName(callingUid) != null) {
4480             return names;
4481         }
4482         final String[] out = new String[names.length];
4483         // reader
4484         synchronized (mPackages) {
4485             final int callingUserId = UserHandle.getUserId(callingUid);
4486             final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId);
4487             for (int i=names.length-1; i>=0; i--) {
4488                 final String cur = mSettings.getRenamedPackageLPr(names[i]);
4489                 boolean translateName = false;
4490                 if (cur != null) {
4491                     final PackageSetting ps = mSettings.mPackages.get(names[i]);
4492                     final boolean targetIsInstantApp =
4493                             ps != null && ps.getInstantApp(callingUserId);
4494                     translateName = !targetIsInstantApp
4495                             || canViewInstantApps
4496                             || mInstantAppRegistry.isInstantAccessGranted(callingUserId,
4497                                     UserHandle.getAppId(callingUid), ps.appId);
4498                 }
4499                 out[i] = translateName ? cur : names[i];
4500             }
4501         }
4502         return out;
4503     }
4504
4505     @Override
4506     public int getPackageUid(String packageName, int flags, int userId) {
4507         if (!sUserManager.exists(userId)) return -1;
4508         final int callingUid = Binder.getCallingUid();
4509         flags = updateFlagsForPackage(flags, userId, packageName);
4510         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4511                 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid");
4512
4513         // reader
4514         synchronized (mPackages) {
4515             final PackageParser.Package p = mPackages.get(packageName);
4516             if (p != null && p.isMatch(flags)) {
4517                 PackageSetting ps = (PackageSetting) p.mExtras;
4518                 if (filterAppAccessLPr(ps, callingUid, userId)) {
4519                     return -1;
4520                 }
4521                 return UserHandle.getUid(userId, p.applicationInfo.uid);
4522             }
4523             if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4524                 final PackageSetting ps = mSettings.mPackages.get(packageName);
4525                 if (ps != null && ps.isMatch(flags)
4526                         && !filterAppAccessLPr(ps, callingUid, userId)) {
4527                     return UserHandle.getUid(userId, ps.appId);
4528                 }
4529             }
4530         }
4531
4532         return -1;
4533     }
4534
4535     /**
4536      * Check if any package sharing/holding a uid has a low enough target SDK.
4537      *
4538      * @param uid The uid of the packages
4539      * @param higherTargetSDK The target SDK that might be higher than the searched package
4540      *
4541      * @return {@code true} if there is a package sharing/holding the uid with
4542      * {@code package.targetSDK < higherTargetSDK}
4543      */
4544     private boolean hasTargetSdkInUidLowerThan(int uid, int higherTargetSDK) {
4545         int userId = UserHandle.getUserId(uid);
4546
4547         synchronized (mPackages) {
4548             Object obj = mSettings.getSettingLPr(UserHandle.getAppId(uid));
4549             if (obj == null) {
4550                 return false;
4551             }
4552
4553             if (obj instanceof PackageSetting) {
4554                 final PackageSetting ps = (PackageSetting) obj;
4555
4556                 if (!ps.getInstalled(userId)) {
4557                     return false;
4558                 }
4559
4560                 return ps.pkg.applicationInfo.targetSdkVersion < higherTargetSDK;
4561             } else if (obj instanceof SharedUserSetting) {
4562                 final SharedUserSetting sus = (SharedUserSetting) obj;
4563
4564                 final int numPkgs = sus.packages.size();
4565                 for (int i = 0; i < numPkgs; i++) {
4566                     final PackageSetting ps = sus.packages.valueAt(i);
4567
4568                     if (!ps.getInstalled(userId)) {
4569                         continue;
4570                     }
4571
4572                     if (ps.pkg.applicationInfo.targetSdkVersion < higherTargetSDK) {
4573                         return true;
4574                     }
4575                 }
4576
4577                 return false;
4578             } else {
4579                 return false;
4580             }
4581         }
4582     }
4583
4584     @Override
4585     public int[] getPackageGids(String packageName, int flags, int userId) {
4586         if (!sUserManager.exists(userId)) return null;
4587         final int callingUid = Binder.getCallingUid();
4588         flags = updateFlagsForPackage(flags, userId, packageName);
4589         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
4590                 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids");
4591
4592         // reader
4593         synchronized (mPackages) {
4594             final PackageParser.Package p = mPackages.get(packageName);
4595             if (p != null && p.isMatch(flags)) {
4596                 PackageSetting ps = (PackageSetting) p.mExtras;
4597                 if (filterAppAccessLPr(ps, callingUid, userId)) {
4598                     return null;
4599                 }
4600                 // TODO: Shouldn't this be checking for package installed state for userId and
4601                 // return null?
4602                 return ps.getPermissionsState().computeGids(userId);
4603             }
4604             if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4605                 final PackageSetting ps = mSettings.mPackages.get(packageName);
4606                 if (ps != null && ps.isMatch(flags)
4607                         && !filterAppAccessLPr(ps, callingUid, userId)) {
4608                     return ps.getPermissionsState().computeGids(userId);
4609                 }
4610             }
4611         }
4612
4613         return null;
4614     }
4615
4616     @Override
4617     public PermissionInfo getPermissionInfo(String name, String packageName, int flags) {
4618         return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid());
4619     }
4620
4621     @Override
4622     public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName,
4623             int flags) {
4624         final List<PermissionInfo> permissionList =
4625                 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid());
4626         return (permissionList == null) ? null : new ParceledListSlice<>(permissionList);
4627     }
4628
4629     @Override
4630     public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) {
4631         return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid());
4632     }
4633
4634     @Override
4635     public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) {
4636         final List<PermissionGroupInfo> permissionList =
4637                 mPermissionManager.getAllPermissionGroups(flags, getCallingUid());
4638         return (permissionList == null)
4639                 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList);
4640     }
4641
4642     @GuardedBy("mPackages")
4643     private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
4644             int filterCallingUid, int userId) {
4645         if (!sUserManager.exists(userId)) return null;
4646         PackageSetting ps = mSettings.mPackages.get(packageName);
4647         if (ps != null) {
4648             if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4649                 return null;
4650             }
4651             if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4652                 return null;
4653             }
4654             if (ps.pkg == null) {
4655                 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId);
4656                 if (pInfo != null) {
4657                     return pInfo.applicationInfo;
4658                 }
4659                 return null;
4660             }
4661             ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4662                     ps.readUserState(userId), userId);
4663             if (ai != null) {
4664                 ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
4665             }
4666             return ai;
4667         }
4668         return null;
4669     }
4670
4671     @Override
4672     public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
4673         return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId);
4674     }
4675
4676     /**
4677      * Important: The provided filterCallingUid is used exclusively to filter out applications
4678      * that can be seen based on user state. It's typically the original caller uid prior
4679      * to clearing. Because it can only be provided by trusted code, it's value can be
4680      * trusted and will be used as-is; unlike userId which will be validated by this method.
4681      */
4682     private ApplicationInfo getApplicationInfoInternal(String packageName, int flags,
4683             int filterCallingUid, int userId) {
4684         if (!sUserManager.exists(userId)) return null;
4685         flags = updateFlagsForApplication(flags, userId, packageName);
4686
4687         if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
4688             mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
4689                     false /* requireFullPermission */, false /* checkShell */,
4690                     "get application info");
4691         }
4692
4693         // writer
4694         synchronized (mPackages) {
4695             // Normalize package name to handle renamed packages and static libs
4696             packageName = resolveInternalPackageNameLPr(packageName,
4697                     PackageManager.VERSION_CODE_HIGHEST);
4698
4699             PackageParser.Package p = mPackages.get(packageName);
4700             if (DEBUG_PACKAGE_INFO) Log.v(
4701                     TAG, "getApplicationInfo " + packageName
4702                     + ": " + p);
4703             if (p != null) {
4704                 PackageSetting ps = mSettings.mPackages.get(packageName);
4705                 if (ps == null) return null;
4706                 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) {
4707                     return null;
4708                 }
4709                 if (filterAppAccessLPr(ps, filterCallingUid, userId)) {
4710                     return null;
4711                 }
4712                 // Note: isEnabledLP() does not apply here - always return info
4713                 ApplicationInfo ai = PackageParser.generateApplicationInfo(
4714                         p, flags, ps.readUserState(userId), userId);
4715                 if (ai != null) {
4716                     ai.packageName = resolveExternalPackageNameLPr(p);
4717                 }
4718                 return ai;
4719             }
4720             if ("android".equals(packageName)||"system".equals(packageName)) {
4721                 return mAndroidApplication;
4722             }
4723             if ((flags & MATCH_KNOWN_PACKAGES) != 0) {
4724                 // Already generates the external package name
4725                 return generateApplicationInfoFromSettingsLPw(packageName,
4726                         flags, filterCallingUid, userId);
4727             }
4728         }
4729         return null;
4730     }
4731
4732     @GuardedBy("mPackages")
4733     private String normalizePackageNameLPr(String packageName) {
4734         String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
4735         return normalizedPackageName != null ? normalizedPackageName : packageName;
4736     }
4737
4738     @Override
4739     public void deletePreloadsFileCache() {
4740         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CLEAR_APP_CACHE,
4741                 "deletePreloadsFileCache");
4742         File dir = Environment.getDataPreloadsFileCacheDirectory();
4743         Slog.i(TAG, "Deleting preloaded file cache " + dir);
4744         FileUtils.deleteContents(dir);
4745     }
4746
4747     @Override
4748     public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
4749             final int storageFlags, final IPackageDataObserver observer) {
4750         mContext.enforceCallingOrSelfPermission(
4751                 android.Manifest.permission.CLEAR_APP_CACHE, null);
4752         mHandler.post(() -> {
4753             boolean success = false;
4754             try {
4755                 freeStorage(volumeUuid, freeStorageSize, storageFlags);
4756                 success = true;
4757             } catch (IOException e) {
4758                 Slog.w(TAG, e);
4759             }
4760             if (observer != null) {
4761                 try {
4762                     observer.onRemoveCompleted(null, success);
4763                 } catch (RemoteException e) {
4764                     Slog.w(TAG, e);
4765                 }
4766             }
4767         });
4768     }
4769
4770     @Override
4771     public void freeStorage(final String volumeUuid, final long freeStorageSize,
4772             final int storageFlags, final IntentSender pi) {
4773         mContext.enforceCallingOrSelfPermission(
4774                 android.Manifest.permission.CLEAR_APP_CACHE, TAG);
4775         mHandler.post(() -> {
4776             boolean success = false;
4777             try {
4778                 freeStorage(volumeUuid, freeStorageSize, storageFlags);
4779                 success = true;
4780             } catch (IOException e) {
4781                 Slog.w(TAG, e);
4782             }
4783             if (pi != null) {
4784                 try {
4785                     pi.sendIntent(null, success ? 1 : 0, null, null, null);
4786                 } catch (SendIntentException e) {
4787                     Slog.w(TAG, e);
4788                 }
4789             }
4790         });
4791     }
4792
4793     /**
4794      * Blocking call to clear various types of cached data across the system
4795      * until the requested bytes are available.
4796      */
4797     public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException {
4798         final StorageManager storage = mContext.getSystemService(StorageManager.class);
4799         final File file = storage.findPathForUuid(volumeUuid);
4800         if (file.getUsableSpace() >= bytes) return;
4801
4802         if (ENABLE_FREE_CACHE_V2) {
4803             final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL,
4804                     volumeUuid);
4805             final boolean aggressive = (storageFlags
4806                     & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0;
4807             final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags);
4808
4809             // 1. Pre-flight to determine if we have any chance to succeed
4810             // 2. Consider preloaded data (after 1w honeymoon, unless aggressive)
4811             if (internalVolume && (aggressive || SystemProperties
4812                     .getBoolean("persist.sys.preloads.file_cache_expired", false))) {
4813                 deletePreloadsFileCache();
4814                 if (file.getUsableSpace() >= bytes) return;
4815             }
4816
4817             // 3. Consider parsed APK data (aggressive only)
4818             if (internalVolume && aggressive) {
4819                 FileUtils.deleteContents(mCacheDir);
4820                 if (file.getUsableSpace() >= bytes) return;
4821             }
4822
4823             // 4. Consider cached app data (above quotas)
4824             try {
4825                 mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4826                         Installer.FLAG_FREE_CACHE_V2);
4827             } catch (InstallerException ignored) {
4828             }
4829             if (file.getUsableSpace() >= bytes) return;
4830
4831             // 5. Consider shared libraries with refcount=0 and age>min cache period
4832             if (internalVolume && pruneUnusedStaticSharedLibraries(bytes,
4833                     android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4834                             Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD,
4835                             DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) {
4836                 return;
4837             }
4838
4839             // 6. Consider dexopt output (aggressive only)
4840             // TODO: Implement
4841
4842             // 7. Consider installed instant apps unused longer than min cache period
4843             if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes,
4844                     android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4845                             Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4846                             InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4847                 return;
4848             }
4849
4850             // 8. Consider cached app data (below quotas)
4851             try {
4852                 mInstaller.freeCache(volumeUuid, bytes, reservedBytes,
4853                         Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA);
4854             } catch (InstallerException ignored) {
4855             }
4856             if (file.getUsableSpace() >= bytes) return;
4857
4858             // 9. Consider DropBox entries
4859             // TODO: Implement
4860
4861             // 10. Consider instant meta-data (uninstalled apps) older that min cache period
4862             if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes,
4863                     android.provider.Settings.Global.getLong(mContext.getContentResolver(),
4864                             Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD,
4865                             InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) {
4866                 return;
4867             }
4868         } else {
4869             try {
4870                 mInstaller.freeCache(volumeUuid, bytes, 0, 0);
4871             } catch (InstallerException ignored) {
4872             }
4873             if (file.getUsableSpace() >= bytes) return;
4874         }
4875
4876         throw new IOException("Failed to free " + bytes + " on storage device at " + file);
4877     }
4878
4879     private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)
4880             throws IOException {
4881         final StorageManager storage = mContext.getSystemService(StorageManager.class);
4882         final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL);
4883
4884         List<VersionedPackage> packagesToDelete = null;
4885         final long now = System.currentTimeMillis();
4886
4887         synchronized (mPackages) {
4888             final int[] allUsers = sUserManager.getUserIds();
4889             final int libCount = mSharedLibraries.size();
4890             for (int i = 0; i < libCount; i++) {
4891                 final LongSparseArray<SharedLibraryInfo> versionedLib
4892                         = mSharedLibraries.valueAt(i);
4893                 if (versionedLib == null) {
4894                     continue;
4895                 }
4896                 final int versionCount = versionedLib.size();
4897                 for (int j = 0; j < versionCount; j++) {
4898                     SharedLibraryInfo libInfo = versionedLib.valueAt(j);
4899                     // Skip packages that are not static shared libs.
4900                     if (!libInfo.isStatic()) {
4901                         break;
4902                     }
4903                     // Important: We skip static shared libs used for some user since
4904                     // in such a case we need to keep the APK on the device. The check for
4905                     // a lib being used for any user is performed by the uninstall call.
4906                     final VersionedPackage declaringPackage = libInfo.getDeclaringPackage();
4907                     // Resolve the package name - we use synthetic package names internally
4908                     final String internalPackageName = resolveInternalPackageNameLPr(
4909                             declaringPackage.getPackageName(),
4910                             declaringPackage.getLongVersionCode());
4911                     final PackageSetting ps = mSettings.getPackageLPr(internalPackageName);
4912                     // Skip unused static shared libs cached less than the min period
4913                     // to prevent pruning a lib needed by a subsequently installed package.
4914                     if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) {
4915                         continue;
4916                     }
4917
4918                     if (ps.pkg.isSystem()) {
4919                         continue;
4920                     }
4921
4922                     if (packagesToDelete == null) {
4923                         packagesToDelete = new ArrayList<>();
4924                     }
4925                     packagesToDelete.add(new VersionedPackage(internalPackageName,
4926                             declaringPackage.getLongVersionCode()));
4927                 }
4928             }
4929         }
4930
4931         if (packagesToDelete != null) {
4932             final int packageCount = packagesToDelete.size();
4933             for (int i = 0; i < packageCount; i++) {
4934                 final VersionedPackage pkgToDelete = packagesToDelete.get(i);
4935                 // Delete the package synchronously (will fail of the lib used for any user).
4936                 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(),
4937                         UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS)
4938                                 == PackageManager.DELETE_SUCCEEDED) {
4939                     if (volume.getUsableSpace() >= neededSpace) {
4940                         return true;
4941                     }
4942                 }
4943             }
4944         }
4945
4946         return false;
4947     }
4948
4949     /**
4950      * Update given flags based on encryption status of current user.
4951      */
4952     private int updateFlags(int flags, int userId) {
4953         if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE
4954                 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) {
4955             // Caller expressed an explicit opinion about what encryption
4956             // aware/unaware components they want to see, so fall through and
4957             // give them what they want
4958         } else {
4959             // Caller expressed no opinion, so match based on user state
4960             if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) {
4961                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE;
4962             } else {
4963                 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE;
4964             }
4965         }
4966         return flags;
4967     }
4968
4969     private UserManagerInternal getUserManagerInternal() {
4970         if (mUserManagerInternal == null) {
4971             mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
4972         }
4973         return mUserManagerInternal;
4974     }
4975
4976     private ActivityManagerInternal getActivityManagerInternal() {
4977         if (mActivityManagerInternal == null) {
4978             mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
4979         }
4980         return mActivityManagerInternal;
4981     }
4982
4983     private ActivityTaskManagerInternal getActivityTaskManagerInternal() {
4984         if (mActivityTaskManagerInternal == null) {
4985             mActivityTaskManagerInternal =
4986                     LocalServices.getService(ActivityTaskManagerInternal.class);
4987         }
4988         return mActivityTaskManagerInternal;
4989     }
4990
4991     private DeviceIdleController.LocalService getDeviceIdleController() {
4992         if (mDeviceIdleController == null) {
4993             mDeviceIdleController =
4994                     LocalServices.getService(DeviceIdleController.LocalService.class);
4995         }
4996         return mDeviceIdleController;
4997     }
4998
4999     private StorageManagerInternal getStorageManagerInternal() {
5000         if (mStorageManagerInternal == null) {
5001             mStorageManagerInternal = LocalServices.getService(StorageManagerInternal.class);
5002         }
5003         return mStorageManagerInternal;
5004     }
5005
5006     /**
5007      * Update given flags when being used to request {@link PackageInfo}.
5008      */
5009     private int updateFlagsForPackage(int flags, int userId, Object cookie) {
5010         final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM;
5011         if ((flags & PackageManager.MATCH_ANY_USER) != 0) {
5012             // require the permission to be held; the calling uid and given user id referring
5013             // to the same user is not sufficient
5014             mPermissionManager.enforceCrossUserPermission(
5015                     Binder.getCallingUid(), userId, false, false,
5016                     !isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId),
5017                     "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at "
5018                     + Debug.getCallers(5));
5019         } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser
5020                 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) {
5021             // If the caller wants all packages and has a restricted profile associated with it,
5022             // then match all users. This is to make sure that launchers that need to access work
5023             // profile apps don't start breaking. TODO: Remove this hack when launchers stop using
5024             // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380
5025             flags |= PackageManager.MATCH_ANY_USER;
5026         }
5027         return updateFlags(flags, userId);
5028     }
5029
5030     /**
5031      * Update given flags when being used to request {@link ApplicationInfo}.
5032      */
5033     private int updateFlagsForApplication(int flags, int userId, Object cookie) {
5034         return updateFlagsForPackage(flags, userId, cookie);
5035     }
5036
5037     /**
5038      * Update given flags when being used to request {@link ComponentInfo}.
5039      */
5040     private int updateFlagsForComponent(int flags, int userId, Object cookie) {
5041         return updateFlags(flags, userId);
5042     }
5043
5044     /**
5045      * Update given intent when being used to request {@link ResolveInfo}.
5046      */
5047     private Intent updateIntentForResolve(Intent intent) {
5048         if (intent.getSelector() != null) {
5049             intent = intent.getSelector();
5050         }
5051         if (DEBUG_PREFERRED) {
5052             intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
5053         }
5054         return intent;
5055     }
5056
5057     /**
5058      * Update given flags when being used to request {@link ResolveInfo}.
5059      * <p>Instant apps are resolved specially, depending upon context. Minimally,
5060      * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT}
5061      * flag set. However, this flag is only honoured in three circumstances:
5062      * <ul>
5063      * <li>when called from a system process</li>
5064      * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li>
5065      * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW}
5066      * action and a {@code android.intent.category.BROWSABLE} category</li>
5067      * </ul>
5068      */
5069     int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) {
5070         return updateFlagsForResolve(flags, userId, intent, callingUid,
5071                 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/);
5072     }
5073     int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
5074             boolean wantInstantApps) {
5075         return updateFlagsForResolve(flags, userId, intent, callingUid,
5076                 wantInstantApps, false /*onlyExposedExplicitly*/);
5077     }
5078     int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid,
5079             boolean wantInstantApps, boolean onlyExposedExplicitly) {
5080         // Safe mode means we shouldn't match any third-party components
5081         if (mSafeMode) {
5082             flags |= PackageManager.MATCH_SYSTEM_ONLY;
5083         }
5084         if (getInstantAppPackageName(callingUid) != null) {
5085             // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components
5086             if (onlyExposedExplicitly) {
5087                 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY;
5088             }
5089             flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY;
5090             flags |= PackageManager.MATCH_INSTANT;
5091         } else {
5092             final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0;
5093             final boolean allowMatchInstant = wantInstantApps
5094                     || (wantMatchInstant && canViewInstantApps(callingUid, userId));
5095             flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY
5096                     | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY);
5097             if (!allowMatchInstant) {
5098                 flags &= ~PackageManager.MATCH_INSTANT;
5099             }
5100         }
5101         return updateFlagsForComponent(flags, userId, intent /*cookie*/);
5102     }
5103
5104     @Override
5105     public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
5106         return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId);
5107     }
5108
5109     /**
5110      * Important: The provided filterCallingUid is used exclusively to filter out activities
5111      * that can be seen based on user state. It's typically the original caller uid prior
5112      * to clearing. Because it can only be provided by trusted code, it's value can be
5113      * trusted and will be used as-is; unlike userId which will be validated by this method.
5114      */
5115     private ActivityInfo getActivityInfoInternal(ComponentName component, int flags,
5116             int filterCallingUid, int userId) {
5117         if (!sUserManager.exists(userId)) return null;
5118         flags = updateFlagsForComponent(flags, userId, component);
5119
5120         if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) {
5121             mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
5122                     false /* requireFullPermission */, false /* checkShell */, "get activity info");
5123         }
5124
5125         synchronized (mPackages) {
5126             PackageParser.Activity a = mComponentResolver.getActivity(component);
5127
5128             if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
5129             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
5130                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5131                 if (ps == null) return null;
5132                 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) {
5133                     return null;
5134                 }
5135                 return PackageParser.generateActivityInfo(
5136                         a, flags, ps.readUserState(userId), userId);
5137             }
5138             if (mResolveComponentName.equals(component)) {
5139                 return PackageParser.generateActivityInfo(
5140                         mResolveActivity, flags, new PackageUserState(), userId);
5141             }
5142         }
5143         return null;
5144     }
5145
5146     private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) {
5147         if (!getActivityTaskManagerInternal().isCallerRecents(callingUid)) {
5148             return false;
5149         }
5150         final long token = Binder.clearCallingIdentity();
5151         try {
5152             final int callingUserId = UserHandle.getUserId(callingUid);
5153             if (ActivityManager.getCurrentUser() != callingUserId) {
5154                 return false;
5155             }
5156             return sUserManager.isSameProfileGroup(callingUserId, targetUserId);
5157         } finally {
5158             Binder.restoreCallingIdentity(token);
5159         }
5160     }
5161
5162     @Override
5163     public boolean activitySupportsIntent(ComponentName component, Intent intent,
5164             String resolvedType) {
5165         synchronized (mPackages) {
5166             if (component.equals(mResolveComponentName)) {
5167                 // The resolver supports EVERYTHING!
5168                 return true;
5169             }
5170             final int callingUid = Binder.getCallingUid();
5171             final int callingUserId = UserHandle.getUserId(callingUid);
5172             PackageParser.Activity a = mComponentResolver.getActivity(component);
5173             if (a == null) {
5174                 return false;
5175             }
5176             PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5177             if (ps == null) {
5178                 return false;
5179             }
5180             if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) {
5181                 return false;
5182             }
5183             for (int i=0; i<a.intents.size(); i++) {
5184                 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
5185                         intent.getData(), intent.getCategories(), TAG) >= 0) {
5186                     return true;
5187                 }
5188             }
5189             return false;
5190         }
5191     }
5192
5193     @Override
5194     public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
5195         if (!sUserManager.exists(userId)) return null;
5196         final int callingUid = Binder.getCallingUid();
5197         flags = updateFlagsForComponent(flags, userId, component);
5198         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5199                 false /* requireFullPermission */, false /* checkShell */, "get receiver info");
5200         synchronized (mPackages) {
5201             PackageParser.Activity a = mComponentResolver.getReceiver(component);
5202             if (DEBUG_PACKAGE_INFO) Log.v(
5203                 TAG, "getReceiverInfo " + component + ": " + a);
5204             if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) {
5205                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5206                 if (ps == null) return null;
5207                 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) {
5208                     return null;
5209                 }
5210                 return PackageParser.generateActivityInfo(
5211                         a, flags, ps.readUserState(userId), userId);
5212             }
5213         }
5214         return null;
5215     }
5216
5217     @Override
5218     public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName,
5219             int flags, int userId) {
5220         if (!sUserManager.exists(userId)) return null;
5221         Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
5222         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5223             return null;
5224         }
5225
5226         flags = updateFlagsForPackage(flags, userId, null);
5227
5228         final boolean canSeeStaticLibraries =
5229                 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES)
5230                         == PERMISSION_GRANTED
5231                 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES)
5232                         == PERMISSION_GRANTED
5233                 || canRequestPackageInstallsInternal(packageName,
5234                         PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId,
5235                         false  /* throwIfPermNotDeclared*/)
5236                 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES)
5237                         == PERMISSION_GRANTED
5238                 || mContext.checkCallingOrSelfPermission(
5239                         Manifest.permission.ACCESS_SHARED_LIBRARIES) == PERMISSION_GRANTED;
5240
5241         synchronized (mPackages) {
5242             List<SharedLibraryInfo> result = null;
5243
5244             final int libCount = mSharedLibraries.size();
5245             for (int i = 0; i < libCount; i++) {
5246                 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.valueAt(i);
5247                 if (versionedLib == null) {
5248                     continue;
5249                 }
5250
5251                 final int versionCount = versionedLib.size();
5252                 for (int j = 0; j < versionCount; j++) {
5253                     SharedLibraryInfo libInfo = versionedLib.valueAt(j);
5254                     if (!canSeeStaticLibraries && libInfo.isStatic()) {
5255                         break;
5256                     }
5257                     final long identity = Binder.clearCallingIdentity();
5258                     try {
5259                         PackageInfo packageInfo = getPackageInfoVersioned(
5260                                 libInfo.getDeclaringPackage(), flags
5261                                         | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5262                         if (packageInfo == null) {
5263                             continue;
5264                         }
5265                     } finally {
5266                         Binder.restoreCallingIdentity(identity);
5267                     }
5268
5269                     SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getPath(),
5270                             libInfo.getPackageName(), libInfo.getAllCodePaths(),
5271                             libInfo.getName(), libInfo.getLongVersion(),
5272                             libInfo.getType(), libInfo.getDeclaringPackage(),
5273                             getPackagesUsingSharedLibraryLPr(libInfo, flags, userId),
5274                             (libInfo.getDependencies() == null
5275                                     ? null
5276                                     : new ArrayList<>(libInfo.getDependencies())));
5277
5278                     if (result == null) {
5279                         result = new ArrayList<>();
5280                     }
5281                     result.add(resLibInfo);
5282                 }
5283             }
5284
5285             return result != null ? new ParceledListSlice<>(result) : null;
5286         }
5287     }
5288
5289     @Nullable
5290     @Override
5291     public ParceledListSlice<SharedLibraryInfo> getDeclaredSharedLibraries(
5292             @NonNull String packageName, int flags, @NonNull int userId) {
5293         mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_SHARED_LIBRARIES,
5294                 "getDeclaredSharedLibraries");
5295         int callingUid = Binder.getCallingUid();
5296         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5297                 true /* requireFullPermission */, false /* checkShell */,
5298                 "getDeclaredSharedLibraries");
5299
5300         Preconditions.checkNotNull(packageName, "packageName cannot be null");
5301         Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0");
5302         if (!sUserManager.exists(userId)) {
5303             return null;
5304         }
5305
5306         if (getInstantAppPackageName(callingUid) != null) {
5307             return null;
5308         }
5309
5310         synchronized (mPackages) {
5311             List<SharedLibraryInfo> result = null;
5312
5313             int libraryCount = mSharedLibraries.size();
5314             for (int i = 0; i < libraryCount; i++) {
5315                 LongSparseArray<SharedLibraryInfo> versionedLibrary = mSharedLibraries.valueAt(i);
5316                 if (versionedLibrary == null) {
5317                     continue;
5318                 }
5319
5320                 int versionCount = versionedLibrary.size();
5321                 for (int j = 0; j < versionCount; j++) {
5322                     SharedLibraryInfo libraryInfo = versionedLibrary.valueAt(j);
5323
5324                     VersionedPackage declaringPackage = libraryInfo.getDeclaringPackage();
5325                     if (!Objects.equals(declaringPackage.getPackageName(), packageName)) {
5326                         continue;
5327                     }
5328
5329                     long identity = Binder.clearCallingIdentity();
5330                     try {
5331                         PackageInfo packageInfo = getPackageInfoVersioned(declaringPackage, flags
5332                                 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
5333                         if (packageInfo == null) {
5334                             continue;
5335                         }
5336                     } finally {
5337                         Binder.restoreCallingIdentity(identity);
5338                     }
5339
5340                     SharedLibraryInfo resultLibraryInfo = new SharedLibraryInfo(
5341                             libraryInfo.getPath(), libraryInfo.getPackageName(),
5342                             libraryInfo.getAllCodePaths(), libraryInfo.getName(),
5343                             libraryInfo.getLongVersion(), libraryInfo.getType(),
5344                             libraryInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(
5345                             libraryInfo, flags, userId), libraryInfo.getDependencies() == null
5346                             ? null : new ArrayList<>(libraryInfo.getDependencies()));
5347
5348                     if (result == null) {
5349                         result = new ArrayList<>();
5350                     }
5351                     result.add(resultLibraryInfo);
5352                 }
5353             }
5354
5355             return result != null ? new ParceledListSlice<>(result) : null;
5356         }
5357     }
5358
5359     @GuardedBy("mPackages")
5360     private List<VersionedPackage> getPackagesUsingSharedLibraryLPr(
5361             SharedLibraryInfo libInfo, int flags, int userId) {
5362         List<VersionedPackage> versionedPackages = null;
5363         final int packageCount = mSettings.mPackages.size();
5364         for (int i = 0; i < packageCount; i++) {
5365             PackageSetting ps = mSettings.mPackages.valueAt(i);
5366
5367             if (ps == null) {
5368                 continue;
5369             }
5370
5371             if (!ps.readUserState(userId).isAvailable(flags)) {
5372                 continue;
5373             }
5374
5375             final String libName = libInfo.getName();
5376             if (libInfo.isStatic()) {
5377                 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
5378                 if (libIdx < 0) {
5379                     continue;
5380                 }
5381                 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) {
5382                     continue;
5383                 }
5384                 if (versionedPackages == null) {
5385                     versionedPackages = new ArrayList<>();
5386                 }
5387                 // If the dependent is a static shared lib, use the public package name
5388                 String dependentPackageName = ps.name;
5389                 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) {
5390                     dependentPackageName = ps.pkg.manifestPackageName;
5391                 }
5392                 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode));
5393             } else if (ps.pkg != null) {
5394                 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName)
5395                         || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) {
5396                     if (versionedPackages == null) {
5397                         versionedPackages = new ArrayList<>();
5398                     }
5399                     versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode));
5400                 }
5401             }
5402         }
5403
5404         return versionedPackages;
5405     }
5406
5407     @Override
5408     public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
5409         if (!sUserManager.exists(userId)) return null;
5410         final int callingUid = Binder.getCallingUid();
5411         flags = updateFlagsForComponent(flags, userId, component);
5412         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5413                 false /* requireFullPermission */, false /* checkShell */, "get service info");
5414         synchronized (mPackages) {
5415             PackageParser.Service s = mComponentResolver.getService(component);
5416             if (DEBUG_PACKAGE_INFO) Log.v(
5417                 TAG, "getServiceInfo " + component + ": " + s);
5418             if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) {
5419                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5420                 if (ps == null) return null;
5421                 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) {
5422                     return null;
5423                 }
5424                 return PackageParser.generateServiceInfo(
5425                         s, flags, ps.readUserState(userId), userId);
5426             }
5427         }
5428         return null;
5429     }
5430
5431     @Override
5432     public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
5433         if (!sUserManager.exists(userId)) return null;
5434         final int callingUid = Binder.getCallingUid();
5435         flags = updateFlagsForComponent(flags, userId, component);
5436         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
5437                 false /* requireFullPermission */, false /* checkShell */, "get provider info");
5438         synchronized (mPackages) {
5439             PackageParser.Provider p = mComponentResolver.getProvider(component);
5440             if (DEBUG_PACKAGE_INFO) Log.v(
5441                 TAG, "getProviderInfo " + component + ": " + p);
5442             if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) {
5443                 PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
5444                 if (ps == null) return null;
5445                 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
5446                     return null;
5447                 }
5448                 return PackageParser.generateProviderInfo(
5449                         p, flags, ps.readUserState(userId), userId);
5450             }
5451         }
5452         return null;
5453     }
5454
5455     @Override
5456     public ModuleInfo getModuleInfo(String packageName, @ModuleInfoFlags int flags) {
5457         return mModuleInfoProvider.getModuleInfo(packageName, flags);
5458     }
5459
5460     @Override
5461     public List<ModuleInfo> getInstalledModules(int flags) {
5462         return mModuleInfoProvider.getInstalledModules(flags);
5463     }
5464
5465     @Override
5466     public String[] getSystemSharedLibraryNames() {
5467         // allow instant applications
5468         synchronized (mPackages) {
5469             Set<String> libs = null;
5470             final int libCount = mSharedLibraries.size();
5471             for (int i = 0; i < libCount; i++) {
5472                 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.valueAt(i);
5473                 if (versionedLib == null) {
5474                     continue;
5475                 }
5476                 final int versionCount = versionedLib.size();
5477                 for (int j = 0; j < versionCount; j++) {
5478                     SharedLibraryInfo libraryInfo = versionedLib.valueAt(j);
5479                     if (!libraryInfo.isStatic()) {
5480                         if (libs == null) {
5481                             libs = new ArraySet<>();
5482                         }
5483                         libs.add(libraryInfo.getName());
5484                         break;
5485                     }
5486                     PackageSetting ps = mSettings.getPackageLPr(libraryInfo.getPackageName());
5487                     if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(),
5488                             UserHandle.getUserId(Binder.getCallingUid()),
5489                             PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) {
5490                         if (libs == null) {
5491                             libs = new ArraySet<>();
5492                         }
5493                         libs.add(libraryInfo.getName());
5494                         break;
5495                     }
5496                 }
5497             }
5498
5499             if (libs != null) {
5500                 String[] libsArray = new String[libs.size()];
5501                 libs.toArray(libsArray);
5502                 return libsArray;
5503             }
5504
5505             return null;
5506         }
5507     }
5508
5509     @Override
5510     public @NonNull String getServicesSystemSharedLibraryPackageName() {
5511         // allow instant applications
5512         synchronized (mPackages) {
5513             return mServicesSystemSharedLibraryPackageName;
5514         }
5515     }
5516
5517     @Override
5518     public @NonNull String getSharedSystemSharedLibraryPackageName() {
5519         // allow instant applications
5520         synchronized (mPackages) {
5521             return mSharedSystemSharedLibraryPackageName;
5522         }
5523     }
5524
5525     @GuardedBy("mPackages")
5526     private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) {
5527         for (int i = userList.length - 1; i >= 0; --i) {
5528             final int userId = userList[i];
5529             // don't add instant app to the list of updates
5530             if (pkgSetting.getInstantApp(userId)) {
5531                 continue;
5532             }
5533             SparseArray<String> changedPackages = mChangedPackages.get(userId);
5534             if (changedPackages == null) {
5535                 changedPackages = new SparseArray<>();
5536                 mChangedPackages.put(userId, changedPackages);
5537             }
5538             Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId);
5539             if (sequenceNumbers == null) {
5540                 sequenceNumbers = new HashMap<>();
5541                 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers);
5542             }
5543             final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name);
5544             if (sequenceNumber != null) {
5545                 changedPackages.remove(sequenceNumber);
5546             }
5547             changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name);
5548             sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber);
5549         }
5550         mChangedPackagesSequenceNumber++;
5551     }
5552
5553     @Override
5554     public ChangedPackages getChangedPackages(int sequenceNumber, int userId) {
5555         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
5556             return null;
5557         }
5558         synchronized (mPackages) {
5559             if (sequenceNumber >= mChangedPackagesSequenceNumber) {
5560                 return null;
5561             }
5562             final SparseArray<String> changedPackages = mChangedPackages.get(userId);
5563             if (changedPackages == null) {
5564                 return null;
5565             }
5566             final List<String> packageNames =
5567                     new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber);
5568             for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) {
5569                 final String packageName = changedPackages.get(i);
5570                 if (packageName != null) {
5571                     packageNames.add(packageName);
5572                 }
5573             }
5574             return packageNames.isEmpty()
5575                     ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames);
5576         }
5577     }
5578
5579     @Override
5580     public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() {
5581         // allow instant applications
5582         ArrayList<FeatureInfo> res;
5583         synchronized (mAvailableFeatures) {
5584             res = new ArrayList<>(mAvailableFeatures.size() + 1);
5585             res.addAll(mAvailableFeatures.values());
5586         }
5587         final FeatureInfo fi = new FeatureInfo();
5588         fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
5589                 FeatureInfo.GL_ES_VERSION_UNDEFINED);
5590         res.add(fi);
5591
5592         return new ParceledListSlice<>(res);
5593     }
5594
5595     @Override
5596     public boolean hasSystemFeature(String name, int version) {
5597         // allow instant applications
5598         synchronized (mAvailableFeatures) {
5599             final FeatureInfo feat = mAvailableFeatures.get(name);
5600             if (feat == null) {
5601                 return false;
5602             } else {
5603                 return feat.version >= version;
5604             }
5605         }
5606     }
5607
5608     @Override
5609     public int checkPermission(String permName, String pkgName, int userId) {
5610         final CheckPermissionDelegate checkPermissionDelegate;
5611         synchronized (mPackages) {
5612             if (mCheckPermissionDelegate == null)  {
5613                 return checkPermissionImpl(permName, pkgName, userId);
5614             }
5615             checkPermissionDelegate = mCheckPermissionDelegate;
5616         }
5617         return checkPermissionDelegate.checkPermission(permName, pkgName, userId,
5618                 PackageManagerService.this::checkPermissionImpl);
5619     }
5620
5621     private int checkPermissionImpl(String permName, String pkgName, int userId) {
5622         return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId);
5623     }
5624
5625     @Override
5626     public int checkUidPermission(String permName, int uid) {
5627         final CheckPermissionDelegate checkPermissionDelegate;
5628         synchronized (mPackages) {
5629             if (mCheckPermissionDelegate == null)  {
5630                 return checkUidPermissionImpl(permName, uid);
5631             }
5632             checkPermissionDelegate = mCheckPermissionDelegate;
5633         }
5634         return checkPermissionDelegate.checkUidPermission(permName, uid,
5635                 PackageManagerService.this::checkUidPermissionImpl);
5636     }
5637
5638     private int checkUidPermissionImpl(String permName, int uid) {
5639         synchronized (mPackages) {
5640             final String[] packageNames = getPackagesForUid(uid);
5641             PackageParser.Package pkg = null;
5642             final int N = packageNames == null ? 0 : packageNames.length;
5643             for (int i = 0; pkg == null && i < N; i++) {
5644                 pkg = mPackages.get(packageNames[i]);
5645             }
5646             return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid());
5647         }
5648     }
5649
5650     @Override
5651     public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) {
5652         if (UserHandle.getCallingUserId() != userId) {
5653             mContext.enforceCallingPermission(
5654                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5655                     "isPermissionRevokedByPolicy for user " + userId);
5656         }
5657
5658         if (checkPermission(permission, packageName, userId)
5659                 == PackageManager.PERMISSION_GRANTED) {
5660             return false;
5661         }
5662
5663         final int callingUid = Binder.getCallingUid();
5664         if (getInstantAppPackageName(callingUid) != null) {
5665             if (!isCallerSameApp(packageName, callingUid)) {
5666                 return false;
5667             }
5668         } else {
5669             if (isInstantApp(packageName, userId)) {
5670                 return false;
5671             }
5672         }
5673
5674         final long identity = Binder.clearCallingIdentity();
5675         try {
5676             final int flags = getPermissionFlags(permission, packageName, userId);
5677             return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0;
5678         } finally {
5679             Binder.restoreCallingIdentity(identity);
5680         }
5681     }
5682
5683     @Override
5684     public String getPermissionControllerPackageName() {
5685         synchronized (mPackages) {
5686             return mRequiredPermissionControllerPackage;
5687         }
5688     }
5689
5690     String getPackageInstallerPackageName() {
5691         synchronized (mPackages) {
5692             return mRequiredInstallerPackage;
5693         }
5694     }
5695
5696     private boolean addDynamicPermission(PermissionInfo info, final boolean async) {
5697         return mPermissionManager.addDynamicPermission(
5698                 info, async, getCallingUid(), new PermissionCallback() {
5699                     @Override
5700                     public void onPermissionChanged() {
5701                         if (!async) {
5702                             mSettings.writeLPr();
5703                         } else {
5704                             scheduleWriteSettingsLocked();
5705                         }
5706                     }
5707                 });
5708     }
5709
5710     @Override
5711     public boolean addPermission(PermissionInfo info) {
5712         synchronized (mPackages) {
5713             return addDynamicPermission(info, false);
5714         }
5715     }
5716
5717     @Override
5718     public boolean addPermissionAsync(PermissionInfo info) {
5719         synchronized (mPackages) {
5720             return addDynamicPermission(info, true);
5721         }
5722     }
5723
5724     @Override
5725     public void removePermission(String permName) {
5726         mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback);
5727     }
5728
5729     @Override
5730     public void grantRuntimePermission(String packageName, String permName, final int userId) {
5731         boolean overridePolicy = (checkUidPermission(
5732                 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, Binder.getCallingUid())
5733                 == PackageManager.PERMISSION_GRANTED);
5734
5735         mPermissionManager.grantRuntimePermission(permName, packageName, overridePolicy,
5736                 getCallingUid(), userId, mPermissionCallback);
5737     }
5738
5739     @Override
5740     public void revokeRuntimePermission(String packageName, String permName, int userId) {
5741         boolean overridePolicy = (checkUidPermission(
5742                 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, Binder.getCallingUid())
5743                 == PackageManager.PERMISSION_GRANTED);
5744
5745         mPermissionManager.revokeRuntimePermission(permName, packageName, overridePolicy,
5746                 userId, mPermissionCallback);
5747     }
5748
5749     @Override
5750     public void resetRuntimePermissions() {
5751         mContext.enforceCallingOrSelfPermission(
5752                 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS,
5753                 "revokeRuntimePermission");
5754
5755         int callingUid = Binder.getCallingUid();
5756         if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
5757             mContext.enforceCallingOrSelfPermission(
5758                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5759                     "resetRuntimePermissions");
5760         }
5761
5762         synchronized (mPackages) {
5763             mPermissionManager.updateAllPermissions(
5764                     StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
5765                     mPermissionCallback);
5766             for (int userId : UserManagerService.getInstance().getUserIds()) {
5767                 final int packageCount = mPackages.size();
5768                 for (int i = 0; i < packageCount; i++) {
5769                     PackageParser.Package pkg = mPackages.valueAt(i);
5770                     if (!(pkg.mExtras instanceof PackageSetting)) {
5771                         continue;
5772                     }
5773                     PackageSetting ps = (PackageSetting) pkg.mExtras;
5774                     resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
5775                 }
5776             }
5777         }
5778     }
5779
5780     @Override
5781     public int getPermissionFlags(String permName, String packageName, int userId) {
5782         return mPermissionManager.getPermissionFlags(
5783                 permName, packageName, getCallingUid(), userId);
5784     }
5785
5786     @Override
5787     public void updatePermissionFlags(String permName, String packageName, int flagMask,
5788             int flagValues, boolean checkAdjustPolicyFlagPermission, int userId) {
5789         int callingUid = getCallingUid();
5790         boolean overridePolicy = false;
5791
5792         if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) {
5793             long callingIdentity = Binder.clearCallingIdentity();
5794             try {
5795                 if ((flagMask & FLAG_PERMISSION_POLICY_FIXED) != 0) {
5796                     if (checkAdjustPolicyFlagPermission) {
5797                         mContext.enforceCallingOrSelfPermission(
5798                                 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY,
5799                                 "Need " + Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY
5800                                         + " to change policy flags");
5801                     } else if (!hasTargetSdkInUidLowerThan(callingUid, Build.VERSION_CODES.Q)) {
5802                         throw new IllegalArgumentException(
5803                                 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY + " needs "
5804                                         + " to be checked for packages targeting "
5805                                         + Build.VERSION_CODES.Q + " or later when changing policy "
5806                                         + "flags");
5807                     }
5808
5809                     overridePolicy = true;
5810                 }
5811             } finally {
5812                 Binder.restoreCallingIdentity(callingIdentity);
5813             }
5814         }
5815
5816         mPermissionManager.updatePermissionFlags(
5817                 permName, packageName, flagMask, flagValues, callingUid, userId,
5818                 overridePolicy, mPermissionCallback);
5819     }
5820
5821     /**
5822      * Update the permission flags for all packages and runtime permissions of a user in order
5823      * to allow device or profile owner to remove POLICY_FIXED.
5824      */
5825     @Override
5826     public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) {
5827         synchronized (mPackages) {
5828             final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps(
5829                     flagMask, flagValues, getCallingUid(), userId, mPackages.values(),
5830                     mPermissionCallback);
5831             if (changed) {
5832                 mSettings.writeRuntimePermissionsForUserLPr(userId, false);
5833             }
5834         }
5835     }
5836
5837     @Override
5838     public @Nullable List<String> getWhitelistedRestrictedPermissions(@NonNull String packageName,
5839             @PermissionWhitelistFlags int whitelistFlags, @UserIdInt int userId) {
5840         Preconditions.checkNotNull(packageName);
5841         Preconditions.checkFlagsArgument(whitelistFlags,
5842                 PackageManager.FLAG_PERMISSION_WHITELIST_UPGRADE
5843                         | PackageManager.FLAG_PERMISSION_WHITELIST_SYSTEM
5844                         | PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER);
5845         Preconditions.checkArgumentNonNegative(userId, null);
5846
5847         if (UserHandle.getCallingUserId() != userId) {
5848             mContext.enforceCallingOrSelfPermission(
5849                     android.Manifest.permission.INTERACT_ACROSS_USERS,
5850                     "getWhitelistedRestrictedPermissions for user " + userId);
5851         }
5852
5853         final PackageParser.Package pkg;
5854
5855         synchronized (mPackages) {
5856             final PackageSetting packageSetting = mSettings.mPackages.get(packageName);
5857             if (packageSetting == null) {
5858                 Slog.w(TAG, "Unknown package: " + packageName);
5859                 return null;
5860             }
5861
5862             pkg = packageSetting.pkg;
5863
5864             final boolean isCallerPrivileged = mContext.checkCallingOrSelfPermission(
5865                     Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS)
5866                             == PackageManager.PERMISSION_GRANTED;
5867             final PackageSetting installerPackageSetting = mSettings.mPackages.get(
5868                     packageSetting.installerPackageName);
5869             final boolean isCallerInstallerOnRecord = installerPackageSetting != null
5870                     && UserHandle.isSameApp(installerPackageSetting.appId, Binder.getCallingUid());
5871
5872             if ((whitelistFlags & PackageManager.FLAG_PERMISSION_WHITELIST_SYSTEM) != 0
5873                     && !isCallerPrivileged) {
5874                 throw new SecurityException("Querying system whitelist requires "
5875                         + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS);
5876             }
5877
5878             if ((whitelistFlags & (PackageManager.FLAG_PERMISSION_WHITELIST_UPGRADE
5879                     | PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER)) != 0) {
5880                 if (!isCallerPrivileged && !isCallerInstallerOnRecord) {
5881                     throw new SecurityException("Querying upgrade or installer whitelist"
5882                             + " requires being installer on record or "
5883                             + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS);
5884                 }
5885             }
5886
5887             if (filterAppAccessLPr(packageSetting, Binder.getCallingUid(),
5888                     UserHandle.getCallingUserId())) {
5889                 return null;
5890             }
5891         }
5892
5893         final long identity = Binder.clearCallingIdentity();
5894         try {
5895             return mPermissionManager.getWhitelistedRestrictedPermissions(
5896                     pkg, whitelistFlags, userId);
5897         } finally {
5898             Binder.restoreCallingIdentity(identity);
5899         }
5900     }
5901
5902     @Override
5903     public boolean addWhitelistedRestrictedPermission(@NonNull String packageName,
5904             @NonNull String permission, @PermissionWhitelistFlags int whitelistFlags,
5905             @UserIdInt int userId) {
5906         // Other argument checks are done in get/setWhitelistedRestrictedPermissions
5907         Preconditions.checkNotNull(permission);
5908
5909         if (!checkExistsAndEnforceCannotModifyImmutablyRestrictedPermission(permission)) {
5910             return false;
5911         }
5912
5913         List<String> permissions = getWhitelistedRestrictedPermissions(packageName,
5914                 whitelistFlags, userId);
5915         if (permissions == null) {
5916             permissions = new ArrayList<>(1);
5917         }
5918         if (permissions.indexOf(permission) < 0) {
5919             permissions.add(permission);
5920             return setWhitelistedRestrictedPermissions(packageName, permissions,
5921                     whitelistFlags, userId);
5922         }
5923         return false;
5924     }
5925
5926     private boolean checkExistsAndEnforceCannotModifyImmutablyRestrictedPermission(
5927             @NonNull String permission) {
5928         synchronized (mPackages) {
5929             final BasePermission bp = mPermissionManager.getPermissionTEMP(permission);
5930             if (bp == null) {
5931                 Slog.w(TAG, "No such permissions: " + permission);
5932                 return false;
5933             }
5934             if (bp.isHardOrSoftRestricted() && bp.isImmutablyRestricted()
5935                     && mContext.checkCallingOrSelfPermission(
5936                     Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS)
5937                     != PackageManager.PERMISSION_GRANTED) {
5938                 throw new SecurityException("Cannot modify whitelisting of an immutably "
5939                         + "restricted permission: " + permission);
5940             }
5941             return true;
5942         }
5943     }
5944
5945     @Override
5946     public boolean removeWhitelistedRestrictedPermission(@NonNull String packageName,
5947             @NonNull String permission, @PermissionWhitelistFlags int whitelistFlags,
5948             @UserIdInt int userId) {
5949         // Other argument checks are done in get/setWhitelistedRestrictedPermissions
5950         Preconditions.checkNotNull(permission);
5951
5952         if (!checkExistsAndEnforceCannotModifyImmutablyRestrictedPermission(permission)) {
5953             return false;
5954         }
5955
5956         final List<String> permissions = getWhitelistedRestrictedPermissions(packageName,
5957                 whitelistFlags, userId);
5958         if (permissions != null && permissions.remove(permission)) {
5959             return setWhitelistedRestrictedPermissions(packageName, permissions,
5960                     whitelistFlags, userId);
5961         }
5962         return false;
5963     }
5964
5965     private boolean setWhitelistedRestrictedPermissions(@NonNull String packageName,
5966             @Nullable List<String> permissions, @PermissionWhitelistFlags int whitelistFlag,
5967             @UserIdInt int userId) {
5968         Preconditions.checkNotNull(packageName);
5969         Preconditions.checkFlagsArgument(whitelistFlag,
5970                 PackageManager.FLAG_PERMISSION_WHITELIST_UPGRADE
5971                         | PackageManager.FLAG_PERMISSION_WHITELIST_SYSTEM
5972                         | PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER);
5973         Preconditions.checkArgument(Integer.bitCount(whitelistFlag) == 1);
5974         Preconditions.checkArgumentNonNegative(userId, null);
5975
5976         if (UserHandle.getCallingUserId() != userId) {
5977             mContext.enforceCallingOrSelfPermission(
5978                     Manifest.permission.INTERACT_ACROSS_USERS,
5979                     "setWhitelistedRestrictedPermissions for user " + userId);
5980         }
5981
5982         final PackageParser.Package pkg;
5983
5984         synchronized (mPackages) {
5985             final PackageSetting packageSetting = mSettings.mPackages.get(packageName);
5986             if (packageSetting == null) {
5987                 Slog.w(TAG, "Unknown package: " + packageName);
5988                 return false;
5989             }
5990
5991             pkg = packageSetting.pkg;
5992
5993             final boolean isCallerPrivileged = mContext.checkCallingOrSelfPermission(
5994                     Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS)
5995                             == PackageManager.PERMISSION_GRANTED;
5996             final PackageSetting installerPackageSetting = mSettings.mPackages.get(
5997                     packageSetting.installerPackageName);
5998             final boolean isCallerInstallerOnRecord = installerPackageSetting != null
5999                     && UserHandle.isSameApp(installerPackageSetting.appId, Binder.getCallingUid());
6000
6001             if ((whitelistFlag & PackageManager.FLAG_PERMISSION_WHITELIST_SYSTEM) != 0
6002                     && !isCallerPrivileged) {
6003                 throw new SecurityException("Modifying system whitelist requires "
6004                         + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS);
6005             }
6006
6007             if ((whitelistFlag & PackageManager.FLAG_PERMISSION_WHITELIST_UPGRADE) != 0) {
6008                 if (!isCallerPrivileged && !isCallerInstallerOnRecord) {
6009                     throw new SecurityException("Modifying upgrade whitelist requires"
6010                             + " being installer on record or "
6011                             + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS);
6012                 }
6013                 final List<String> whitelistedPermissions = getWhitelistedRestrictedPermissions(
6014                         packageName, whitelistFlag, userId);
6015                 if (permissions == null || permissions.isEmpty()) {
6016                     if (whitelistedPermissions == null || whitelistedPermissions.isEmpty()) {
6017                         return true;
6018                     }
6019                 } else {
6020                     // Only the system can add and remove while the installer can only remove.
6021                     final int permissionCount = permissions.size();
6022                     for (int i = 0; i < permissionCount; i++) {
6023                         if ((whitelistedPermissions == null
6024                                 || !whitelistedPermissions.contains(permissions.get(i)))
6025                                 && !isCallerPrivileged) {
6026                             throw new SecurityException("Adding to upgrade whitelist requires"
6027                                     + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS);
6028                         }
6029                     }
6030                 }
6031             }
6032
6033             if ((whitelistFlag & PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER) != 0) {
6034                 if (!isCallerPrivileged && !isCallerInstallerOnRecord) {
6035                     throw new SecurityException("Modifying installer whitelist requires"
6036                             + " being installer on record or "
6037                             + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS);
6038                 }
6039             }
6040
6041             if (filterAppAccessLPr(packageSetting, Binder.getCallingUid(),
6042                     UserHandle.getCallingUserId())) {
6043                 return false;
6044             }
6045         }
6046
6047         final long identity = Binder.clearCallingIdentity();
6048         try {
6049             mPermissionManager.setWhitelistedRestrictedPermissions(pkg,
6050                     new int[]{userId}, permissions, Process.myUid(), whitelistFlag,
6051                     mPermissionCallback);
6052         } finally {
6053             Binder.restoreCallingIdentity(identity);
6054         }
6055
6056         return true;
6057     }
6058
6059     @Override
6060     public boolean shouldShowRequestPermissionRationale(String permissionName,
6061             String packageName, int userId) {
6062         if (UserHandle.getCallingUserId() != userId) {
6063             mContext.enforceCallingPermission(
6064                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
6065                     "canShowRequestPermissionRationale for user " + userId);
6066         }
6067
6068         final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId);
6069         if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) {
6070             return false;
6071         }
6072
6073         if (checkPermission(permissionName, packageName, userId)
6074                 == PackageManager.PERMISSION_GRANTED) {
6075             return false;
6076         }
6077
6078         final int flags;
6079
6080         final long identity = Binder.clearCallingIdentity();
6081         try {
6082             flags = getPermissionFlags(permissionName,
6083                     packageName, userId);
6084         } finally {
6085             Binder.restoreCallingIdentity(identity);
6086         }
6087
6088         final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED
6089                 | PackageManager.FLAG_PERMISSION_POLICY_FIXED
6090                 | PackageManager.FLAG_PERMISSION_USER_FIXED;
6091
6092         if ((flags & fixedFlags) != 0) {
6093             return false;
6094         }
6095
6096         return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0;
6097     }
6098
6099     @Override
6100     public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6101         mContext.enforceCallingOrSelfPermission(
6102                 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS,
6103                 "addOnPermissionsChangeListener");
6104
6105         synchronized (mPackages) {
6106             mOnPermissionChangeListeners.addListenerLocked(listener);
6107         }
6108     }
6109
6110     @Override
6111     public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) {
6112         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6113             throw new SecurityException("Instant applications don't have access to this method");
6114         }
6115         synchronized (mPackages) {
6116             mOnPermissionChangeListeners.removeListenerLocked(listener);
6117         }
6118     }
6119
6120     @Override
6121     public boolean isProtectedBroadcast(String actionName) {
6122         // allow instant applications
6123         synchronized (mProtectedBroadcasts) {
6124             if (mProtectedBroadcasts.contains(actionName)) {
6125                 return true;
6126             } else if (actionName != null) {
6127                 // TODO: remove these terrible hacks
6128                 if (actionName.startsWith("android.net.netmon.lingerExpired")
6129                         || actionName.startsWith("com.android.server.sip.SipWakeupTimer")
6130                         || actionName.startsWith("com.android.internal.telephony.data-reconnect")
6131                         || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) {
6132                     return true;
6133                 }
6134             }
6135         }
6136         return false;
6137     }
6138
6139     @Override
6140     public int checkSignatures(String pkg1, String pkg2) {
6141         synchronized (mPackages) {
6142             final PackageParser.Package p1 = mPackages.get(pkg1);
6143             final PackageParser.Package p2 = mPackages.get(pkg2);
6144             if (p1 == null || p1.mExtras == null
6145                     || p2 == null || p2.mExtras == null) {
6146                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6147             }
6148             final int callingUid = Binder.getCallingUid();
6149             final int callingUserId = UserHandle.getUserId(callingUid);
6150             final PackageSetting ps1 = (PackageSetting) p1.mExtras;
6151             final PackageSetting ps2 = (PackageSetting) p2.mExtras;
6152             if (filterAppAccessLPr(ps1, callingUid, callingUserId)
6153                     || filterAppAccessLPr(ps2, callingUid, callingUserId)) {
6154                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6155             }
6156             return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures);
6157         }
6158     }
6159
6160     @Override
6161     public int checkUidSignatures(int uid1, int uid2) {
6162         final int callingUid = Binder.getCallingUid();
6163         final int callingUserId = UserHandle.getUserId(callingUid);
6164         final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6165         // Map to base uids.
6166         final int appId1 = UserHandle.getAppId(uid1);
6167         final int appId2 = UserHandle.getAppId(uid2);
6168         // reader
6169         synchronized (mPackages) {
6170             Signature[] s1;
6171             Signature[] s2;
6172             Object obj = mSettings.getSettingLPr(appId1);
6173             if (obj != null) {
6174                 if (obj instanceof SharedUserSetting) {
6175                     if (isCallerInstantApp) {
6176                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6177                     }
6178                     s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
6179                 } else if (obj instanceof PackageSetting) {
6180                     final PackageSetting ps = (PackageSetting) obj;
6181                     if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6182                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6183                     }
6184                     s1 = ps.signatures.mSigningDetails.signatures;
6185                 } else {
6186                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6187                 }
6188             } else {
6189                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6190             }
6191             obj = mSettings.getSettingLPr(appId2);
6192             if (obj != null) {
6193                 if (obj instanceof SharedUserSetting) {
6194                     if (isCallerInstantApp) {
6195                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6196                     }
6197                     s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
6198                 } else if (obj instanceof PackageSetting) {
6199                     final PackageSetting ps = (PackageSetting) obj;
6200                     if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6201                         return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6202                     }
6203                     s2 = ps.signatures.mSigningDetails.signatures;
6204                 } else {
6205                     return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6206                 }
6207             } else {
6208                 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
6209             }
6210             return compareSignatures(s1, s2);
6211         }
6212     }
6213
6214     @Override
6215     public boolean hasSigningCertificate(
6216             String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) {
6217
6218         synchronized (mPackages) {
6219             final PackageParser.Package p = mPackages.get(packageName);
6220             if (p == null || p.mExtras == null) {
6221                 return false;
6222             }
6223             final int callingUid = Binder.getCallingUid();
6224             final int callingUserId = UserHandle.getUserId(callingUid);
6225             final PackageSetting ps = (PackageSetting) p.mExtras;
6226             if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6227                 return false;
6228             }
6229             switch (type) {
6230                 case CERT_INPUT_RAW_X509:
6231                     return p.mSigningDetails.hasCertificate(certificate);
6232                 case CERT_INPUT_SHA256:
6233                     return p.mSigningDetails.hasSha256Certificate(certificate);
6234                 default:
6235                     return false;
6236             }
6237         }
6238     }
6239
6240     @Override
6241     public boolean hasUidSigningCertificate(
6242             int uid, byte[] certificate, @PackageManager.CertificateInputType int type) {
6243         final int callingUid = Binder.getCallingUid();
6244         final int callingUserId = UserHandle.getUserId(callingUid);
6245         // Map to base uids.
6246         final int appId = UserHandle.getAppId(uid);
6247         // reader
6248         synchronized (mPackages) {
6249             final PackageParser.SigningDetails signingDetails;
6250             final Object obj = mSettings.getSettingLPr(appId);
6251             if (obj != null) {
6252                 if (obj instanceof SharedUserSetting) {
6253                     final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6254                     if (isCallerInstantApp) {
6255                         return false;
6256                     }
6257                     signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails;
6258                 } else if (obj instanceof PackageSetting) {
6259                     final PackageSetting ps = (PackageSetting) obj;
6260                     if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
6261                         return false;
6262                     }
6263                     signingDetails = ps.signatures.mSigningDetails;
6264                 } else {
6265                     return false;
6266                 }
6267             } else {
6268                 return false;
6269             }
6270             switch (type) {
6271                 case CERT_INPUT_RAW_X509:
6272                     return signingDetails.hasCertificate(certificate);
6273                 case CERT_INPUT_SHA256:
6274                     return signingDetails.hasSha256Certificate(certificate);
6275                 default:
6276                     return false;
6277             }
6278         }
6279     }
6280
6281     /**
6282      * This method should typically only be used when granting or revoking
6283      * permissions, since the app may immediately restart after this call.
6284      * <p>
6285      * If you're doing surgery on app code/data, use {@link PackageFreezer} to
6286      * guard your work against the app being relaunched.
6287      */
6288     private void killUid(int appId, int userId, String reason) {
6289         final long identity = Binder.clearCallingIdentity();
6290         try {
6291             IActivityManager am = ActivityManager.getService();
6292             if (am != null) {
6293                 try {
6294                     am.killUid(appId, userId, reason);
6295                 } catch (RemoteException e) {
6296                     /* ignore - same process */
6297                 }
6298             }
6299         } finally {
6300             Binder.restoreCallingIdentity(identity);
6301         }
6302     }
6303
6304     /**
6305      * If the database version for this type of package (internal storage or
6306      * external storage) is less than the version where package signatures
6307      * were updated, return true.
6308      */
6309     private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6310         return isCompatSignatureUpdateNeeded(getSettingsVersionForPackage(scannedPkg));
6311     }
6312
6313     private static boolean isCompatSignatureUpdateNeeded(VersionInfo ver) {
6314         return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY;
6315     }
6316
6317     private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
6318         return isRecoverSignatureUpdateNeeded(getSettingsVersionForPackage(scannedPkg));
6319     }
6320
6321     private static boolean isRecoverSignatureUpdateNeeded(VersionInfo ver) {
6322         return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER;
6323     }
6324
6325     @Override
6326     public List<String> getAllPackages() {
6327         final int callingUid = Binder.getCallingUid();
6328         final int callingUserId = UserHandle.getUserId(callingUid);
6329         synchronized (mPackages) {
6330             if (canViewInstantApps(callingUid, callingUserId)) {
6331                 return new ArrayList<>(mPackages.keySet());
6332             }
6333             final String instantAppPkgName = getInstantAppPackageName(callingUid);
6334             final List<String> result = new ArrayList<>();
6335             if (instantAppPkgName != null) {
6336                 // caller is an instant application; filter unexposed applications
6337                 for (PackageParser.Package pkg : mPackages.values()) {
6338                     if (!pkg.visibleToInstantApps) {
6339                         continue;
6340                     }
6341                     result.add(pkg.packageName);
6342                 }
6343             } else {
6344                 // caller is a normal application; filter instant applications
6345                 for (PackageParser.Package pkg : mPackages.values()) {
6346                     final PackageSetting ps =
6347                             pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null;
6348                     if (ps != null
6349                             && ps.getInstantApp(callingUserId)
6350                             && !mInstantAppRegistry.isInstantAccessGranted(
6351                                     callingUserId, UserHandle.getAppId(callingUid), ps.appId)) {
6352                         continue;
6353                     }
6354                     result.add(pkg.packageName);
6355                 }
6356             }
6357             return result;
6358         }
6359     }
6360
6361     /**
6362      * <em>IMPORTANT:</em> Not all packages returned by this method may be known
6363      * to the system. There are two conditions in which this may occur:
6364      * <ol>
6365      *   <li>The package is on adoptable storage and the device has been removed</li>
6366      *   <li>The package is being removed and the internal structures are partially updated</li>
6367      * </ol>
6368      * The second is an artifact of the current data structures and should be fixed. See
6369      * b/111075456 for one such instance.
6370      */
6371     @Override
6372     public String[] getPackagesForUid(int uid) {
6373         final int callingUid = Binder.getCallingUid();
6374         final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null;
6375         final int userId = UserHandle.getUserId(uid);
6376         final int appId = UserHandle.getAppId(uid);
6377         // reader
6378         synchronized (mPackages) {
6379             final Object obj = mSettings.getSettingLPr(appId);
6380             if (obj instanceof SharedUserSetting) {
6381                 if (isCallerInstantApp) {
6382                     return null;
6383                 }
6384                 final SharedUserSetting sus = (SharedUserSetting) obj;
6385                 final int N = sus.packages.size();
6386                 String[] res = new String[N];
6387                 final Iterator<PackageSetting> it = sus.packages.iterator();
6388                 int i = 0;
6389                 while (it.hasNext()) {
6390                     PackageSetting ps = it.next();
6391                     if (ps.getInstalled(userId)) {
6392                         res[i++] = ps.name;
6393                     } else {
6394                         res = ArrayUtils.removeElement(String.class, res, res[i]);
6395                     }
6396                 }
6397                 return res;
6398             } else if (obj instanceof PackageSetting) {
6399                 final PackageSetting ps = (PackageSetting) obj;
6400                 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) {
6401                     return new String[]{ps.name};
6402                 }
6403             }
6404         }
6405         return null;
6406     }
6407
6408     @Override
6409     public String getNameForUid(int uid) {
6410         final int callingUid = Binder.getCallingUid();
6411         if (getInstantAppPackageName(callingUid) != null) {
6412             return null;
6413         }
6414         final int appId = UserHandle.getAppId(uid);
6415         synchronized (mPackages) {
6416             final Object obj = mSettings.getSettingLPr(appId);
6417             if (obj instanceof SharedUserSetting) {
6418                 final SharedUserSetting sus = (SharedUserSetting) obj;
6419                 return sus.name + ":" + sus.userId;
6420             } else if (obj instanceof PackageSetting) {
6421                 final PackageSetting ps = (PackageSetting) obj;
6422                 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6423                     return null;
6424                 }
6425                 return ps.name;
6426             }
6427             return null;
6428         }
6429     }
6430
6431     @Override
6432     public String[] getNamesForUids(int[] uids) {
6433         if (uids == null || uids.length == 0) {
6434             return null;
6435         }
6436         final int callingUid = Binder.getCallingUid();
6437         if (getInstantAppPackageName(callingUid) != null) {
6438             return null;
6439         }
6440         final String[] names = new String[uids.length];
6441         synchronized (mPackages) {
6442             for (int i = uids.length - 1; i >= 0; i--) {
6443                 final int appId = UserHandle.getAppId(uids[i]);
6444                 final Object obj = mSettings.getSettingLPr(appId);
6445                 if (obj instanceof SharedUserSetting) {
6446                     final SharedUserSetting sus = (SharedUserSetting) obj;
6447                     names[i] = "shared:" + sus.name;
6448                 } else if (obj instanceof PackageSetting) {
6449                     final PackageSetting ps = (PackageSetting) obj;
6450                     if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6451                         names[i] = null;
6452                     } else {
6453                         names[i] = ps.name;
6454                     }
6455                 } else {
6456                     names[i] = null;
6457                 }
6458             }
6459         }
6460         return names;
6461     }
6462
6463     @Override
6464     public int getUidForSharedUser(String sharedUserName) {
6465         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6466             return -1;
6467         }
6468         if (sharedUserName == null) {
6469             return -1;
6470         }
6471         // reader
6472         synchronized (mPackages) {
6473             SharedUserSetting suid;
6474             try {
6475                 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
6476                 if (suid != null) {
6477                     return suid.userId;
6478                 }
6479             } catch (PackageManagerException ignore) {
6480                 // can't happen, but, still need to catch it
6481             }
6482             return -1;
6483         }
6484     }
6485
6486     @Override
6487     public int getFlagsForUid(int uid) {
6488         final int callingUid = Binder.getCallingUid();
6489         if (getInstantAppPackageName(callingUid) != null) {
6490             return 0;
6491         }
6492         final int appId = UserHandle.getAppId(uid);
6493         synchronized (mPackages) {
6494             final Object obj = mSettings.getSettingLPr(appId);
6495             if (obj instanceof SharedUserSetting) {
6496                 final SharedUserSetting sus = (SharedUserSetting) obj;
6497                 return sus.pkgFlags;
6498             } else if (obj instanceof PackageSetting) {
6499                 final PackageSetting ps = (PackageSetting) obj;
6500                 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6501                     return 0;
6502                 }
6503                 return ps.pkgFlags;
6504             }
6505         }
6506         return 0;
6507     }
6508
6509     @Override
6510     public int getPrivateFlagsForUid(int uid) {
6511         final int callingUid = Binder.getCallingUid();
6512         if (getInstantAppPackageName(callingUid) != null) {
6513             return 0;
6514         }
6515         final int appId = UserHandle.getAppId(uid);
6516         synchronized (mPackages) {
6517             final Object obj = mSettings.getSettingLPr(appId);
6518             if (obj instanceof SharedUserSetting) {
6519                 final SharedUserSetting sus = (SharedUserSetting) obj;
6520                 return sus.pkgPrivateFlags;
6521             } else if (obj instanceof PackageSetting) {
6522                 final PackageSetting ps = (PackageSetting) obj;
6523                 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
6524                     return 0;
6525                 }
6526                 return ps.pkgPrivateFlags;
6527             }
6528         }
6529         return 0;
6530     }
6531
6532     @Override
6533     public boolean isUidPrivileged(int uid) {
6534         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6535             return false;
6536         }
6537         final int appId = UserHandle.getAppId(uid);
6538         // reader
6539         synchronized (mPackages) {
6540             final Object obj = mSettings.getSettingLPr(appId);
6541             if (obj instanceof SharedUserSetting) {
6542                 final SharedUserSetting sus = (SharedUserSetting) obj;
6543                 final Iterator<PackageSetting> it = sus.packages.iterator();
6544                 while (it.hasNext()) {
6545                     if (it.next().isPrivileged()) {
6546                         return true;
6547                     }
6548                 }
6549             } else if (obj instanceof PackageSetting) {
6550                 final PackageSetting ps = (PackageSetting) obj;
6551                 return ps.isPrivileged();
6552             }
6553         }
6554         return false;
6555     }
6556
6557     @Override
6558     public String[] getAppOpPermissionPackages(String permName) {
6559         return mPermissionManager.getAppOpPermissionPackages(permName);
6560     }
6561
6562     @Override
6563     public ResolveInfo resolveIntent(Intent intent, String resolvedType,
6564             int flags, int userId) {
6565         return resolveIntentInternal(intent, resolvedType, flags, userId, false,
6566                 Binder.getCallingUid());
6567     }
6568
6569     /**
6570      * Normally instant apps can only be resolved when they're visible to the caller.
6571      * However, if {@code resolveForStart} is {@code true}, all instant apps are visible
6572      * since we need to allow the system to start any installed application.
6573      */
6574     private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType,
6575             int flags, int userId, boolean resolveForStart, int filterCallingUid) {
6576         try {
6577             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent");
6578
6579             if (!sUserManager.exists(userId)) return null;
6580             final int callingUid = Binder.getCallingUid();
6581             flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart);
6582             mPermissionManager.enforceCrossUserPermission(callingUid, userId,
6583                     false /*requireFullPermission*/, false /*checkShell*/, "resolve intent");
6584
6585             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
6586             final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType,
6587                     flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/);
6588             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6589
6590             final ResolveInfo bestChoice =
6591                     chooseBestActivity(intent, resolvedType, flags, query, userId);
6592             return bestChoice;
6593         } finally {
6594             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
6595         }
6596     }
6597
6598     @Override
6599     public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) {
6600         if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) {
6601             throw new SecurityException(
6602                     "findPersistentPreferredActivity can only be run by the system");
6603         }
6604         if (!sUserManager.exists(userId)) {
6605             return null;
6606         }
6607         final int callingUid = Binder.getCallingUid();
6608         intent = updateIntentForResolve(intent);
6609         final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
6610         final int flags = updateFlagsForResolve(
6611                 0, userId, intent, callingUid, false /*includeInstantApps*/);
6612         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6613                 userId);
6614         synchronized (mPackages) {
6615             return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false,
6616                     userId);
6617         }
6618     }
6619
6620     @Override
6621     public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
6622             IntentFilter filter, int match, ComponentName activity) {
6623         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6624             return;
6625         }
6626         final int userId = UserHandle.getCallingUserId();
6627         if (DEBUG_PREFERRED) {
6628             Log.v(TAG, "setLastChosenActivity intent=" + intent
6629                 + " resolvedType=" + resolvedType
6630                 + " flags=" + flags
6631                 + " filter=" + filter
6632                 + " match=" + match
6633                 + " activity=" + activity);
6634             filter.dump(new PrintStreamPrinter(System.out), "    ");
6635         }
6636         intent.setComponent(null);
6637         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6638                 userId);
6639         // Find any earlier preferred or last chosen entries and nuke them
6640         findPreferredActivityNotLocked(
6641                 intent, resolvedType, flags, query, 0, false, true, false, userId);
6642         // Add the new activity as the last chosen for this filter
6643         addPreferredActivityInternal(filter, match, null, activity, false, userId,
6644                 "Setting last chosen");
6645     }
6646
6647     @Override
6648     public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
6649         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
6650             return null;
6651         }
6652         final int userId = UserHandle.getCallingUserId();
6653         if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
6654         final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags,
6655                 userId);
6656         return findPreferredActivityNotLocked(
6657                 intent, resolvedType, flags, query, 0, false, false, false, userId);
6658     }
6659
6660     /**
6661      * Returns whether or not instant apps have been disabled remotely.
6662      */
6663     private boolean areWebInstantAppsDisabled(int userId) {
6664         return mWebInstantAppsDisabled.get(userId);
6665     }
6666
6667     private boolean isInstantAppResolutionAllowed(
6668             Intent intent, List<ResolveInfo> resolvedActivities, int userId,
6669             boolean skipPackageCheck) {
6670         if (mInstantAppResolverConnection == null) {
6671             return false;
6672         }
6673         if (mInstantAppInstallerActivity == null) {
6674             return false;
6675         }
6676         if (intent.getComponent() != null) {
6677             return false;
6678         }
6679         if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) {
6680             return false;
6681         }
6682         if (!skipPackageCheck && intent.getPackage() != null) {
6683             return false;
6684         }
6685         if (!intent.isWebIntent()) {
6686             // for non web intents, we should not resolve externally if an app already exists to
6687             // handle it or if the caller didn't explicitly request it.
6688             if ((resolvedActivities != null && resolvedActivities.size() != 0)
6689                     || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) {
6690                 return false;
6691             }
6692         } else {
6693             if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) {
6694                 return false;
6695             } else if (areWebInstantAppsDisabled(userId)) {
6696                 return false;
6697             }
6698         }
6699         // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution.
6700         // Or if there's already an ephemeral app installed that handles the action
6701         synchronized (mPackages) {
6702             final int count = (resolvedActivities == null ? 0 : resolvedActivities.size());
6703             for (int n = 0; n < count; n++) {
6704                 final ResolveInfo info = resolvedActivities.get(n);
6705                 final String packageName = info.activityInfo.packageName;
6706                 final PackageSetting ps = mSettings.mPackages.get(packageName);
6707                 if (ps != null) {
6708                     // only check domain verification status if the app is not a browser
6709                     if (!info.handleAllWebDataURI) {
6710                         // Try to get the status from User settings first
6711                         final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6712                         final int status = (int) (packedStatus >> 32);
6713                         if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS
6714                             || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6715                             if (DEBUG_INSTANT) {
6716                                 Slog.v(TAG, "DENY instant app;"
6717                                     + " pkg: " + packageName + ", status: " + status);
6718                             }
6719                             return false;
6720                         }
6721                     }
6722                     if (ps.getInstantApp(userId)) {
6723                         if (DEBUG_INSTANT) {
6724                             Slog.v(TAG, "DENY instant app installed;"
6725                                     + " pkg: " + packageName);
6726                         }
6727                         return false;
6728                     }
6729                 }
6730             }
6731         }
6732         // We've exhausted all ways to deny ephemeral application; let the system look for them.
6733         return true;
6734     }
6735
6736     private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
6737             Intent origIntent, String resolvedType, String callingPackage,
6738             Bundle verificationBundle, int userId) {
6739         final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO,
6740                 new InstantAppRequest(responseObj, origIntent, resolvedType,
6741                         callingPackage, userId, verificationBundle, false /*resolveForStart*/));
6742         mHandler.sendMessage(msg);
6743     }
6744
6745     private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
6746             int flags, List<ResolveInfo> query, int userId) {
6747         if (query != null) {
6748             final int N = query.size();
6749             if (N == 1) {
6750                 return query.get(0);
6751             } else if (N > 1) {
6752                 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
6753                 // If there is more than one activity with the same priority,
6754                 // then let the user decide between them.
6755                 ResolveInfo r0 = query.get(0);
6756                 ResolveInfo r1 = query.get(1);
6757                 if (DEBUG_INTENT_MATCHING || debug) {
6758                     Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
6759                             + r1.activityInfo.name + "=" + r1.priority);
6760                 }
6761                 // If the first activity has a higher priority, or a different
6762                 // default, then it is always desirable to pick it.
6763                 if (r0.priority != r1.priority
6764                         || r0.preferredOrder != r1.preferredOrder
6765                         || r0.isDefault != r1.isDefault) {
6766                     return query.get(0);
6767                 }
6768                 // If we have saved a preference for a preferred activity for
6769                 // this Intent, use that.
6770                 ResolveInfo ri = findPreferredActivityNotLocked(intent, resolvedType,
6771                         flags, query, r0.priority, true, false, debug, userId);
6772                 if (ri != null) {
6773                     return ri;
6774                 }
6775                 // If we have an ephemeral app, use it
6776                 for (int i = 0; i < N; i++) {
6777                     ri = query.get(i);
6778                     if (ri.activityInfo.applicationInfo.isInstantApp()) {
6779                         final String packageName = ri.activityInfo.packageName;
6780                         final PackageSetting ps = mSettings.mPackages.get(packageName);
6781                         final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
6782                         final int status = (int)(packedStatus >> 32);
6783                         if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
6784                             return ri;
6785                         }
6786                     }
6787                 }
6788                 ri = new ResolveInfo(mResolveInfo);
6789                 ri.activityInfo = new ActivityInfo(ri.activityInfo);
6790                 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction());
6791                 // If all of the options come from the same package, show the application's
6792                 // label and icon instead of the generic resolver's.
6793                 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here
6794                 // and then throw away the ResolveInfo itself, meaning that the caller loses
6795                 // the resolvePackageName. Therefore the activityInfo.labelRes above provides
6796                 // a fallback for this case; we only set the target package's resources on
6797                 // the ResolveInfo, not the ActivityInfo.
6798                 final String intentPackage = intent.getPackage();
6799                 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) {
6800                     final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo;
6801                     ri.resolvePackageName = intentPackage;
6802                     if (userNeedsBadging(userId)) {
6803                         ri.noResourceId = true;
6804                     } else {
6805                         ri.icon = appi.icon;
6806                     }
6807                     ri.iconResourceId = appi.icon;
6808                     ri.labelRes = appi.labelRes;
6809                 }
6810                 ri.activityInfo.applicationInfo = new ApplicationInfo(
6811                         ri.activityInfo.applicationInfo);
6812                 if (userId != 0) {
6813                     ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
6814                             UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
6815                 }
6816                 // Make sure that the resolver is displayable in car mode
6817                 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle();
6818                 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true);
6819                 return ri;
6820             }
6821         }
6822         return null;
6823     }
6824
6825     /**
6826      * Return true if the given list is not empty and all of its contents have
6827      * an activityInfo with the given package name.
6828      */
6829     private boolean allHavePackage(List<ResolveInfo> list, String packageName) {
6830         if (ArrayUtils.isEmpty(list)) {
6831             return false;
6832         }
6833         for (int i = 0, N = list.size(); i < N; i++) {
6834             final ResolveInfo ri = list.get(i);
6835             final ActivityInfo ai = ri != null ? ri.activityInfo : null;
6836             if (ai == null || !packageName.equals(ai.packageName)) {
6837                 return false;
6838             }
6839         }
6840         return true;
6841     }
6842
6843     @GuardedBy("mPackages")
6844     private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
6845             int flags, List<ResolveInfo> query, boolean debug, int userId) {
6846         final int N = query.size();
6847         PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
6848                 .get(userId);
6849         // Get the list of persistent preferred activities that handle the intent
6850         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
6851         List<PersistentPreferredActivity> pprefs = ppir != null
6852                 ? ppir.queryIntent(intent, resolvedType,
6853                         (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6854                         userId)
6855                 : null;
6856         if (pprefs != null && pprefs.size() > 0) {
6857             final int M = pprefs.size();
6858             for (int i=0; i<M; i++) {
6859                 final PersistentPreferredActivity ppa = pprefs.get(i);
6860                 if (DEBUG_PREFERRED || debug) {
6861                     Slog.v(TAG, "Checking PersistentPreferredActivity ds="
6862                             + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
6863                             + "\n  component=" + ppa.mComponent);
6864                     ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6865                 }
6866                 final ActivityInfo ai = getActivityInfo(ppa.mComponent,
6867                         flags | MATCH_DISABLED_COMPONENTS, userId);
6868                 if (DEBUG_PREFERRED || debug) {
6869                     Slog.v(TAG, "Found persistent preferred activity:");
6870                     if (ai != null) {
6871                         ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6872                     } else {
6873                         Slog.v(TAG, "  null");
6874                     }
6875                 }
6876                 if (ai == null) {
6877                     // This previously registered persistent preferred activity
6878                     // component is no longer known. Ignore it and do NOT remove it.
6879                     continue;
6880                 }
6881                 for (int j=0; j<N; j++) {
6882                     final ResolveInfo ri = query.get(j);
6883                     if (!ri.activityInfo.applicationInfo.packageName
6884                             .equals(ai.applicationInfo.packageName)) {
6885                         continue;
6886                     }
6887                     if (!ri.activityInfo.name.equals(ai.name)) {
6888                         continue;
6889                     }
6890                     //  Found a persistent preference that can handle the intent.
6891                     if (DEBUG_PREFERRED || debug) {
6892                         Slog.v(TAG, "Returning persistent preferred activity: " +
6893                                 ri.activityInfo.packageName + "/" + ri.activityInfo.name);
6894                     }
6895                     return ri;
6896                 }
6897             }
6898         }
6899         return null;
6900     }
6901
6902     private boolean isHomeIntent(Intent intent) {
6903         return ACTION_MAIN.equals(intent.getAction())
6904                 && intent.hasCategory(CATEGORY_HOME)
6905                 && intent.hasCategory(CATEGORY_DEFAULT);
6906     }
6907
6908     // TODO: handle preferred activities missing while user has amnesia
6909     /** <b>must not hold {@link #mPackages}</b> */
6910     ResolveInfo findPreferredActivityNotLocked(Intent intent, String resolvedType, int flags,
6911             List<ResolveInfo> query, int priority, boolean always,
6912             boolean removeMatches, boolean debug, int userId) {
6913         if (Thread.holdsLock(mPackages)) {
6914             Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName()
6915                     + " is holding mPackages", new Throwable());
6916         }
6917         if (!sUserManager.exists(userId)) return null;
6918         final int callingUid = Binder.getCallingUid();
6919         // Do NOT hold the packages lock; this calls up into the settings provider which
6920         // could cause a deadlock.
6921         final boolean isDeviceProvisioned =
6922                 android.provider.Settings.Global.getInt(mContext.getContentResolver(),
6923                         android.provider.Settings.Global.DEVICE_PROVISIONED, 0) == 1;
6924         flags = updateFlagsForResolve(
6925                 flags, userId, intent, callingUid, false /*includeInstantApps*/);
6926         intent = updateIntentForResolve(intent);
6927         // writer
6928         synchronized (mPackages) {
6929             // Try to find a matching persistent preferred activity.
6930             ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
6931                     debug, userId);
6932
6933             // If a persistent preferred activity matched, use it.
6934             if (pri != null) {
6935                 return pri;
6936             }
6937
6938             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
6939             // Get the list of preferred activities that handle the intent
6940             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
6941             List<PreferredActivity> prefs = pir != null
6942                     ? pir.queryIntent(intent, resolvedType,
6943                             (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0,
6944                             userId)
6945                     : null;
6946             if (prefs != null && prefs.size() > 0) {
6947                 boolean changed = false;
6948                 try {
6949                     // First figure out how good the original match set is.
6950                     // We will only allow preferred activities that came
6951                     // from the same match quality.
6952                     int match = 0;
6953
6954                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
6955
6956                     final int N = query.size();
6957                     for (int j=0; j<N; j++) {
6958                         final ResolveInfo ri = query.get(j);
6959                         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
6960                                 + ": 0x" + Integer.toHexString(match));
6961                         if (ri.match > match) {
6962                             match = ri.match;
6963                         }
6964                     }
6965
6966                     if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
6967                             + Integer.toHexString(match));
6968
6969                     match &= IntentFilter.MATCH_CATEGORY_MASK;
6970                     final int M = prefs.size();
6971                     for (int i=0; i<M; i++) {
6972                         final PreferredActivity pa = prefs.get(i);
6973                         if (DEBUG_PREFERRED || debug) {
6974                             Slog.v(TAG, "Checking PreferredActivity ds="
6975                                     + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
6976                                     + "\n  component=" + pa.mPref.mComponent);
6977                             pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6978                         }
6979                         if (pa.mPref.mMatch != match) {
6980                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
6981                                     + Integer.toHexString(pa.mPref.mMatch));
6982                             continue;
6983                         }
6984                         // If it's not an "always" type preferred activity and that's what we're
6985                         // looking for, skip it.
6986                         if (always && !pa.mPref.mAlways) {
6987                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
6988                             continue;
6989                         }
6990                         final ActivityInfo ai = getActivityInfo(
6991                                 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS
6992                                         | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE,
6993                                 userId);
6994                         if (DEBUG_PREFERRED || debug) {
6995                             Slog.v(TAG, "Found preferred activity:");
6996                             if (ai != null) {
6997                                 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
6998                             } else {
6999                                 Slog.v(TAG, "  null");
7000                             }
7001                         }
7002                         final boolean excludeSetupWizardHomeActivity = isHomeIntent(intent)
7003                                 && !isDeviceProvisioned;
7004                         if (ai == null) {
7005                             // Do not remove launcher's preferred activity during SetupWizard
7006                             // due to it may not install yet
7007                             if (excludeSetupWizardHomeActivity) {
7008                                 continue;
7009                             }
7010
7011                             // This previously registered preferred activity
7012                             // component is no longer known.  Most likely an update
7013                             // to the app was installed and in the new version this
7014                             // component no longer exists.  Clean it up by removing
7015                             // it from the preferred activities list, and skip it.
7016                             Slog.w(TAG, "Removing dangling preferred activity: "
7017                                     + pa.mPref.mComponent);
7018                             pir.removeFilter(pa);
7019                             changed = true;
7020                             continue;
7021                         }
7022                         for (int j=0; j<N; j++) {
7023                             final ResolveInfo ri = query.get(j);
7024                             if (!ri.activityInfo.applicationInfo.packageName
7025                                     .equals(ai.applicationInfo.packageName)) {
7026                                 continue;
7027                             }
7028                             if (!ri.activityInfo.name.equals(ai.name)) {
7029                                 continue;
7030                             }
7031
7032                             if (removeMatches) {
7033                                 pir.removeFilter(pa);
7034                                 changed = true;
7035                                 if (DEBUG_PREFERRED) {
7036                                     Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
7037                                 }
7038                                 break;
7039                             }
7040
7041                             // Okay we found a previously set preferred or last chosen app.
7042                             // If the result set is different from when this
7043                             // was created, and is not a subset of the preferred set, we need to
7044                             // clear it and re-ask the user their preference, if we're looking for
7045                             // an "always" type entry.
7046
7047                             if (always && !pa.mPref.sameSet(query, excludeSetupWizardHomeActivity)) {
7048                                 if (pa.mPref.isSuperset(query, excludeSetupWizardHomeActivity)) {
7049                                     if (!excludeSetupWizardHomeActivity) {
7050                                         // some components of the set are no longer present in
7051                                         // the query, but the preferred activity can still be reused
7052                                         if (DEBUG_PREFERRED) {
7053                                             Slog.i(TAG, "Result set changed, but PreferredActivity"
7054                                                     + " is still valid as only non-preferred"
7055                                                     + " components were removed for " + intent
7056                                                     + " type " + resolvedType);
7057                                         }
7058                                         // remove obsolete components and re-add the up-to-date
7059                                         // filter
7060                                         PreferredActivity freshPa = new PreferredActivity(pa,
7061                                                 pa.mPref.mMatch,
7062                                                 pa.mPref.discardObsoleteComponents(query),
7063                                                 pa.mPref.mComponent,
7064                                                 pa.mPref.mAlways);
7065                                         pir.removeFilter(pa);
7066                                         pir.addFilter(freshPa);
7067                                         changed = true;
7068                                     } else {
7069                                         if (DEBUG_PREFERRED) {
7070                                             Slog.i(TAG, "Do not remove preferred activity for launcher"
7071                                                     + " during SetupWizard");
7072                                         }
7073                                     }
7074                                 } else {
7075                                     Slog.i(TAG,
7076                                             "Result set changed, dropping preferred activity for "
7077                                                     + intent + " type " + resolvedType);
7078                                     if (DEBUG_PREFERRED) {
7079                                         Slog.v(TAG, "Removing preferred activity since set changed "
7080                                                 + pa.mPref.mComponent);
7081                                     }
7082                                     pir.removeFilter(pa);
7083                                     // Re-add the filter as a "last chosen" entry (!always)
7084                                     PreferredActivity lastChosen = new PreferredActivity(
7085                                             pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
7086                                     pir.addFilter(lastChosen);
7087                                     changed = true;
7088                                     return null;
7089                                 }
7090                             }
7091
7092                             // Yay! Either the set matched or we're looking for the last chosen
7093                             if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
7094                                     + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
7095                             return ri;
7096                         }
7097                     }
7098                 } finally {
7099                     if (changed) {
7100                         if (DEBUG_PREFERRED) {
7101                             Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
7102                         }
7103                         scheduleWritePackageRestrictionsLocked(userId);
7104                     }
7105                 }
7106             }
7107         }
7108         if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
7109         return null;
7110     }
7111
7112     /*
7113      * Returns if intent can be forwarded from the sourceUserId to the targetUserId
7114      */
7115     @Override
7116     public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
7117             int targetUserId) {
7118         mContext.enforceCallingOrSelfPermission(
7119                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
7120         List<CrossProfileIntentFilter> matches =
7121                 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
7122         if (matches != null) {
7123             int size = matches.size();
7124             for (int i = 0; i < size; i++) {
7125                 if (matches.get(i).getTargetUserId() == targetUserId) return true;
7126             }
7127         }
7128         if (intent.hasWebURI()) {
7129             // cross-profile app linking works only towards the parent.
7130             final int callingUid = Binder.getCallingUid();
7131             final UserInfo parent = getProfileParent(sourceUserId);
7132             synchronized(mPackages) {
7133                 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid,
7134                         false /*includeInstantApps*/);
7135                 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr(
7136                         intent, resolvedType, flags, sourceUserId, parent.id);
7137                 return xpDomainInfo != null;
7138             }
7139         }
7140         return false;
7141     }
7142
7143     private UserInfo getProfileParent(int userId) {
7144         final long identity = Binder.clearCallingIdentity();
7145         try {
7146             return sUserManager.getProfileParent(userId);
7147         } finally {
7148             Binder.restoreCallingIdentity(identity);
7149         }
7150     }
7151
7152     private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
7153             String resolvedType, int userId) {
7154         CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
7155         if (resolver != null) {
7156             return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId);
7157         }
7158         return null;
7159     }
7160
7161     @Override
7162     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent,
7163             String resolvedType, int flags, int userId) {
7164         try {
7165             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities");
7166
7167             return new ParceledListSlice<>(
7168                     queryIntentActivitiesInternal(intent, resolvedType, flags, userId));
7169         } finally {
7170             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7171         }
7172     }
7173
7174     /**
7175      * Returns the package name of the calling Uid if it's an instant app. If it isn't
7176      * instant, returns {@code null}.
7177      */
7178     private String getInstantAppPackageName(int callingUid) {
7179         synchronized (mPackages) {
7180             // If the caller is an isolated app use the owner's uid for the lookup.
7181             if (Process.isIsolated(callingUid)) {
7182                 callingUid = mIsolatedOwners.get(callingUid);
7183             }
7184             final int appId = UserHandle.getAppId(callingUid);
7185             final Object obj = mSettings.getSettingLPr(appId);
7186             if (obj instanceof PackageSetting) {
7187                 final PackageSetting ps = (PackageSetting) obj;
7188                 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid));
7189                 return isInstantApp ? ps.pkg.packageName : null;
7190             }
7191         }
7192         return null;
7193     }
7194
7195     private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7196             String resolvedType, int flags, int userId) {
7197         return queryIntentActivitiesInternal(
7198                 intent, resolvedType, flags, Binder.getCallingUid(), userId,
7199                 false /*resolveForStart*/, true /*allowDynamicSplits*/);
7200     }
7201
7202     private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent,
7203             String resolvedType, int flags, int filterCallingUid, int userId,
7204             boolean resolveForStart, boolean allowDynamicSplits) {
7205         if (!sUserManager.exists(userId)) return Collections.emptyList();
7206         final String instantAppPkgName = getInstantAppPackageName(filterCallingUid);
7207         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
7208                 false /* requireFullPermission */, false /* checkShell */,
7209                 "query intent activities");
7210         final String pkgName = intent.getPackage();
7211         ComponentName comp = intent.getComponent();
7212         if (comp == null) {
7213             if (intent.getSelector() != null) {
7214                 intent = intent.getSelector();
7215                 comp = intent.getComponent();
7216             }
7217         }
7218
7219         flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart,
7220                 comp != null || pkgName != null /*onlyExposedExplicitly*/);
7221         if (comp != null) {
7222             final List<ResolveInfo> list = new ArrayList<>(1);
7223             final ActivityInfo ai = getActivityInfo(comp, flags, userId);
7224             if (ai != null) {
7225                 // When specifying an explicit component, we prevent the activity from being
7226                 // used when either 1) the calling package is normal and the activity is within
7227                 // an ephemeral application or 2) the calling package is ephemeral and the
7228                 // activity is not visible to ephemeral applications.
7229                 final boolean matchInstantApp =
7230                         (flags & PackageManager.MATCH_INSTANT) != 0;
7231                 final boolean matchVisibleToInstantAppOnly =
7232                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
7233                 final boolean matchExplicitlyVisibleOnly =
7234                         (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
7235                 final boolean isCallerInstantApp =
7236                         instantAppPkgName != null;
7237                 final boolean isTargetSameInstantApp =
7238                         comp.getPackageName().equals(instantAppPkgName);
7239                 final boolean isTargetInstantApp =
7240                         (ai.applicationInfo.privateFlags
7241                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
7242                 final boolean isTargetVisibleToInstantApp =
7243                         (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
7244                 final boolean isTargetExplicitlyVisibleToInstantApp =
7245                         isTargetVisibleToInstantApp
7246                         && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
7247                 final boolean isTargetHiddenFromInstantApp =
7248                         !isTargetVisibleToInstantApp
7249                         || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
7250                 final boolean blockResolution =
7251                         !isTargetSameInstantApp
7252                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
7253                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
7254                                         && isTargetHiddenFromInstantApp));
7255                 if (!blockResolution) {
7256                     final ResolveInfo ri = new ResolveInfo();
7257                     ri.activityInfo = ai;
7258                     list.add(ri);
7259                 }
7260             }
7261             return applyPostResolutionFilter(
7262                     list, instantAppPkgName, allowDynamicSplits, filterCallingUid, resolveForStart,
7263                     userId, intent);
7264         }
7265
7266         // reader
7267         boolean sortResult = false;
7268         boolean addInstant = false;
7269         List<ResolveInfo> result;
7270         synchronized (mPackages) {
7271             if (pkgName == null) {
7272                 List<CrossProfileIntentFilter> matchingFilters =
7273                         getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
7274                 // Check for results that need to skip the current profile.
7275                 ResolveInfo xpResolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
7276                         resolvedType, flags, userId);
7277                 if (xpResolveInfo != null) {
7278                     List<ResolveInfo> xpResult = new ArrayList<>(1);
7279                     xpResult.add(xpResolveInfo);
7280                     return applyPostResolutionFilter(
7281                             filterIfNotSystemUser(xpResult, userId), instantAppPkgName,
7282                             allowDynamicSplits, filterCallingUid, resolveForStart, userId, intent);
7283                 }
7284
7285                 // Check for results in the current profile.
7286                 result = filterIfNotSystemUser(mComponentResolver.queryActivities(
7287                         intent, resolvedType, flags, userId), userId);
7288                 addInstant = isInstantAppResolutionAllowed(intent, result, userId,
7289                         false /*skipPackageCheck*/);
7290                 // Check for cross profile results.
7291                 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result);
7292                 xpResolveInfo = queryCrossProfileIntents(
7293                         matchingFilters, intent, resolvedType, flags, userId,
7294                         hasNonNegativePriorityResult);
7295                 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
7296                     boolean isVisibleToUser = filterIfNotSystemUser(
7297                             Collections.singletonList(xpResolveInfo), userId).size() > 0;
7298                     if (isVisibleToUser) {
7299                         result.add(xpResolveInfo);
7300                         sortResult = true;
7301                     }
7302                 }
7303                 if (intent.hasWebURI()) {
7304                     CrossProfileDomainInfo xpDomainInfo = null;
7305                     final UserInfo parent = getProfileParent(userId);
7306                     if (parent != null) {
7307                         xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType,
7308                                 flags, userId, parent.id);
7309                     }
7310                     if (xpDomainInfo != null) {
7311                         if (xpResolveInfo != null) {
7312                             // If we didn't remove it, the cross-profile ResolveInfo would be twice
7313                             // in the result.
7314                             result.remove(xpResolveInfo);
7315                         }
7316                         if (result.size() == 0 && !addInstant) {
7317                             // No result in current profile, but found candidate in parent user.
7318                             // And we are not going to add emphemeral app, so we can return the
7319                             // result straight away.
7320                             result.add(xpDomainInfo.resolveInfo);
7321                             return applyPostResolutionFilter(result, instantAppPkgName,
7322                                     allowDynamicSplits, filterCallingUid, resolveForStart, userId,
7323                                     intent);
7324                         }
7325                     } else if (result.size() <= 1 && !addInstant) {
7326                         // No result in parent user and <= 1 result in current profile, and we
7327                         // are not going to add emphemeral app, so we can return the result without
7328                         // further processing.
7329                         return applyPostResolutionFilter(result, instantAppPkgName,
7330                                 allowDynamicSplits, filterCallingUid, resolveForStart, userId,
7331                                 intent);
7332                     }
7333                     // We have more than one candidate (combining results from current and parent
7334                     // profile), so we need filtering and sorting.
7335                     result = filterCandidatesWithDomainPreferredActivitiesLPr(
7336                             intent, flags, result, xpDomainInfo, userId);
7337                     sortResult = true;
7338                 }
7339             } else {
7340                 final PackageParser.Package pkg = mPackages.get(pkgName);
7341                 result = null;
7342                 if (pkg != null) {
7343                     result = filterIfNotSystemUser(mComponentResolver.queryActivities(
7344                             intent, resolvedType, flags, pkg.activities, userId), userId);
7345                 }
7346                 if (result == null || result.size() == 0) {
7347                     // the caller wants to resolve for a particular package; however, there
7348                     // were no installed results, so, try to find an ephemeral result
7349                     addInstant = isInstantAppResolutionAllowed(
7350                                     intent, null /*result*/, userId, true /*skipPackageCheck*/);
7351                     if (result == null) {
7352                         result = new ArrayList<>();
7353                     }
7354                 }
7355             }
7356         }
7357         if (addInstant) {
7358             result = maybeAddInstantAppInstaller(
7359                     result, intent, resolvedType, flags, userId, resolveForStart);
7360         }
7361         if (sortResult) {
7362             Collections.sort(result, RESOLVE_PRIORITY_SORTER);
7363         }
7364         return applyPostResolutionFilter(
7365                 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, resolveForStart,
7366                 userId, intent);
7367     }
7368
7369     private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent,
7370             String resolvedType, int flags, int userId, boolean resolveForStart) {
7371         // first, check to see if we've got an instant app already installed
7372         final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0;
7373         ResolveInfo localInstantApp = null;
7374         boolean blockResolution = false;
7375         if (!alreadyResolvedLocally) {
7376             final List<ResolveInfo> instantApps = mComponentResolver.queryActivities(
7377                     intent,
7378                     resolvedType,
7379                     flags
7380                         | PackageManager.GET_RESOLVED_FILTER
7381                         | PackageManager.MATCH_INSTANT
7382                         | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY,
7383                     userId);
7384             for (int i = instantApps.size() - 1; i >= 0; --i) {
7385                 final ResolveInfo info = instantApps.get(i);
7386                 final String packageName = info.activityInfo.packageName;
7387                 final PackageSetting ps = mSettings.mPackages.get(packageName);
7388                 if (ps.getInstantApp(userId)) {
7389                     final long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7390                     final int status = (int)(packedStatus >> 32);
7391                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7392                         // there's a local instant application installed, but, the user has
7393                         // chosen to never use it; skip resolution and don't acknowledge
7394                         // an instant application is even available
7395                         if (DEBUG_INSTANT) {
7396                             Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName);
7397                         }
7398                         blockResolution = true;
7399                         break;
7400                     } else {
7401                         // we have a locally installed instant application; skip resolution
7402                         // but acknowledge there's an instant application available
7403                         if (DEBUG_INSTANT) {
7404                             Slog.v(TAG, "Found installed instant app; pkg: " + packageName);
7405                         }
7406                         localInstantApp = info;
7407                         break;
7408                     }
7409                 }
7410             }
7411         }
7412         // no app installed, let's see if one's available
7413         AuxiliaryResolveInfo auxiliaryResponse = null;
7414         if (!blockResolution) {
7415             if (localInstantApp == null) {
7416                 // we don't have an instant app locally, resolve externally
7417                 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral");
7418                 final InstantAppRequest requestObject = new InstantAppRequest(
7419                         null /*responseObj*/, intent /*origIntent*/, resolvedType,
7420                         null /*callingPackage*/, userId, null /*verificationBundle*/,
7421                         resolveForStart);
7422                 auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(
7423                         mInstantAppResolverConnection, requestObject);
7424                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
7425             } else {
7426                 // we have an instant application locally, but, we can't admit that since
7427                 // callers shouldn't be able to determine prior browsing. create a dummy
7428                 // auxiliary response so the downstream code behaves as if there's an
7429                 // instant application available externally. when it comes time to start
7430                 // the instant application, we'll do the right thing.
7431                 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo;
7432                 auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */,
7433                                         ai.packageName, ai.longVersionCode, null /* splitName */);
7434             }
7435         }
7436         if (intent.isWebIntent() && auxiliaryResponse == null) {
7437             return result;
7438         }
7439         final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName);
7440         if (ps == null
7441                 || !ps.readUserState(userId).isEnabled(mInstantAppInstallerActivity, 0)) {
7442             return result;
7443         }
7444         final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo);
7445         ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo(
7446                 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId);
7447         ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
7448                 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
7449         // add a non-generic filter
7450         ephemeralInstaller.filter = new IntentFilter();
7451         if (intent.getAction() != null) {
7452             ephemeralInstaller.filter.addAction(intent.getAction());
7453         }
7454         if (intent.getData() != null && intent.getData().getPath() != null) {
7455             ephemeralInstaller.filter.addDataPath(
7456                     intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL);
7457         }
7458         ephemeralInstaller.isInstantAppAvailable = true;
7459         // make sure this resolver is the default
7460         ephemeralInstaller.isDefault = true;
7461         ephemeralInstaller.auxiliaryInfo = auxiliaryResponse;
7462         if (DEBUG_INSTANT) {
7463             Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
7464         }
7465
7466         result.add(ephemeralInstaller);
7467         return result;
7468     }
7469
7470     private static class CrossProfileDomainInfo {
7471         /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */
7472         ResolveInfo resolveInfo;
7473         /* Best domain verification status of the activities found in the other profile */
7474         int bestDomainVerificationStatus;
7475     }
7476
7477     private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent,
7478             String resolvedType, int flags, int sourceUserId, int parentUserId) {
7479         if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING,
7480                 sourceUserId)) {
7481             return null;
7482         }
7483         List<ResolveInfo> resultTargetUser = mComponentResolver.queryActivities(intent,
7484                 resolvedType, flags, parentUserId);
7485
7486         if (resultTargetUser == null || resultTargetUser.isEmpty()) {
7487             return null;
7488         }
7489         CrossProfileDomainInfo result = null;
7490         int size = resultTargetUser.size();
7491         for (int i = 0; i < size; i++) {
7492             ResolveInfo riTargetUser = resultTargetUser.get(i);
7493             // Intent filter verification is only for filters that specify a host. So don't return
7494             // those that handle all web uris.
7495             if (riTargetUser.handleAllWebDataURI) {
7496                 continue;
7497             }
7498             String packageName = riTargetUser.activityInfo.packageName;
7499             PackageSetting ps = mSettings.mPackages.get(packageName);
7500             if (ps == null) {
7501                 continue;
7502             }
7503             long verificationState = getDomainVerificationStatusLPr(ps, parentUserId);
7504             int status = (int)(verificationState >> 32);
7505             if (result == null) {
7506                 result = new CrossProfileDomainInfo();
7507                 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(),
7508                         sourceUserId, parentUserId);
7509                 result.bestDomainVerificationStatus = status;
7510             } else {
7511                 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status,
7512                         result.bestDomainVerificationStatus);
7513             }
7514         }
7515         // Don't consider matches with status NEVER across profiles.
7516         if (result != null && result.bestDomainVerificationStatus
7517                 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7518             return null;
7519         }
7520         return result;
7521     }
7522
7523     /**
7524      * Verification statuses are ordered from the worse to the best, except for
7525      * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse.
7526      */
7527     private int bestDomainVerificationStatus(int status1, int status2) {
7528         if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7529             return status2;
7530         }
7531         if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7532             return status1;
7533         }
7534         return (int) MathUtils.max(status1, status2);
7535     }
7536
7537     private boolean isUserEnabled(int userId) {
7538         long callingId = Binder.clearCallingIdentity();
7539         try {
7540             UserInfo userInfo = sUserManager.getUserInfo(userId);
7541             return userInfo != null && userInfo.isEnabled();
7542         } finally {
7543             Binder.restoreCallingIdentity(callingId);
7544         }
7545     }
7546
7547     /**
7548      * Filter out activities with systemUserOnly flag set, when current user is not System.
7549      *
7550      * @return filtered list
7551      */
7552     private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) {
7553         if (userId == UserHandle.USER_SYSTEM) {
7554             return resolveInfos;
7555         }
7556         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7557             ResolveInfo info = resolveInfos.get(i);
7558             if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) {
7559                 resolveInfos.remove(i);
7560             }
7561         }
7562         return resolveInfos;
7563     }
7564
7565     /**
7566      * Filters out ephemeral activities.
7567      * <p>When resolving for an ephemeral app, only activities that 1) are defined in the
7568      * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned.
7569      *
7570      * @param resolveInfos The pre-filtered list of resolved activities
7571      * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering
7572      *          is performed.
7573      * @param intent
7574      * @return A filtered list of resolved activities.
7575      */
7576     private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos,
7577             String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid,
7578             boolean resolveForStart, int userId, Intent intent) {
7579         final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled(userId);
7580         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
7581             final ResolveInfo info = resolveInfos.get(i);
7582             // remove locally resolved instant app web results when disabled
7583             if (info.isInstantAppAvailable && blockInstant) {
7584                 resolveInfos.remove(i);
7585                 continue;
7586             }
7587             // allow activities that are defined in the provided package
7588             if (allowDynamicSplits
7589                     && info.activityInfo != null
7590                     && info.activityInfo.splitName != null
7591                     && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames,
7592                             info.activityInfo.splitName)) {
7593                 if (mInstantAppInstallerActivity == null) {
7594                     if (DEBUG_INSTALL) {
7595                         Slog.v(TAG, "No installer - not adding it to the ResolveInfo list");
7596                     }
7597                     resolveInfos.remove(i);
7598                     continue;
7599                 }
7600                 if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) {
7601                     resolveInfos.remove(i);
7602                     continue;
7603                 }
7604                 // requested activity is defined in a split that hasn't been installed yet.
7605                 // add the installer to the resolve list
7606                 if (DEBUG_INSTALL) {
7607                     Slog.v(TAG, "Adding installer to the ResolveInfo list");
7608                 }
7609                 final ResolveInfo installerInfo = new ResolveInfo(
7610                         mInstantAppInstallerInfo);
7611                 final ComponentName installFailureActivity = findInstallFailureActivity(
7612                         info.activityInfo.packageName,  filterCallingUid, userId);
7613                 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
7614                         installFailureActivity,
7615                         info.activityInfo.packageName,
7616                         info.activityInfo.applicationInfo.longVersionCode,
7617                         info.activityInfo.splitName);
7618                 // add a non-generic filter
7619                 installerInfo.filter = new IntentFilter();
7620
7621                 // This resolve info may appear in the chooser UI, so let us make it
7622                 // look as the one it replaces as far as the user is concerned which
7623                 // requires loading the correct label and icon for the resolve info.
7624                 installerInfo.resolvePackageName = info.getComponentInfo().packageName;
7625                 installerInfo.labelRes = info.resolveLabelResId();
7626                 installerInfo.icon = info.resolveIconResId();
7627                 installerInfo.isInstantAppAvailable = true;
7628                 resolveInfos.set(i, installerInfo);
7629                 continue;
7630             }
7631             // caller is a full app, don't need to apply any other filtering
7632             if (ephemeralPkgName == null) {
7633                 continue;
7634             } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) {
7635                 // caller is same app; don't need to apply any other filtering
7636                 continue;
7637             } else if (resolveForStart
7638                     && (intent.isWebIntent()
7639                             || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) != 0)
7640                     && intent.getPackage() == null
7641                     && intent.getComponent() == null) {
7642                 // ephemeral apps can launch other ephemeral apps indirectly
7643                 continue;
7644             }
7645             // allow activities that have been explicitly exposed to ephemeral apps
7646             final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp();
7647             if (!isEphemeralApp
7648                     && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
7649                 continue;
7650             }
7651             resolveInfos.remove(i);
7652         }
7653         return resolveInfos;
7654     }
7655
7656     /**
7657      * Returns the activity component that can handle install failures.
7658      * <p>By default, the instant application installer handles failures. However, an
7659      * application may want to handle failures on its own. Applications do this by
7660      * creating an activity with an intent filter that handles the action
7661      * {@link Intent#ACTION_INSTALL_FAILURE}.
7662      */
7663     private @Nullable ComponentName findInstallFailureActivity(
7664             String packageName, int filterCallingUid, int userId) {
7665         final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE);
7666         failureActivityIntent.setPackage(packageName);
7667         // IMPORTANT: disallow dynamic splits to avoid an infinite loop
7668         final List<ResolveInfo> result = queryIntentActivitiesInternal(
7669                 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId,
7670                 false /*resolveForStart*/, false /*allowDynamicSplits*/);
7671         final int NR = result.size();
7672         if (NR > 0) {
7673             for (int i = 0; i < NR; i++) {
7674                 final ResolveInfo info = result.get(i);
7675                 if (info.activityInfo.splitName != null) {
7676                     continue;
7677                 }
7678                 return new ComponentName(packageName, info.activityInfo.name);
7679             }
7680         }
7681         return null;
7682     }
7683
7684     /**
7685      * @param resolveInfos list of resolve infos in descending priority order
7686      * @return if the list contains a resolve info with non-negative priority
7687      */
7688     private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) {
7689         return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0;
7690     }
7691
7692     private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent,
7693             int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo,
7694             int userId) {
7695         final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0;
7696
7697         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7698             Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " +
7699                     candidates.size());
7700         }
7701
7702         final ArrayList<ResolveInfo> result = new ArrayList<>();
7703         final ArrayList<ResolveInfo> alwaysList = new ArrayList<>();
7704         final ArrayList<ResolveInfo> undefinedList = new ArrayList<>();
7705         final ArrayList<ResolveInfo> alwaysAskList = new ArrayList<>();
7706         final ArrayList<ResolveInfo> neverList = new ArrayList<>();
7707         final ArrayList<ResolveInfo> matchAllList = new ArrayList<>();
7708
7709         synchronized (mPackages) {
7710             final int count = candidates.size();
7711             // First, try to use linked apps. Partition the candidates into four lists:
7712             // one for the final results, one for the "do not use ever", one for "undefined status"
7713             // and finally one for "browser app type".
7714             for (int n=0; n<count; n++) {
7715                 ResolveInfo info = candidates.get(n);
7716                 String packageName = info.activityInfo.packageName;
7717                 PackageSetting ps = mSettings.mPackages.get(packageName);
7718                 if (ps != null) {
7719                     // Add to the special match all list (Browser use case)
7720                     if (info.handleAllWebDataURI) {
7721                         matchAllList.add(info);
7722                         continue;
7723                     }
7724                     // Try to get the status from User settings first
7725                     long packedStatus = getDomainVerificationStatusLPr(ps, userId);
7726                     int status = (int)(packedStatus >> 32);
7727                     int linkGeneration = (int)(packedStatus & 0xFFFFFFFF);
7728                     if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
7729                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
7730                             Slog.i(TAG, "  + always: " + info.activityInfo.packageName
7731                                     + " : linkgen=" + linkGeneration);
7732                         }
7733                         // Use link-enabled generation as preferredOrder, i.e.
7734                         // prefer newly-enabled over earlier-enabled.
7735                         info.preferredOrder = linkGeneration;
7736                         alwaysList.add(info);
7737                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
7738                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
7739                             Slog.i(TAG, "  + never: " + info.activityInfo.packageName);
7740                         }
7741                         neverList.add(info);
7742                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) {
7743                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
7744                             Slog.i(TAG, "  + always-ask: " + info.activityInfo.packageName);
7745                         }
7746                         alwaysAskList.add(info);
7747                     } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED ||
7748                             status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) {
7749                         if (DEBUG_DOMAIN_VERIFICATION || debug) {
7750                             Slog.i(TAG, "  + ask: " + info.activityInfo.packageName);
7751                         }
7752                         undefinedList.add(info);
7753                     }
7754                 }
7755             }
7756
7757             // We'll want to include browser possibilities in a few cases
7758             boolean includeBrowser = false;
7759
7760             // First try to add the "always" resolution(s) for the current user, if any
7761             if (alwaysList.size() > 0) {
7762                 result.addAll(alwaysList);
7763             } else {
7764                 // Add all undefined apps as we want them to appear in the disambiguation dialog.
7765                 result.addAll(undefinedList);
7766                 // Maybe add one for the other profile.
7767                 if (xpDomainInfo != null && (
7768                         xpDomainInfo.bestDomainVerificationStatus
7769                         != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) {
7770                     result.add(xpDomainInfo.resolveInfo);
7771                 }
7772                 includeBrowser = true;
7773             }
7774
7775             // The presence of any 'always ask' alternatives means we'll also offer browsers.
7776             // If there were 'always' entries their preferred order has been set, so we also
7777             // back that off to make the alternatives equivalent
7778             if (alwaysAskList.size() > 0) {
7779                 for (ResolveInfo i : result) {
7780                     i.preferredOrder = 0;
7781                 }
7782                 result.addAll(alwaysAskList);
7783                 includeBrowser = true;
7784             }
7785
7786             if (includeBrowser) {
7787                 // Also add browsers (all of them or only the default one)
7788                 if (DEBUG_DOMAIN_VERIFICATION) {
7789                     Slog.v(TAG, "   ...including browsers in candidate set");
7790                 }
7791                 if ((matchFlags & MATCH_ALL) != 0) {
7792                     result.addAll(matchAllList);
7793                 } else {
7794                     // Browser/generic handling case.  If there's a default browser, go straight
7795                     // to that (but only if there is no other higher-priority match).
7796                     final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
7797                     int maxMatchPrio = 0;
7798                     ResolveInfo defaultBrowserMatch = null;
7799                     final int numCandidates = matchAllList.size();
7800                     for (int n = 0; n < numCandidates; n++) {
7801                         ResolveInfo info = matchAllList.get(n);
7802                         // track the highest overall match priority...
7803                         if (info.priority > maxMatchPrio) {
7804                             maxMatchPrio = info.priority;
7805                         }
7806                         // ...and the highest-priority default browser match
7807                         if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) {
7808                             if (defaultBrowserMatch == null
7809                                     || (defaultBrowserMatch.priority < info.priority)) {
7810                                 if (debug) {
7811                                     Slog.v(TAG, "Considering default browser match " + info);
7812                                 }
7813                                 defaultBrowserMatch = info;
7814                             }
7815                         }
7816                     }
7817                     if (defaultBrowserMatch != null
7818                             && defaultBrowserMatch.priority >= maxMatchPrio
7819                             && !TextUtils.isEmpty(defaultBrowserPackageName))
7820                     {
7821                         if (debug) {
7822                             Slog.v(TAG, "Default browser match " + defaultBrowserMatch);
7823                         }
7824                         result.add(defaultBrowserMatch);
7825                     } else {
7826                         result.addAll(matchAllList);
7827                     }
7828                 }
7829
7830                 // If there is nothing selected, add all candidates and remove the ones that the user
7831                 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state
7832                 if (result.size() == 0) {
7833                     result.addAll(candidates);
7834                     result.removeAll(neverList);
7835                 }
7836             }
7837         }
7838         if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) {
7839             Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " +
7840                     result.size());
7841             for (ResolveInfo info : result) {
7842                 Slog.v(TAG, "  + " + info.activityInfo);
7843             }
7844         }
7845         return result;
7846     }
7847
7848     // Returns a packed value as a long:
7849     //
7850     // high 'int'-sized word: link status: undefined/ask/never/always.
7851     // low 'int'-sized word: relative priority among 'always' results.
7852     private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
7853         long result = ps.getDomainVerificationStatusForUser(userId);
7854         // if none available, get the master status
7855         if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
7856             if (ps.getIntentFilterVerificationInfo() != null) {
7857                 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32;
7858             }
7859         }
7860         return result;
7861     }
7862
7863     private ResolveInfo querySkipCurrentProfileIntents(
7864             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7865             int flags, int sourceUserId) {
7866         if (matchingFilters != null) {
7867             int size = matchingFilters.size();
7868             for (int i = 0; i < size; i ++) {
7869                 CrossProfileIntentFilter filter = matchingFilters.get(i);
7870                 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
7871                     // Checking if there are activities in the target user that can handle the
7872                     // intent.
7873                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7874                             resolvedType, flags, sourceUserId);
7875                     if (resolveInfo != null) {
7876                         return resolveInfo;
7877                     }
7878                 }
7879             }
7880         }
7881         return null;
7882     }
7883
7884     // Return matching ResolveInfo in target user if any.
7885     private ResolveInfo queryCrossProfileIntents(
7886             List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
7887             int flags, int sourceUserId, boolean matchInCurrentProfile) {
7888         if (matchingFilters != null) {
7889             // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
7890             // match the same intent. For performance reasons, it is better not to
7891             // run queryIntent twice for the same userId
7892             SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
7893             int size = matchingFilters.size();
7894             for (int i = 0; i < size; i++) {
7895                 CrossProfileIntentFilter filter = matchingFilters.get(i);
7896                 int targetUserId = filter.getTargetUserId();
7897                 boolean skipCurrentProfile =
7898                         (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0;
7899                 boolean skipCurrentProfileIfNoMatchFound =
7900                         (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0;
7901                 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId)
7902                         && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) {
7903                     // Checking if there are activities in the target user that can handle the
7904                     // intent.
7905                     ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent,
7906                             resolvedType, flags, sourceUserId);
7907                     if (resolveInfo != null) return resolveInfo;
7908                     alreadyTriedUserIds.put(targetUserId, true);
7909                 }
7910             }
7911         }
7912         return null;
7913     }
7914
7915     /**
7916      * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that
7917      * will forward the intent to the filter's target user.
7918      * Otherwise, returns null.
7919      */
7920     private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent,
7921             String resolvedType, int flags, int sourceUserId) {
7922         int targetUserId = filter.getTargetUserId();
7923         List<ResolveInfo> resultTargetUser = mComponentResolver.queryActivities(intent,
7924                 resolvedType, flags, targetUserId);
7925         if (resultTargetUser != null && isUserEnabled(targetUserId)) {
7926             // If all the matches in the target profile are suspended, return null.
7927             for (int i = resultTargetUser.size() - 1; i >= 0; i--) {
7928                 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags
7929                         & ApplicationInfo.FLAG_SUSPENDED) == 0) {
7930                     return createForwardingResolveInfoUnchecked(filter, sourceUserId,
7931                             targetUserId);
7932                 }
7933             }
7934         }
7935         return null;
7936     }
7937
7938     private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter,
7939             int sourceUserId, int targetUserId) {
7940         ResolveInfo forwardingResolveInfo = new ResolveInfo();
7941         long ident = Binder.clearCallingIdentity();
7942         boolean targetIsProfile;
7943         try {
7944             targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile();
7945         } finally {
7946             Binder.restoreCallingIdentity(ident);
7947         }
7948         String className;
7949         if (targetIsProfile) {
7950             className = FORWARD_INTENT_TO_MANAGED_PROFILE;
7951         } else {
7952             className = FORWARD_INTENT_TO_PARENT;
7953         }
7954         ComponentName forwardingActivityComponentName = new ComponentName(
7955                 mAndroidApplication.packageName, className);
7956         ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
7957                 sourceUserId);
7958         if (!targetIsProfile) {
7959             forwardingActivityInfo.showUserIcon = targetUserId;
7960             forwardingResolveInfo.noResourceId = true;
7961         }
7962         forwardingResolveInfo.activityInfo = forwardingActivityInfo;
7963         forwardingResolveInfo.priority = 0;
7964         forwardingResolveInfo.preferredOrder = 0;
7965         forwardingResolveInfo.match = 0;
7966         forwardingResolveInfo.isDefault = true;
7967         forwardingResolveInfo.filter = filter;
7968         forwardingResolveInfo.targetUserId = targetUserId;
7969         return forwardingResolveInfo;
7970     }
7971
7972     @Override
7973     public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
7974             Intent[] specifics, String[] specificTypes, Intent intent,
7975             String resolvedType, int flags, int userId) {
7976         return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics,
7977                 specificTypes, intent, resolvedType, flags, userId));
7978     }
7979
7980     private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller,
7981             Intent[] specifics, String[] specificTypes, Intent intent,
7982             String resolvedType, int flags, int userId) {
7983         if (!sUserManager.exists(userId)) return Collections.emptyList();
7984         final int callingUid = Binder.getCallingUid();
7985         flags = updateFlagsForResolve(flags, userId, intent, callingUid,
7986                 false /*includeInstantApps*/);
7987         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
7988                 false /*requireFullPermission*/, false /*checkShell*/,
7989                 "query intent activity options");
7990         final String resultsAction = intent.getAction();
7991
7992         final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags
7993                 | PackageManager.GET_RESOLVED_FILTER, userId);
7994
7995         if (DEBUG_INTENT_MATCHING) {
7996             Log.v(TAG, "Query " + intent + ": " + results);
7997         }
7998
7999         int specificsPos = 0;
8000         int N;
8001
8002         // todo: note that the algorithm used here is O(N^2).  This
8003         // isn't a problem in our current environment, but if we start running
8004         // into situations where we have more than 5 or 10 matches then this
8005         // should probably be changed to something smarter...
8006
8007         // First we go through and resolve each of the specific items
8008         // that were supplied, taking care of removing any corresponding
8009         // duplicate items in the generic resolve list.
8010         if (specifics != null) {
8011             for (int i=0; i<specifics.length; i++) {
8012                 final Intent sintent = specifics[i];
8013                 if (sintent == null) {
8014                     continue;
8015                 }
8016
8017                 if (DEBUG_INTENT_MATCHING) {
8018                     Log.v(TAG, "Specific #" + i + ": " + sintent);
8019                 }
8020
8021                 String action = sintent.getAction();
8022                 if (resultsAction != null && resultsAction.equals(action)) {
8023                     // If this action was explicitly requested, then don't
8024                     // remove things that have it.
8025                     action = null;
8026                 }
8027
8028                 ResolveInfo ri = null;
8029                 ActivityInfo ai = null;
8030
8031                 ComponentName comp = sintent.getComponent();
8032                 if (comp == null) {
8033                     ri = resolveIntent(
8034                         sintent,
8035                         specificTypes != null ? specificTypes[i] : null,
8036                             flags, userId);
8037                     if (ri == null) {
8038                         continue;
8039                     }
8040                     if (ri == mResolveInfo) {
8041                         // ACK!  Must do something better with this.
8042                     }
8043                     ai = ri.activityInfo;
8044                     comp = new ComponentName(ai.applicationInfo.packageName,
8045                             ai.name);
8046                 } else {
8047                     ai = getActivityInfo(comp, flags, userId);
8048                     if (ai == null) {
8049                         continue;
8050                     }
8051                 }
8052
8053                 // Look for any generic query activities that are duplicates
8054                 // of this specific one, and remove them from the results.
8055                 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
8056                 N = results.size();
8057                 int j;
8058                 for (j=specificsPos; j<N; j++) {
8059                     ResolveInfo sri = results.get(j);
8060                     if ((sri.activityInfo.name.equals(comp.getClassName())
8061                             && sri.activityInfo.applicationInfo.packageName.equals(
8062                                     comp.getPackageName()))
8063                         || (action != null && sri.filter.matchAction(action))) {
8064                         results.remove(j);
8065                         if (DEBUG_INTENT_MATCHING) Log.v(
8066                             TAG, "Removing duplicate item from " + j
8067                             + " due to specific " + specificsPos);
8068                         if (ri == null) {
8069                             ri = sri;
8070                         }
8071                         j--;
8072                         N--;
8073                     }
8074                 }
8075
8076                 // Add this specific item to its proper place.
8077                 if (ri == null) {
8078                     ri = new ResolveInfo();
8079                     ri.activityInfo = ai;
8080                 }
8081                 results.add(specificsPos, ri);
8082                 ri.specificIndex = i;
8083                 specificsPos++;
8084             }
8085         }
8086
8087         // Now we go through the remaining generic results and remove any
8088         // duplicate actions that are found here.
8089         N = results.size();
8090         for (int i=specificsPos; i<N-1; i++) {
8091             final ResolveInfo rii = results.get(i);
8092             if (rii.filter == null) {
8093                 continue;
8094             }
8095
8096             // Iterate over all of the actions of this result's intent
8097             // filter...  typically this should be just one.
8098             final Iterator<String> it = rii.filter.actionsIterator();
8099             if (it == null) {
8100                 continue;
8101             }
8102             while (it.hasNext()) {
8103                 final String action = it.next();
8104                 if (resultsAction != null && resultsAction.equals(action)) {
8105                     // If this action was explicitly requested, then don't
8106                     // remove things that have it.
8107                     continue;
8108                 }
8109                 for (int j=i+1; j<N; j++) {
8110                     final ResolveInfo rij = results.get(j);
8111                     if (rij.filter != null && rij.filter.hasAction(action)) {
8112                         results.remove(j);
8113                         if (DEBUG_INTENT_MATCHING) Log.v(
8114                             TAG, "Removing duplicate item from " + j
8115                             + " due to action " + action + " at " + i);
8116                         j--;
8117                         N--;
8118                     }
8119                 }
8120             }
8121
8122             // If the caller didn't request filter information, drop it now
8123             // so we don't have to marshall/unmarshall it.
8124             if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8125                 rii.filter = null;
8126             }
8127         }
8128
8129         // Filter out the caller activity if so requested.
8130         if (caller != null) {
8131             N = results.size();
8132             for (int i=0; i<N; i++) {
8133                 ActivityInfo ainfo = results.get(i).activityInfo;
8134                 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
8135                         && caller.getClassName().equals(ainfo.name)) {
8136                     results.remove(i);
8137                     break;
8138                 }
8139             }
8140         }
8141
8142         // If the caller didn't request filter information,
8143         // drop them now so we don't have to
8144         // marshall/unmarshall it.
8145         if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
8146             N = results.size();
8147             for (int i=0; i<N; i++) {
8148                 results.get(i).filter = null;
8149             }
8150         }
8151
8152         if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
8153         return results;
8154     }
8155
8156     @Override
8157     public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent,
8158             String resolvedType, int flags, int userId) {
8159         return new ParceledListSlice<>(
8160                 queryIntentReceiversInternal(intent, resolvedType, flags, userId,
8161                         false /*allowDynamicSplits*/));
8162     }
8163
8164     private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent,
8165             String resolvedType, int flags, int userId, boolean allowDynamicSplits) {
8166         if (!sUserManager.exists(userId)) return Collections.emptyList();
8167         final int callingUid = Binder.getCallingUid();
8168         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
8169                 false /*requireFullPermission*/, false /*checkShell*/,
8170                 "query intent receivers");
8171         final String instantAppPkgName = getInstantAppPackageName(callingUid);
8172         flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8173                 false /*includeInstantApps*/);
8174         ComponentName comp = intent.getComponent();
8175         if (comp == null) {
8176             if (intent.getSelector() != null) {
8177                 intent = intent.getSelector();
8178                 comp = intent.getComponent();
8179             }
8180         }
8181         if (comp != null) {
8182             final List<ResolveInfo> list = new ArrayList<>(1);
8183             final ActivityInfo ai = getReceiverInfo(comp, flags, userId);
8184             if (ai != null) {
8185                 // When specifying an explicit component, we prevent the activity from being
8186                 // used when either 1) the calling package is normal and the activity is within
8187                 // an instant application or 2) the calling package is ephemeral and the
8188                 // activity is not visible to instant applications.
8189                 final boolean matchInstantApp =
8190                         (flags & PackageManager.MATCH_INSTANT) != 0;
8191                 final boolean matchVisibleToInstantAppOnly =
8192                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8193                 final boolean matchExplicitlyVisibleOnly =
8194                         (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0;
8195                 final boolean isCallerInstantApp =
8196                         instantAppPkgName != null;
8197                 final boolean isTargetSameInstantApp =
8198                         comp.getPackageName().equals(instantAppPkgName);
8199                 final boolean isTargetInstantApp =
8200                         (ai.applicationInfo.privateFlags
8201                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8202                 final boolean isTargetVisibleToInstantApp =
8203                         (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0;
8204                 final boolean isTargetExplicitlyVisibleToInstantApp =
8205                         isTargetVisibleToInstantApp
8206                         && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0;
8207                 final boolean isTargetHiddenFromInstantApp =
8208                         !isTargetVisibleToInstantApp
8209                         || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp);
8210                 final boolean blockResolution =
8211                         !isTargetSameInstantApp
8212                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8213                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
8214                                         && isTargetHiddenFromInstantApp));
8215                 if (!blockResolution) {
8216                     ResolveInfo ri = new ResolveInfo();
8217                     ri.activityInfo = ai;
8218                     list.add(ri);
8219                 }
8220             }
8221             return applyPostResolutionFilter(
8222                     list, instantAppPkgName, allowDynamicSplits, callingUid, false, userId,
8223                     intent);
8224         }
8225
8226         // reader
8227         synchronized (mPackages) {
8228             String pkgName = intent.getPackage();
8229             if (pkgName == null) {
8230                 final List<ResolveInfo> result =
8231                         mComponentResolver.queryReceivers(intent, resolvedType, flags, userId);
8232                 return applyPostResolutionFilter(
8233                         result, instantAppPkgName, allowDynamicSplits, callingUid, false, userId,
8234                         intent);
8235             }
8236             final PackageParser.Package pkg = mPackages.get(pkgName);
8237             if (pkg != null) {
8238                 final List<ResolveInfo> result = mComponentResolver.queryReceivers(
8239                         intent, resolvedType, flags, pkg.receivers, userId);
8240                 return applyPostResolutionFilter(
8241                         result, instantAppPkgName, allowDynamicSplits, callingUid, false, userId,
8242                         intent);
8243             }
8244             return Collections.emptyList();
8245         }
8246     }
8247
8248     @Override
8249     public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
8250         final int callingUid = Binder.getCallingUid();
8251         return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
8252     }
8253
8254     private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags,
8255             int userId, int callingUid) {
8256         if (!sUserManager.exists(userId)) return null;
8257         flags = updateFlagsForResolve(
8258                 flags, userId, intent, callingUid, false /*includeInstantApps*/);
8259         List<ResolveInfo> query = queryIntentServicesInternal(
8260                 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/);
8261         if (query != null) {
8262             if (query.size() >= 1) {
8263                 // If there is more than one service with the same priority,
8264                 // just arbitrarily pick the first one.
8265                 return query.get(0);
8266             }
8267         }
8268         return null;
8269     }
8270
8271     @Override
8272     public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent,
8273             String resolvedType, int flags, int userId) {
8274         final int callingUid = Binder.getCallingUid();
8275         return new ParceledListSlice<>(queryIntentServicesInternal(
8276                 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/));
8277     }
8278
8279     private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent,
8280             String resolvedType, int flags, int userId, int callingUid,
8281             boolean includeInstantApps) {
8282         if (!sUserManager.exists(userId)) return Collections.emptyList();
8283         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
8284                 false /*requireFullPermission*/, false /*checkShell*/,
8285                 "query intent receivers");
8286         final String instantAppPkgName = getInstantAppPackageName(callingUid);
8287         flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps);
8288         ComponentName comp = intent.getComponent();
8289         if (comp == null) {
8290             if (intent.getSelector() != null) {
8291                 intent = intent.getSelector();
8292                 comp = intent.getComponent();
8293             }
8294         }
8295         if (comp != null) {
8296             final List<ResolveInfo> list = new ArrayList<>(1);
8297             final ServiceInfo si = getServiceInfo(comp, flags, userId);
8298             if (si != null) {
8299                 // When specifying an explicit component, we prevent the service from being
8300                 // used when either 1) the service is in an instant application and the
8301                 // caller is not the same instant application or 2) the calling package is
8302                 // ephemeral and the activity is not visible to ephemeral applications.
8303                 final boolean matchInstantApp =
8304                         (flags & PackageManager.MATCH_INSTANT) != 0;
8305                 final boolean matchVisibleToInstantAppOnly =
8306                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8307                 final boolean isCallerInstantApp =
8308                         instantAppPkgName != null;
8309                 final boolean isTargetSameInstantApp =
8310                         comp.getPackageName().equals(instantAppPkgName);
8311                 final boolean isTargetInstantApp =
8312                         (si.applicationInfo.privateFlags
8313                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8314                 final boolean isTargetHiddenFromInstantApp =
8315                         (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8316                 final boolean blockResolution =
8317                         !isTargetSameInstantApp
8318                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8319                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
8320                                         && isTargetHiddenFromInstantApp));
8321                 if (!blockResolution) {
8322                     final ResolveInfo ri = new ResolveInfo();
8323                     ri.serviceInfo = si;
8324                     list.add(ri);
8325                 }
8326             }
8327             return list;
8328         }
8329
8330         // reader
8331         synchronized (mPackages) {
8332             String pkgName = intent.getPackage();
8333             if (pkgName == null) {
8334                 return applyPostServiceResolutionFilter(
8335                         mComponentResolver.queryServices(intent, resolvedType, flags, userId),
8336                         instantAppPkgName);
8337             }
8338             final PackageParser.Package pkg = mPackages.get(pkgName);
8339             if (pkg != null) {
8340                 return applyPostServiceResolutionFilter(
8341                         mComponentResolver.queryServices(intent, resolvedType, flags, pkg.services,
8342                                 userId),
8343                         instantAppPkgName);
8344             }
8345             return Collections.emptyList();
8346         }
8347     }
8348
8349     private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos,
8350             String instantAppPkgName) {
8351         if (instantAppPkgName == null) {
8352             return resolveInfos;
8353         }
8354         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8355             final ResolveInfo info = resolveInfos.get(i);
8356             final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp();
8357             // allow services that are defined in the provided package
8358             if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) {
8359                 if (info.serviceInfo.splitName != null
8360                         && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames,
8361                                 info.serviceInfo.splitName)) {
8362                     // requested service is defined in a split that hasn't been installed yet.
8363                     // add the installer to the resolve list
8364                     if (DEBUG_INSTANT) {
8365                         Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8366                     }
8367                     final ResolveInfo installerInfo = new ResolveInfo(
8368                             mInstantAppInstallerInfo);
8369                     installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8370                             null /* installFailureActivity */,
8371                             info.serviceInfo.packageName,
8372                             info.serviceInfo.applicationInfo.longVersionCode,
8373                             info.serviceInfo.splitName);
8374                     // add a non-generic filter
8375                     installerInfo.filter = new IntentFilter();
8376                     // load resources from the correct package
8377                     installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8378                     resolveInfos.set(i, installerInfo);
8379                 }
8380                 continue;
8381             }
8382             // allow services that have been explicitly exposed to ephemeral apps
8383             if (!isEphemeralApp
8384                     && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8385                 continue;
8386             }
8387             resolveInfos.remove(i);
8388         }
8389         return resolveInfos;
8390     }
8391
8392     @Override
8393     public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent,
8394             String resolvedType, int flags, int userId) {
8395         return new ParceledListSlice<>(
8396                 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId));
8397     }
8398
8399     private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal(
8400             Intent intent, String resolvedType, int flags, int userId) {
8401         if (!sUserManager.exists(userId)) return Collections.emptyList();
8402         final int callingUid = Binder.getCallingUid();
8403         final String instantAppPkgName = getInstantAppPackageName(callingUid);
8404         flags = updateFlagsForResolve(flags, userId, intent, callingUid,
8405                 false /*includeInstantApps*/);
8406         ComponentName comp = intent.getComponent();
8407         if (comp == null) {
8408             if (intent.getSelector() != null) {
8409                 intent = intent.getSelector();
8410                 comp = intent.getComponent();
8411             }
8412         }
8413         if (comp != null) {
8414             final List<ResolveInfo> list = new ArrayList<>(1);
8415             final ProviderInfo pi = getProviderInfo(comp, flags, userId);
8416             if (pi != null) {
8417                 // When specifying an explicit component, we prevent the provider from being
8418                 // used when either 1) the provider is in an instant application and the
8419                 // caller is not the same instant application or 2) the calling package is an
8420                 // instant application and the provider is not visible to instant applications.
8421                 final boolean matchInstantApp =
8422                         (flags & PackageManager.MATCH_INSTANT) != 0;
8423                 final boolean matchVisibleToInstantAppOnly =
8424                         (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0;
8425                 final boolean isCallerInstantApp =
8426                         instantAppPkgName != null;
8427                 final boolean isTargetSameInstantApp =
8428                         comp.getPackageName().equals(instantAppPkgName);
8429                 final boolean isTargetInstantApp =
8430                         (pi.applicationInfo.privateFlags
8431                                 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0;
8432                 final boolean isTargetHiddenFromInstantApp =
8433                         (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0;
8434                 final boolean blockResolution =
8435                         !isTargetSameInstantApp
8436                         && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp)
8437                                 || (matchVisibleToInstantAppOnly && isCallerInstantApp
8438                                         && isTargetHiddenFromInstantApp));
8439                 if (!blockResolution) {
8440                     final ResolveInfo ri = new ResolveInfo();
8441                     ri.providerInfo = pi;
8442                     list.add(ri);
8443                 }
8444             }
8445             return list;
8446         }
8447
8448         // reader
8449         synchronized (mPackages) {
8450             String pkgName = intent.getPackage();
8451             if (pkgName == null) {
8452                 return applyPostContentProviderResolutionFilter(
8453                         mComponentResolver.queryProviders(intent, resolvedType, flags, userId),
8454                         instantAppPkgName);
8455             }
8456             final PackageParser.Package pkg = mPackages.get(pkgName);
8457             if (pkg != null) {
8458                 return applyPostContentProviderResolutionFilter(
8459                         mComponentResolver.queryProviders(intent, resolvedType, flags,
8460                                 pkg.providers, userId),
8461                         instantAppPkgName);
8462             }
8463             return Collections.emptyList();
8464         }
8465     }
8466
8467     private List<ResolveInfo> applyPostContentProviderResolutionFilter(
8468             List<ResolveInfo> resolveInfos, String instantAppPkgName) {
8469         if (instantAppPkgName == null) {
8470             return resolveInfos;
8471         }
8472         for (int i = resolveInfos.size() - 1; i >= 0; i--) {
8473             final ResolveInfo info = resolveInfos.get(i);
8474             final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp();
8475             // allow providers that are defined in the provided package
8476             if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) {
8477                 if (info.providerInfo.splitName != null
8478                         && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames,
8479                                 info.providerInfo.splitName)) {
8480                     // requested provider is defined in a split that hasn't been installed yet.
8481                     // add the installer to the resolve list
8482                     if (DEBUG_INSTANT) {
8483                         Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list");
8484                     }
8485                     final ResolveInfo installerInfo = new ResolveInfo(
8486                             mInstantAppInstallerInfo);
8487                     installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo(
8488                             null /*failureActivity*/,
8489                             info.providerInfo.packageName,
8490                             info.providerInfo.applicationInfo.longVersionCode,
8491                             info.providerInfo.splitName);
8492                     // add a non-generic filter
8493                     installerInfo.filter = new IntentFilter();
8494                     // load resources from the correct package
8495                     installerInfo.resolvePackageName = info.getComponentInfo().packageName;
8496                     resolveInfos.set(i, installerInfo);
8497                 }
8498                 continue;
8499             }
8500             // allow providers that have been explicitly exposed to instant applications
8501             if (!isEphemeralApp
8502                     && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) {
8503                 continue;
8504             }
8505             resolveInfos.remove(i);
8506         }
8507         return resolveInfos;
8508     }
8509
8510     @Override
8511     public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
8512         final int callingUid = Binder.getCallingUid();
8513         if (getInstantAppPackageName(callingUid) != null) {
8514             return ParceledListSlice.emptyList();
8515         }
8516         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8517         flags = updateFlagsForPackage(flags, userId, null);
8518         final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8519         final boolean listApex = (flags & MATCH_APEX) != 0;
8520         final boolean listFactory = (flags & MATCH_FACTORY_ONLY) != 0;
8521
8522         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
8523                 false /* requireFullPermission */, false /* checkShell */,
8524                 "get installed packages");
8525
8526         // writer
8527         synchronized (mPackages) {
8528             ArrayList<PackageInfo> list;
8529             if (listUninstalled) {
8530                 list = new ArrayList<>(mSettings.mPackages.size());
8531                 for (PackageSetting ps : mSettings.mPackages.values()) {
8532                     if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8533                         continue;
8534                     }
8535                     if (filterAppAccessLPr(ps, callingUid, userId)) {
8536                         continue;
8537                     }
8538                     final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8539                     if (pi != null) {
8540                         list.add(pi);
8541                     }
8542                 }
8543             } else {
8544                 list = new ArrayList<>(mPackages.size());
8545                 for (PackageParser.Package p : mPackages.values()) {
8546                     final PackageSetting ps = (PackageSetting) p.mExtras;
8547                     if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8548                         continue;
8549                     }
8550                     if (filterAppAccessLPr(ps, callingUid, userId)) {
8551                         continue;
8552                     }
8553                     final PackageInfo pi = generatePackageInfo((PackageSetting)
8554                             p.mExtras, flags, userId);
8555                     if (pi != null) {
8556                         list.add(pi);
8557                     }
8558                 }
8559             }
8560             if (listApex) {
8561                 if (listFactory) {
8562                     list.addAll(mApexManager.getFactoryPackages());
8563                 } else {
8564                     list.addAll(mApexManager.getActivePackages());
8565                 }
8566                 if (listUninstalled) {
8567                     list.addAll(mApexManager.getInactivePackages());
8568                 }
8569             }
8570             return new ParceledListSlice<>(list);
8571         }
8572     }
8573
8574     private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
8575             String[] permissions, boolean[] tmp, int flags, int userId) {
8576         int numMatch = 0;
8577         final PermissionsState permissionsState = ps.getPermissionsState();
8578         for (int i=0; i<permissions.length; i++) {
8579             final String permission = permissions[i];
8580             if (permissionsState.hasPermission(permission, userId)) {
8581                 tmp[i] = true;
8582                 numMatch++;
8583             } else {
8584                 tmp[i] = false;
8585             }
8586         }
8587         if (numMatch == 0) {
8588             return;
8589         }
8590         final PackageInfo pi = generatePackageInfo(ps, flags, userId);
8591
8592         // The above might return null in cases of uninstalled apps or install-state
8593         // skew across users/profiles.
8594         if (pi != null) {
8595             if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
8596                 if (numMatch == permissions.length) {
8597                     pi.requestedPermissions = permissions;
8598                 } else {
8599                     pi.requestedPermissions = new String[numMatch];
8600                     numMatch = 0;
8601                     for (int i=0; i<permissions.length; i++) {
8602                         if (tmp[i]) {
8603                             pi.requestedPermissions[numMatch] = permissions[i];
8604                             numMatch++;
8605                         }
8606                     }
8607                 }
8608             }
8609             list.add(pi);
8610         }
8611     }
8612
8613     @Override
8614     public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
8615             String[] permissions, int flags, int userId) {
8616         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8617         flags = updateFlagsForPackage(flags, userId, permissions);
8618         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8619                 true /* requireFullPermission */, false /* checkShell */,
8620                 "get packages holding permissions");
8621         final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8622
8623         // writer
8624         synchronized (mPackages) {
8625             ArrayList<PackageInfo> list = new ArrayList<>();
8626             boolean[] tmpBools = new boolean[permissions.length];
8627             if (listUninstalled) {
8628                 for (PackageSetting ps : mSettings.mPackages.values()) {
8629                     addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8630                             userId);
8631                 }
8632             } else {
8633                 for (PackageParser.Package pkg : mPackages.values()) {
8634                     PackageSetting ps = (PackageSetting)pkg.mExtras;
8635                     if (ps != null) {
8636                         addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
8637                                 userId);
8638                     }
8639                 }
8640             }
8641
8642             return new ParceledListSlice<>(list);
8643         }
8644     }
8645
8646     @Override
8647     public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
8648         final int callingUid = Binder.getCallingUid();
8649         return new ParceledListSlice<>(
8650                 getInstalledApplicationsListInternal(flags, userId, callingUid));
8651     }
8652
8653     private List<ApplicationInfo> getInstalledApplicationsListInternal(int flags, int userId,
8654             int callingUid) {
8655         if (getInstantAppPackageName(callingUid) != null) {
8656             return Collections.emptyList();
8657         }
8658         if (!sUserManager.exists(userId)) return Collections.emptyList();
8659         flags = updateFlagsForApplication(flags, userId, null);
8660         final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0;
8661
8662         mPermissionManager.enforceCrossUserPermission(
8663             callingUid,
8664             userId,
8665             false /* requireFullPermission */,
8666             false /* checkShell */,
8667             "get installed application info");
8668
8669         // writer
8670         synchronized (mPackages) {
8671             ArrayList<ApplicationInfo> list;
8672             if (listUninstalled) {
8673                 list = new ArrayList<>(mSettings.mPackages.size());
8674                 for (PackageSetting ps : mSettings.mPackages.values()) {
8675                     ApplicationInfo ai;
8676                     int effectiveFlags = flags;
8677                     if (ps.isSystem()) {
8678                         effectiveFlags |= PackageManager.MATCH_ANY_USER;
8679                     }
8680                     if (ps.pkg != null) {
8681                         if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) {
8682                             continue;
8683                         }
8684                         if (filterAppAccessLPr(ps, callingUid, userId)) {
8685                             continue;
8686                         }
8687                         ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags,
8688                                 ps.readUserState(userId), userId);
8689                         if (ai != null) {
8690                             ai.packageName = resolveExternalPackageNameLPr(ps.pkg);
8691                         }
8692                     } else {
8693                         // Shared lib filtering done in generateApplicationInfoFromSettingsLPw
8694                         // and already converts to externally visible package name
8695                         ai = generateApplicationInfoFromSettingsLPw(ps.name,
8696                                 callingUid, effectiveFlags, userId);
8697                     }
8698                     if (ai != null) {
8699                         list.add(ai);
8700                     }
8701                 }
8702             } else {
8703                 list = new ArrayList<>(mPackages.size());
8704                 for (PackageParser.Package p : mPackages.values()) {
8705                     if (p.mExtras != null) {
8706                         PackageSetting ps = (PackageSetting) p.mExtras;
8707                         if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) {
8708                             continue;
8709                         }
8710                         if (filterAppAccessLPr(ps, callingUid, userId)) {
8711                             continue;
8712                         }
8713                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8714                                 ps.readUserState(userId), userId);
8715                         if (ai != null) {
8716                             ai.packageName = resolveExternalPackageNameLPr(p);
8717                             list.add(ai);
8718                         }
8719                     }
8720                 }
8721             }
8722
8723             return list;
8724         }
8725     }
8726
8727     @Override
8728     public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) {
8729         if (HIDE_EPHEMERAL_APIS) {
8730             return null;
8731         }
8732         if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8733             mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8734                     "getEphemeralApplications");
8735         }
8736         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8737                 true /* requireFullPermission */, false /* checkShell */,
8738                 "getEphemeralApplications");
8739         synchronized (mPackages) {
8740             List<InstantAppInfo> instantApps = mInstantAppRegistry
8741                     .getInstantAppsLPr(userId);
8742             if (instantApps != null) {
8743                 return new ParceledListSlice<>(instantApps);
8744             }
8745         }
8746         return null;
8747     }
8748
8749     @Override
8750     public boolean isInstantApp(String packageName, int userId) {
8751         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8752                 true /* requireFullPermission */, false /* checkShell */,
8753                 "isInstantApp");
8754         if (HIDE_EPHEMERAL_APIS) {
8755             return false;
8756         }
8757
8758         synchronized (mPackages) {
8759             int callingUid = Binder.getCallingUid();
8760             if (Process.isIsolated(callingUid)) {
8761                 callingUid = mIsolatedOwners.get(callingUid);
8762             }
8763             final PackageSetting ps = mSettings.mPackages.get(packageName);
8764             PackageParser.Package pkg = mPackages.get(packageName);
8765             final boolean returnAllowed =
8766                     ps != null
8767                     && (isCallerSameApp(packageName, callingUid)
8768                             || canViewInstantApps(callingUid, userId)
8769                             || mInstantAppRegistry.isInstantAccessGranted(
8770                                     userId, UserHandle.getAppId(callingUid), ps.appId));
8771             if (returnAllowed) {
8772                 return ps.getInstantApp(userId);
8773             }
8774         }
8775         return false;
8776     }
8777
8778     @Override
8779     public byte[] getInstantAppCookie(String packageName, int userId) {
8780         if (HIDE_EPHEMERAL_APIS) {
8781             return null;
8782         }
8783
8784         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8785                 true /* requireFullPermission */, false /* checkShell */,
8786                 "getInstantAppCookie");
8787         if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8788             return null;
8789         }
8790         synchronized (mPackages) {
8791             return mInstantAppRegistry.getInstantAppCookieLPw(
8792                     packageName, userId);
8793         }
8794     }
8795
8796     @Override
8797     public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) {
8798         if (HIDE_EPHEMERAL_APIS) {
8799             return true;
8800         }
8801
8802         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8803                 true /* requireFullPermission */, true /* checkShell */,
8804                 "setInstantAppCookie");
8805         if (!isCallerSameApp(packageName, Binder.getCallingUid())) {
8806             return false;
8807         }
8808         synchronized (mPackages) {
8809             return mInstantAppRegistry.setInstantAppCookieLPw(
8810                     packageName, cookie, userId);
8811         }
8812     }
8813
8814     @Override
8815     public Bitmap getInstantAppIcon(String packageName, int userId) {
8816         if (HIDE_EPHEMERAL_APIS) {
8817             return null;
8818         }
8819
8820         if (!canViewInstantApps(Binder.getCallingUid(), userId)) {
8821             mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS,
8822                     "getInstantAppIcon");
8823         }
8824         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
8825                 true /* requireFullPermission */, false /* checkShell */,
8826                 "getInstantAppIcon");
8827
8828         synchronized (mPackages) {
8829             return mInstantAppRegistry.getInstantAppIconLPw(
8830                     packageName, userId);
8831         }
8832     }
8833
8834     private boolean isCallerSameApp(String packageName, int uid) {
8835         PackageParser.Package pkg = mPackages.get(packageName);
8836         return pkg != null
8837                 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid;
8838     }
8839
8840     @Override
8841     public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) {
8842         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8843             return ParceledListSlice.emptyList();
8844         }
8845         return new ParceledListSlice<>(getPersistentApplicationsInternal(flags));
8846     }
8847
8848     private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) {
8849         final ArrayList<ApplicationInfo> finalList = new ArrayList<>();
8850
8851         // reader
8852         synchronized (mPackages) {
8853             final Iterator<PackageParser.Package> i = mPackages.values().iterator();
8854             final int userId = UserHandle.getCallingUserId();
8855             while (i.hasNext()) {
8856                 final PackageParser.Package p = i.next();
8857                 if (p.applicationInfo == null) continue;
8858
8859                 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0)
8860                         && !p.applicationInfo.isDirectBootAware();
8861                 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0)
8862                         && p.applicationInfo.isDirectBootAware();
8863
8864                 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0
8865                         && (!mSafeMode || isSystemApp(p))
8866                         && (matchesUnaware || matchesAware)) {
8867                     PackageSetting ps = mSettings.mPackages.get(p.packageName);
8868                     if (ps != null) {
8869                         ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
8870                                 ps.readUserState(userId), userId);
8871                         if (ai != null) {
8872                             finalList.add(ai);
8873                         }
8874                     }
8875                 }
8876             }
8877         }
8878
8879         return finalList;
8880     }
8881
8882     @Override
8883     public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
8884         return resolveContentProviderInternal(name, flags, userId);
8885     }
8886
8887     private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) {
8888         if (!sUserManager.exists(userId)) return null;
8889         flags = updateFlagsForComponent(flags, userId, name);
8890         final int callingUid = Binder.getCallingUid();
8891         final ProviderInfo providerInfo = mComponentResolver.queryProvider(name, flags, userId);
8892         if (providerInfo == null) {
8893             return null;
8894         }
8895         if (!mSettings.isEnabledAndMatchLPr(providerInfo, flags, userId)) {
8896             return null;
8897         }
8898         synchronized (mPackages) {
8899             final PackageSetting ps = mSettings.mPackages.get(providerInfo.packageName);
8900             final ComponentName component =
8901                     new ComponentName(providerInfo.packageName, providerInfo.name);
8902             if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8903                 return null;
8904             }
8905             return providerInfo;
8906         }
8907     }
8908
8909     /**
8910      * @deprecated
8911      */
8912     @Deprecated
8913     public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
8914         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
8915             return;
8916         }
8917         mComponentResolver.querySyncProviders(
8918                 outNames, outInfo, mSafeMode, UserHandle.getCallingUserId());
8919     }
8920
8921     @Override
8922     public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName,
8923             int uid, int flags, String metaDataKey) {
8924         final int callingUid = Binder.getCallingUid();
8925         final int userId = processName != null ? UserHandle.getUserId(uid)
8926                 : UserHandle.getCallingUserId();
8927         if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList();
8928         flags = updateFlagsForComponent(flags, userId, processName);
8929         ArrayList<ProviderInfo> finalList = null;
8930         final List<ProviderInfo> matchList =
8931                 mComponentResolver.queryProviders(processName, metaDataKey, uid, flags, userId);
8932         final int listSize = (matchList == null ? 0 : matchList.size());
8933         synchronized (mPackages) {
8934             for (int i = 0; i < listSize; i++) {
8935                 final ProviderInfo providerInfo = matchList.get(i);
8936                 if (!mSettings.isEnabledAndMatchLPr(providerInfo, flags, userId)) {
8937                     continue;
8938                 }
8939                 final PackageSetting ps = mSettings.mPackages.get(providerInfo.packageName);
8940                 final ComponentName component =
8941                         new ComponentName(providerInfo.packageName, providerInfo.name);
8942                 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) {
8943                     continue;
8944                 }
8945                 if (finalList == null) {
8946                     finalList = new ArrayList<>(listSize - i);
8947                 }
8948                 finalList.add(providerInfo);
8949             }
8950         }
8951
8952         if (finalList != null) {
8953             finalList.sort(sProviderInitOrderSorter);
8954             return new ParceledListSlice<>(finalList);
8955         }
8956
8957         return ParceledListSlice.emptyList();
8958     }
8959
8960     @Override
8961     public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) {
8962         // reader
8963         synchronized (mPackages) {
8964             final int callingUid = Binder.getCallingUid();
8965             final int callingUserId = UserHandle.getUserId(callingUid);
8966             final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
8967             if (ps == null) return null;
8968             if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) {
8969                 return null;
8970             }
8971             final PackageParser.Instrumentation i = mInstrumentation.get(component);
8972             return PackageParser.generateInstrumentationInfo(i, flags);
8973         }
8974     }
8975
8976     @Override
8977     public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation(
8978             String targetPackage, int flags) {
8979         final int callingUid = Binder.getCallingUid();
8980         final int callingUserId = UserHandle.getUserId(callingUid);
8981         final PackageSetting ps = mSettings.mPackages.get(targetPackage);
8982         if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
8983             return ParceledListSlice.emptyList();
8984         }
8985         return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags));
8986     }
8987
8988     private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage,
8989             int flags) {
8990         ArrayList<InstrumentationInfo> finalList = new ArrayList<>();
8991
8992         // reader
8993         synchronized (mPackages) {
8994             final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
8995             while (i.hasNext()) {
8996                 final PackageParser.Instrumentation p = i.next();
8997                 if (targetPackage == null
8998                         || targetPackage.equals(p.info.targetPackage)) {
8999                     InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
9000                             flags);
9001                     if (ii != null) {
9002                         finalList.add(ii);
9003                     }
9004                 }
9005             }
9006         }
9007
9008         return finalList;
9009     }
9010
9011     private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
9012         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]");
9013         try {
9014             scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
9015         } finally {
9016             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9017         }
9018     }
9019
9020     private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
9021         final File[] files = scanDir.listFiles();
9022         if (ArrayUtils.isEmpty(files)) {
9023             Log.d(TAG, "No files in app dir " + scanDir);
9024             return;
9025         }
9026
9027         if (DEBUG_PACKAGE_SCANNING) {
9028             Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags
9029                     + " flags=0x" + Integer.toHexString(parseFlags));
9030         }
9031         try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser(
9032                 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir,
9033                 mParallelPackageParserCallback)) {
9034             // Submit files for parsing in parallel
9035             int fileCount = 0;
9036             for (File file : files) {
9037                 final boolean isPackage = (isApkFile(file) || file.isDirectory())
9038                         && !PackageInstallerService.isStageName(file.getName());
9039                 if (!isPackage) {
9040                     // Ignore entries which are not packages
9041                     continue;
9042                 }
9043                 parallelPackageParser.submit(file, parseFlags);
9044                 fileCount++;
9045             }
9046
9047             // Process results one by one
9048             for (; fileCount > 0; fileCount--) {
9049                 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
9050                 Throwable throwable = parseResult.throwable;
9051                 int errorCode = PackageManager.INSTALL_SUCCEEDED;
9052
9053                 if (throwable == null) {
9054                     // TODO(toddke): move lower in the scan chain
9055                     // Static shared libraries have synthetic package names
9056                     if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) {
9057                         renameStaticSharedLibraryPackage(parseResult.pkg);
9058                     }
9059                     try {
9060                         scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags,
9061                                 currentTime, null);
9062                     } catch (PackageManagerException e) {
9063                         errorCode = e.error;
9064                         Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage());
9065                     }
9066                 } else if (throwable instanceof PackageParser.PackageParserException) {
9067                     PackageParser.PackageParserException e = (PackageParser.PackageParserException)
9068                             throwable;
9069                     errorCode = e.error;
9070                     Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage());
9071                 } else {
9072                     throw new IllegalStateException("Unexpected exception occurred while parsing "
9073                             + parseResult.scanFile, throwable);
9074                 }
9075
9076                 // Delete invalid userdata apps
9077                 if ((scanFlags & SCAN_AS_SYSTEM) == 0 &&
9078                         errorCode != PackageManager.INSTALL_SUCCEEDED) {
9079                     logCriticalInfo(Log.WARN,
9080                             "Deleting invalid package at " + parseResult.scanFile);
9081                     removeCodePathLI(parseResult.scanFile);
9082                 }
9083             }
9084         }
9085     }
9086
9087     public static void reportSettingsProblem(int priority, String msg) {
9088         logCriticalInfo(priority, msg);
9089     }
9090
9091     private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg,
9092             boolean forceCollect, boolean skipVerify) throws PackageManagerException {
9093         // When upgrading from pre-N MR1, verify the package time stamp using the package
9094         // directory and not the APK file.
9095         final long lastModifiedTime = mIsPreNMR1Upgrade
9096                 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg);
9097         final VersionInfo settingsVersionForPackage = getSettingsVersionForPackage(pkg);
9098         if (ps != null && !forceCollect
9099                 && ps.codePathString.equals(pkg.codePath)
9100                 && ps.timeStamp == lastModifiedTime
9101                 && !isCompatSignatureUpdateNeeded(settingsVersionForPackage)
9102                 && !isRecoverSignatureUpdateNeeded(settingsVersionForPackage)) {
9103             if (ps.signatures.mSigningDetails.signatures != null
9104                     && ps.signatures.mSigningDetails.signatures.length != 0
9105                     && ps.signatures.mSigningDetails.signatureSchemeVersion
9106                             != SignatureSchemeVersion.UNKNOWN) {
9107                 // Optimization: reuse the existing cached signing data
9108                 // if the package appears to be unchanged.
9109                 pkg.mSigningDetails =
9110                         new PackageParser.SigningDetails(ps.signatures.mSigningDetails);
9111                 return;
9112             }
9113
9114             Slog.w(TAG, "PackageSetting for " + ps.name
9115                     + " is missing signatures.  Collecting certs again to recover them.");
9116         } else {
9117             Slog.i(TAG, pkg.codePath + " changed; collecting certs" +
9118                     (forceCollect ? " (forced)" : ""));
9119         }
9120
9121         try {
9122             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates");
9123             PackageParser.collectCertificates(pkg, skipVerify);
9124         } catch (PackageParserException e) {
9125             throw PackageManagerException.from(e);
9126         } finally {
9127             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9128         }
9129     }
9130
9131     /**
9132      * Clear the package profile if this was an upgrade and the package
9133      * version was updated.
9134      */
9135     private void maybeClearProfilesForUpgradesLI(
9136             @Nullable PackageSetting originalPkgSetting,
9137             @NonNull PackageParser.Package currentPkg) {
9138         if (originalPkgSetting == null || !isDeviceUpgrading()) {
9139           return;
9140         }
9141         if (originalPkgSetting.versionCode == currentPkg.mVersionCode) {
9142           return;
9143         }
9144
9145         clearAppProfilesLIF(currentPkg, UserHandle.USER_ALL);
9146         if (DEBUG_INSTALL) {
9147             Slog.d(TAG, originalPkgSetting.name
9148                   + " clear profile due to version change "
9149                   + originalPkgSetting.versionCode + " != "
9150                   + currentPkg.mVersionCode);
9151         }
9152     }
9153
9154     /**
9155      *  Traces a package scan.
9156      *  @see #scanPackageLI(File, int, int, long, UserHandle)
9157      */
9158     @GuardedBy({"mInstallLock", "mPackages"})
9159     private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags,
9160             int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
9161         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]");
9162         try {
9163             return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user);
9164         } finally {
9165             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9166         }
9167     }
9168
9169     /**
9170      *  Scans a package and returns the newly parsed package.
9171      *  Returns {@code null} in case of errors and the error code is stored in mLastScanError
9172      */
9173     @GuardedBy({"mInstallLock", "mPackages"})
9174     private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
9175             long currentTime, UserHandle user) throws PackageManagerException {
9176         if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
9177         PackageParser pp = new PackageParser();
9178         pp.setSeparateProcesses(mSeparateProcesses);
9179         pp.setOnlyCoreApps(mOnlyCore);
9180         pp.setDisplayMetrics(mMetrics);
9181         pp.setCallback(mPackageParserCallback);
9182
9183         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
9184         final PackageParser.Package pkg;
9185         try {
9186             pkg = pp.parsePackage(scanFile, parseFlags);
9187         } catch (PackageParserException e) {
9188             throw PackageManagerException.from(e);
9189         } finally {
9190             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9191         }
9192
9193         // Static shared libraries have synthetic package names
9194         if (pkg.applicationInfo.isStaticSharedLibrary()) {
9195             renameStaticSharedLibraryPackage(pkg);
9196         }
9197
9198         return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
9199     }
9200
9201     /**
9202      *  Scans a package and returns the newly parsed package.
9203      *  @throws PackageManagerException on a parse error.
9204      */
9205     @GuardedBy({"mInstallLock", "mPackages"})
9206     private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg,
9207             final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9208             @Nullable UserHandle user)
9209                     throws PackageManagerException {
9210         // If the package has children and this is the first dive in the function
9211         // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all
9212         // packages (parent and children) would be successfully scanned before the
9213         // actual scan since scanning mutates internal state and we want to atomically
9214         // install the package and its children.
9215         if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
9216             if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
9217                 scanFlags |= SCAN_CHECK_ONLY;
9218             }
9219         } else {
9220             scanFlags &= ~SCAN_CHECK_ONLY;
9221         }
9222
9223         // Scan the parent
9224         PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags,
9225                 scanFlags, currentTime, user);
9226
9227         // Scan the children
9228         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
9229         for (int i = 0; i < childCount; i++) {
9230             PackageParser.Package childPackage = pkg.childPackages.get(i);
9231             addForInitLI(childPackage, parseFlags, scanFlags,
9232                     currentTime, user);
9233         }
9234
9235
9236         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
9237             return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user);
9238         }
9239
9240         return scannedPkg;
9241     }
9242
9243     /**
9244      * Returns if forced apk verification can be skipped for the whole package, including splits.
9245      */
9246     private boolean canSkipForcedPackageVerification(PackageParser.Package pkg) {
9247         if (!canSkipForcedApkVerification(pkg.baseCodePath)) {
9248             return false;
9249         }
9250         // TODO: Allow base and splits to be verified individually.
9251         if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
9252             for (int i = 0; i < pkg.splitCodePaths.length; i++) {
9253                 if (!canSkipForcedApkVerification(pkg.splitCodePaths[i])) {
9254                     return false;
9255                 }
9256             }
9257         }
9258         return true;
9259     }
9260
9261     /**
9262      * Returns if forced apk verification can be skipped, depending on current FSVerity setup and
9263      * whether the apk contains signed root hash.  Note that the signer's certificate still needs to
9264      * match one in a trusted source, and should be done separately.
9265      */
9266     private boolean canSkipForcedApkVerification(String apkPath) {
9267         if (!PackageManagerServiceUtils.isLegacyApkVerityEnabled()) {
9268             return VerityUtils.hasFsverity(apkPath);
9269         }
9270
9271         try {
9272             final byte[] rootHashObserved = VerityUtils.generateApkVerityRootHash(apkPath);
9273             if (rootHashObserved == null) {
9274                 return false;  // APK does not contain Merkle tree root hash.
9275             }
9276             synchronized (mInstallLock) {
9277                 // Returns whether the observed root hash matches what kernel has.
9278                 mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved);
9279                 return true;
9280             }
9281         } catch (InstallerException | IOException | DigestException |
9282                 NoSuchAlgorithmException e) {
9283             Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e);
9284         }
9285         return false;
9286     }
9287
9288     /**
9289      * Adds a new package to the internal data structures during platform initialization.
9290      * <p>After adding, the package is known to the system and available for querying.
9291      * <p>For packages located on the device ROM [eg. packages located in /system, /vendor,
9292      * etc...], additional checks are performed. Basic verification [such as ensuring
9293      * matching signatures, checking version codes, etc...] occurs if the package is
9294      * identical to a previously known package. If the package fails a signature check,
9295      * the version installed on /data will be removed. If the version of the new package
9296      * is less than or equal than the version on /data, it will be ignored.
9297      * <p>Regardless of the package location, the results are applied to the internal
9298      * structures and the package is made available to the rest of the system.
9299      * <p>NOTE: The return value should be removed. It's the passed in package object.
9300      */
9301     @GuardedBy({"mInstallLock", "mPackages"})
9302     private PackageParser.Package addForInitLI(PackageParser.Package pkg,
9303             @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
9304             @Nullable UserHandle user)
9305                     throws PackageManagerException {
9306         final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0;
9307         final String renamedPkgName;
9308         final PackageSetting disabledPkgSetting;
9309         final boolean isSystemPkgUpdated;
9310         final boolean pkgAlreadyExists;
9311         PackageSetting pkgSetting;
9312
9313         // NOTE: installPackageLI() has the same code to setup the package's
9314         // application info. This probably should be done lower in the call
9315         // stack [such as scanPackageOnly()]. However, we verify the application
9316         // info prior to that [in scanPackageNew()] and thus have to setup
9317         // the application info early.
9318         pkg.setApplicationVolumeUuid(pkg.volumeUuid);
9319         pkg.setApplicationInfoCodePath(pkg.codePath);
9320         pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
9321         pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
9322         pkg.setApplicationInfoResourcePath(pkg.codePath);
9323         pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
9324         pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
9325
9326         synchronized (mPackages) {
9327             renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
9328             final String realPkgName = getRealPackageName(pkg, renamedPkgName);
9329             if (realPkgName != null) {
9330                 ensurePackageRenamed(pkg, renamedPkgName);
9331             }
9332             final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
9333             final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName);
9334             pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting;
9335             pkgAlreadyExists = pkgSetting != null;
9336             final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName;
9337             disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName);
9338             isSystemPkgUpdated = disabledPkgSetting != null;
9339
9340             if (DEBUG_INSTALL && isSystemPkgUpdated) {
9341                 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting);
9342             }
9343
9344             final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null)
9345                     ? mSettings.getSharedUserLPw(pkg.mSharedUserId,
9346                             0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true)
9347                     : null;
9348             if (DEBUG_PACKAGE_SCANNING
9349                     && (parseFlags & PackageParser.PARSE_CHATTY) != 0
9350                     && sharedUserSetting != null) {
9351                 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
9352                         + " (uid=" + sharedUserSetting.userId + "):"
9353                         + " packages=" + sharedUserSetting.packages);
9354             }
9355
9356             if (scanSystemPartition) {
9357                 // Potentially prune child packages. If the application on the /system
9358                 // partition has been updated via OTA, but, is still disabled by a
9359                 // version on /data, cycle through all of its children packages and
9360                 // remove children that are no longer defined.
9361                 if (isSystemPkgUpdated) {
9362                     final int scannedChildCount = (pkg.childPackages != null)
9363                             ? pkg.childPackages.size() : 0;
9364                     final int disabledChildCount = disabledPkgSetting.childPackageNames != null
9365                             ? disabledPkgSetting.childPackageNames.size() : 0;
9366                     for (int i = 0; i < disabledChildCount; i++) {
9367                         String disabledChildPackageName =
9368                                 disabledPkgSetting.childPackageNames.get(i);
9369                         boolean disabledPackageAvailable = false;
9370                         for (int j = 0; j < scannedChildCount; j++) {
9371                             PackageParser.Package childPkg = pkg.childPackages.get(j);
9372                             if (childPkg.packageName.equals(disabledChildPackageName)) {
9373                                 disabledPackageAvailable = true;
9374                                 break;
9375                             }
9376                         }
9377                         if (!disabledPackageAvailable) {
9378                             mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName);
9379                         }
9380                     }
9381                     // we're updating the disabled package, so, scan it as the package setting
9382                     final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, null,
9383                             disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */,
9384                             null /* originalPkgSetting */, null, parseFlags, scanFlags,
9385                             (pkg == mPlatformPackage), user);
9386                     applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
9387                     final ScanResult scanResult = scanPackageOnlyLI(request, mFactoryTest, -1L);
9388                     if (scanResult.existingSettingCopied && scanResult.request.pkgSetting != null) {
9389                         scanResult.request.pkgSetting.updateFrom(scanResult.pkgSetting);
9390                     }
9391                 }
9392             }
9393         }
9394
9395         final boolean newPkgChangedPaths =
9396                 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath);
9397         final boolean newPkgVersionGreater =
9398                 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode;
9399         final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated
9400                 && newPkgChangedPaths && newPkgVersionGreater;
9401         if (isSystemPkgBetter) {
9402             // The version of the application on /system is greater than the version on
9403             // /data. Switch back to the application on /system.
9404             // It's safe to assume the application on /system will correctly scan. If not,
9405             // there won't be a working copy of the application.
9406             synchronized (mPackages) {
9407                 // just remove the loaded entries from package lists
9408                 mPackages.remove(pkgSetting.name);
9409             }
9410
9411             logCriticalInfo(Log.WARN,
9412                     "System package updated;"
9413                     + " name: " + pkgSetting.name
9414                     + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
9415                     + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
9416
9417             final InstallArgs args = createInstallArgsForExisting(
9418                     pkgSetting.codePathString,
9419                     pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
9420             args.cleanUpResourcesLI();
9421             synchronized (mPackages) {
9422                 mSettings.enableSystemPackageLPw(pkgSetting.name);
9423             }
9424         }
9425
9426         if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) {
9427             // The version of the application on the /system partition is less than or
9428             // equal to the version on the /data partition. Throw an exception and use
9429             // the application already installed on the /data partition.
9430             throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at "
9431                     + pkg.codePath + " ignored: updated version " + pkgSetting.versionCode
9432                     + " better than this " + pkg.getLongVersionCode());
9433         }
9434
9435         // Verify certificates against what was last scanned. If there was an upgrade and this is an
9436         // app in a system partition, or if this is an updated priv app, we will force re-collecting
9437         // certificate.
9438         final boolean forceCollect = (mIsUpgrade && scanSystemPartition)
9439                 || PackageManagerServiceUtils.isApkVerificationForced(disabledPkgSetting);
9440         // Full APK verification can be skipped during certificate collection, only if the file is
9441         // in verified partition, or can be verified on access (when apk verity is enabled). In both
9442         // cases, only data in Signing Block is verified instead of the whole file.
9443         final boolean skipVerify = scanSystemPartition
9444                 || (forceCollect && canSkipForcedPackageVerification(pkg));
9445         collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify);
9446
9447         // Reset profile if the application version is changed
9448         maybeClearProfilesForUpgradesLI(pkgSetting, pkg);
9449
9450         /*
9451          * A new system app appeared, but we already had a non-system one of the
9452          * same name installed earlier.
9453          */
9454         boolean shouldHideSystemApp = false;
9455         // A new application appeared on /system, but, we already have a copy of
9456         // the application installed on /data.
9457         if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists
9458                 && !pkgSetting.isSystem()) {
9459
9460             if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails,
9461                     PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)
9462                             && !pkgSetting.signatures.mSigningDetails.checkCapability(
9463                                     pkg.mSigningDetails,
9464                                     PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) {
9465                 logCriticalInfo(Log.WARN,
9466                         "System package signature mismatch;"
9467                         + " name: " + pkgSetting.name);
9468                 try (PackageFreezer freezer = freezePackage(pkg.packageName,
9469                         "scanPackageInternalLI")) {
9470                     deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null);
9471                 }
9472                 pkgSetting = null;
9473             } else if (newPkgVersionGreater) {
9474                 // The application on /system is newer than the application on /data.
9475                 // Simply remove the application on /data [keeping application data]
9476                 // and replace it with the version on /system.
9477                 logCriticalInfo(Log.WARN,
9478                         "System package enabled;"
9479                         + " name: " + pkgSetting.name
9480                         + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode()
9481                         + "; " + pkgSetting.codePathString + " --> " + pkg.codePath);
9482                 InstallArgs args = createInstallArgsForExisting(
9483                         pkgSetting.codePathString,
9484                         pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting));
9485                 synchronized (mInstallLock) {
9486                     args.cleanUpResourcesLI();
9487                 }
9488             } else {
9489                 // The application on /system is older than the application on /data. Hide
9490                 // the application on /system and the version on /data will be scanned later
9491                 // and re-added like an update.
9492                 shouldHideSystemApp = true;
9493                 logCriticalInfo(Log.INFO,
9494                         "System package disabled;"
9495                         + " name: " + pkgSetting.name
9496                         + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode
9497                         + "; new: " + pkg.codePath + " @ " + pkg.codePath);
9498             }
9499         }
9500
9501         final ScanResult scanResult = scanPackageNewLI(pkg, parseFlags, scanFlags
9502                 | SCAN_UPDATE_SIGNATURE, currentTime, user);
9503         if (scanResult.success) {
9504             synchronized (mPackages) {
9505                 boolean appIdCreated = false;
9506                 try {
9507                     final String pkgName = scanResult.pkgSetting.name;
9508                     final Map<String, ReconciledPackage> reconcileResult = reconcilePackagesLocked(
9509                             new ReconcileRequest(
9510                                     Collections.singletonMap(pkgName, scanResult),
9511                                     mSharedLibraries,
9512                                     mPackages,
9513                                     Collections.singletonMap(
9514                                             pkgName, getSettingsVersionForPackage(pkg)),
9515                                     Collections.singletonMap(pkgName,
9516                                             getSharedLibLatestVersionSetting(scanResult))),
9517                             mSettings.mKeySetManagerService);
9518                     appIdCreated = optimisticallyRegisterAppId(scanResult);
9519                     commitReconciledScanResultLocked(reconcileResult.get(pkgName));
9520                 } catch (PackageManagerException e) {
9521                     if (appIdCreated) {
9522                         cleanUpAppIdCreation(scanResult);
9523                     }
9524                     throw e;
9525                 }
9526             }
9527         }
9528
9529         if (shouldHideSystemApp) {
9530             synchronized (mPackages) {
9531                 mSettings.disableSystemPackageLPw(pkg.packageName, true);
9532             }
9533         }
9534         return scanResult.pkgSetting.pkg;
9535     }
9536
9537     private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) {
9538         // Derive the new package synthetic package name
9539         pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER
9540                 + pkg.staticSharedLibVersion);
9541     }
9542
9543     static String fixProcessName(String defProcessName, String processName) {
9544         if (processName == null) {
9545             return defProcessName;
9546         }
9547         return processName;
9548     }
9549
9550     /**
9551      * Enforces that only the system UID or root's UID can call a method exposed
9552      * via Binder.
9553      *
9554      * @param message used as message if SecurityException is thrown
9555      * @throws SecurityException if the caller is not system or root
9556      */
9557     private static void enforceSystemOrRoot(String message) {
9558         final int uid = Binder.getCallingUid();
9559         if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) {
9560             throw new SecurityException(message);
9561         }
9562     }
9563
9564     /**
9565      * Enforces that only the system UID or root's UID or shell's UID can call
9566      * a method exposed via Binder.
9567      *
9568      * @param message used as message if SecurityException is thrown
9569      * @throws SecurityException if the caller is not system or shell
9570      */
9571     private static void enforceSystemOrRootOrShell(String message) {
9572         final int uid = Binder.getCallingUid();
9573         if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID && uid != Process.SHELL_UID) {
9574             throw new SecurityException(message);
9575         }
9576     }
9577
9578     @Override
9579     public void performFstrimIfNeeded() {
9580         enforceSystemOrRoot("Only the system can request fstrim");
9581
9582         // Before everything else, see whether we need to fstrim.
9583         try {
9584             IStorageManager sm = PackageHelper.getStorageManager();
9585             if (sm != null) {
9586                 boolean doTrim = false;
9587                 final long interval = android.provider.Settings.Global.getLong(
9588                         mContext.getContentResolver(),
9589                         android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
9590                         DEFAULT_MANDATORY_FSTRIM_INTERVAL);
9591                 if (interval > 0) {
9592                     final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance();
9593                     if (timeSinceLast > interval) {
9594                         doTrim = true;
9595                         Slog.w(TAG, "No disk maintenance in " + timeSinceLast
9596                                 + "; running immediately");
9597                     }
9598                 }
9599                 if (doTrim) {
9600                     final boolean dexOptDialogShown;
9601                     synchronized (mPackages) {
9602                         dexOptDialogShown = mDexOptDialogShown;
9603                     }
9604                     if (!isFirstBoot() && dexOptDialogShown) {
9605                         try {
9606                             ActivityManager.getService().showBootMessage(
9607                                     mContext.getResources().getString(
9608                                             R.string.android_upgrading_fstrim), true);
9609                         } catch (RemoteException e) {
9610                         }
9611                     }
9612                     sm.runMaintenance();
9613                 }
9614             } else {
9615                 Slog.e(TAG, "storageManager service unavailable!");
9616             }
9617         } catch (RemoteException e) {
9618             // Can't happen; StorageManagerService is local
9619         }
9620     }
9621
9622     @Override
9623     public void updatePackagesIfNeeded() {
9624         enforceSystemOrRoot("Only the system can request package update");
9625
9626         // We need to re-extract after an OTA.
9627         boolean causeUpgrade = isDeviceUpgrading();
9628
9629         // First boot or factory reset.
9630         // Note: we also handle devices that are upgrading to N right now as if it is their
9631         //       first boot, as they do not have profile data.
9632         boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade;
9633
9634         // We need to re-extract after a pruned cache, as AoT-ed files will be out of date.
9635         boolean causePrunedCache = VMRuntime.didPruneDalvikCache();
9636
9637         if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) {
9638             return;
9639         }
9640
9641         List<PackageParser.Package> pkgs;
9642         synchronized (mPackages) {
9643             pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this);
9644         }
9645
9646         final long startTime = System.nanoTime();
9647         final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */,
9648                     causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT,
9649                     false /* bootComplete */);
9650
9651         final int elapsedTimeSeconds =
9652                 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime);
9653
9654         MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]);
9655         MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]);
9656         MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]);
9657         MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size());
9658         MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds);
9659     }
9660
9661     /*
9662      * Return the prebuilt profile path given a package base code path.
9663      */
9664     private static String getPrebuildProfilePath(PackageParser.Package pkg) {
9665         return pkg.baseCodePath + ".prof";
9666     }
9667
9668     /**
9669      * Performs dexopt on the set of packages in {@code packages} and returns an int array
9670      * containing statistics about the invocation. The array consists of three elements,
9671      * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped}
9672      * and {@code numberOfPackagesFailed}.
9673      */
9674     private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog,
9675             final int compilationReason, boolean bootComplete) {
9676
9677         int numberOfPackagesVisited = 0;
9678         int numberOfPackagesOptimized = 0;
9679         int numberOfPackagesSkipped = 0;
9680         int numberOfPackagesFailed = 0;
9681         final int numberOfPackagesToDexopt = pkgs.size();
9682
9683         for (PackageParser.Package pkg : pkgs) {
9684             numberOfPackagesVisited++;
9685
9686             boolean useProfileForDexopt = false;
9687
9688             if ((isFirstBoot() || isDeviceUpgrading()) && isSystemApp(pkg)) {
9689                 // Copy over initial preopt profiles since we won't get any JIT samples for methods
9690                 // that are already compiled.
9691                 File profileFile = new File(getPrebuildProfilePath(pkg));
9692                 // Copy profile if it exists.
9693                 if (profileFile.exists()) {
9694                     try {
9695                         // We could also do this lazily before calling dexopt in
9696                         // PackageDexOptimizer to prevent this happening on first boot. The issue
9697                         // is that we don't have a good way to say "do this only once".
9698                         if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9699                                 pkg.applicationInfo.uid, pkg.packageName,
9700                                 ArtManager.getProfileName(null))) {
9701                             Log.e(TAG, "Installer failed to copy system profile!");
9702                         } else {
9703                             // Disabled as this causes speed-profile compilation during first boot
9704                             // even if things are already compiled.
9705                             // useProfileForDexopt = true;
9706                         }
9707                     } catch (Exception e) {
9708                         Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ",
9709                                 e);
9710                     }
9711                 } else {
9712                     PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName);
9713                     // Handle compressed APKs in this path. Only do this for stubs with profiles to
9714                     // minimize the number off apps being speed-profile compiled during first boot.
9715                     // The other paths will not change the filter.
9716                     if (disabledPs != null && disabledPs.pkg.isStub) {
9717                         // The package is the stub one, remove the stub suffix to get the normal
9718                         // package and APK names.
9719                         String systemProfilePath =
9720                                 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, "");
9721                         profileFile = new File(systemProfilePath);
9722                         // If we have a profile for a compressed APK, copy it to the reference
9723                         // location.
9724                         // Note that copying the profile here will cause it to override the
9725                         // reference profile every OTA even though the existing reference profile
9726                         // may have more data. We can't copy during decompression since the
9727                         // directories are not set up at that point.
9728                         if (profileFile.exists()) {
9729                             try {
9730                                 // We could also do this lazily before calling dexopt in
9731                                 // PackageDexOptimizer to prevent this happening on first boot. The
9732                                 // issue is that we don't have a good way to say "do this only
9733                                 // once".
9734                                 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(),
9735                                         pkg.applicationInfo.uid, pkg.packageName,
9736                                         ArtManager.getProfileName(null))) {
9737                                     Log.e(TAG, "Failed to copy system profile for stub package!");
9738                                 } else {
9739                                     useProfileForDexopt = true;
9740                                 }
9741                             } catch (Exception e) {
9742                                 Log.e(TAG, "Failed to copy profile " +
9743                                         profileFile.getAbsolutePath() + " ", e);
9744                             }
9745                         }
9746                     }
9747                 }
9748             }
9749
9750             if (!PackageDexOptimizer.canOptimizePackage(pkg)) {
9751                 if (DEBUG_DEXOPT) {
9752                     Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName);
9753                 }
9754                 numberOfPackagesSkipped++;
9755                 continue;
9756             }
9757
9758             if (DEBUG_DEXOPT) {
9759                 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " +
9760                         numberOfPackagesToDexopt + ": " + pkg.packageName);
9761             }
9762
9763             if (showDialog) {
9764                 try {
9765                     ActivityManager.getService().showBootMessage(
9766                             mContext.getResources().getString(R.string.android_upgrading_apk,
9767                                     numberOfPackagesVisited, numberOfPackagesToDexopt), true);
9768                 } catch (RemoteException e) {
9769                 }
9770                 synchronized (mPackages) {
9771                     mDexOptDialogShown = true;
9772                 }
9773             }
9774
9775             int pkgCompilationReason = compilationReason;
9776             if (useProfileForDexopt) {
9777                 // Use background dexopt mode to try and use the profile. Note that this does not
9778                 // guarantee usage of the profile.
9779                 pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT;
9780             }
9781
9782             if (SystemProperties.getBoolean(PRECOMPILE_LAYOUTS, false)) {
9783                 mArtManagerService.compileLayouts(pkg);
9784             }
9785
9786             // checkProfiles is false to avoid merging profiles during boot which
9787             // might interfere with background compilation (b/28612421).
9788             // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will
9789             // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a
9790             // trade-off worth doing to save boot time work.
9791             int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0;
9792             if (compilationReason == REASON_FIRST_BOOT) {
9793                 // TODO: This doesn't cover the upgrade case, we should check for this too.
9794                 dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE;
9795             }
9796             int primaryDexOptStaus = performDexOptTraced(new DexoptOptions(
9797                     pkg.packageName,
9798                     pkgCompilationReason,
9799                     dexoptFlags));
9800
9801             switch (primaryDexOptStaus) {
9802                 case PackageDexOptimizer.DEX_OPT_PERFORMED:
9803                     numberOfPackagesOptimized++;
9804                     break;
9805                 case PackageDexOptimizer.DEX_OPT_SKIPPED:
9806                     numberOfPackagesSkipped++;
9807                     break;
9808                 case PackageDexOptimizer.DEX_OPT_FAILED:
9809                     numberOfPackagesFailed++;
9810                     break;
9811                 default:
9812                     Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus);
9813                     break;
9814             }
9815         }
9816
9817         return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped,
9818                 numberOfPackagesFailed };
9819     }
9820
9821     @Override
9822     public void notifyPackageUse(String packageName, int reason) {
9823         synchronized (mPackages) {
9824             final int callingUid = Binder.getCallingUid();
9825             final int callingUserId = UserHandle.getUserId(callingUid);
9826             if (getInstantAppPackageName(callingUid) != null) {
9827                 if (!isCallerSameApp(packageName, callingUid)) {
9828                     return;
9829                 }
9830             } else {
9831                 if (isInstantApp(packageName, callingUserId)) {
9832                     return;
9833                 }
9834             }
9835             notifyPackageUseLocked(packageName, reason);
9836         }
9837     }
9838
9839     @GuardedBy("mPackages")
9840     public CheckPermissionDelegate getCheckPermissionDelegateLocked() {
9841         return mCheckPermissionDelegate;
9842     }
9843
9844     @GuardedBy("mPackages")
9845     public void setCheckPermissionDelegateLocked(CheckPermissionDelegate delegate) {
9846         mCheckPermissionDelegate = delegate;
9847     }
9848
9849     @GuardedBy("mPackages")
9850     private void notifyPackageUseLocked(String packageName, int reason) {
9851         final PackageParser.Package p = mPackages.get(packageName);
9852         if (p == null) {
9853             return;
9854         }
9855         p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis();
9856     }
9857
9858     @Override
9859     public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames,
9860             List<String> classPaths, String loaderIsa) {
9861         int userId = UserHandle.getCallingUserId();
9862         ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId);
9863         if (ai == null) {
9864             Slog.w(TAG, "Loading a package that does not exist for the calling user. package="
9865                 + loadingPackageName + ", user=" + userId);
9866             return;
9867         }
9868         mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId);
9869     }
9870
9871     @Override
9872     public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule,
9873             IDexModuleRegisterCallback callback) {
9874         int userId = UserHandle.getCallingUserId();
9875         ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId);
9876         DexManager.RegisterDexModuleResult result;
9877         if (ai == null) {
9878             Slog.w(TAG, "Registering a dex module for a package that does not exist for the" +
9879                      " calling user. package=" + packageName + ", user=" + userId);
9880             result = new DexManager.RegisterDexModuleResult(false, "Package not installed");
9881         } else {
9882             result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId);
9883         }
9884
9885         if (callback != null) {
9886             mHandler.post(() -> {
9887                 try {
9888                     callback.onDexModuleRegistered(dexModulePath, result.success, result.message);
9889                 } catch (RemoteException e) {
9890                     Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e);
9891                 }
9892             });
9893         }
9894     }
9895
9896     /**
9897      * Ask the package manager to perform a dex-opt with the given compiler filter.
9898      *
9899      * Note: exposed only for the shell command to allow moving packages explicitly to a
9900      *       definite state.
9901      */
9902     @Override
9903     public boolean performDexOptMode(String packageName,
9904             boolean checkProfiles, String targetCompilerFilter, boolean force,
9905             boolean bootComplete, String splitName) {
9906         int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) |
9907                 (force ? DexoptOptions.DEXOPT_FORCE : 0) |
9908                 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0);
9909         return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN,
9910                 targetCompilerFilter, splitName, flags));
9911     }
9912
9913     /**
9914      * Ask the package manager to perform a dex-opt with the given compiler filter on the
9915      * secondary dex files belonging to the given package.
9916      *
9917      * Note: exposed only for the shell command to allow moving packages explicitly to a
9918      *       definite state.
9919      */
9920     @Override
9921     public boolean performDexOptSecondary(String packageName, String compilerFilter,
9922             boolean force) {
9923         int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX |
9924                 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES |
9925                 DexoptOptions.DEXOPT_BOOT_COMPLETE |
9926                 (force ? DexoptOptions.DEXOPT_FORCE : 0);
9927         return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags));
9928     }
9929
9930     /**
9931     * Ask the package manager to compile layouts in the given package.
9932     */
9933     @Override
9934     public boolean compileLayouts(String packageName) {
9935         PackageParser.Package pkg;
9936         synchronized (mPackages) {
9937             pkg = mPackages.get(packageName);
9938             if (pkg == null) {
9939                 return false;
9940             }
9941         }
9942         return mViewCompiler.compileLayouts(pkg);
9943     }
9944
9945     /*package*/ boolean performDexOpt(DexoptOptions options) {
9946         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
9947             return false;
9948         } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) {
9949             return false;
9950         }
9951
9952         if (options.isDexoptOnlySecondaryDex()) {
9953             return mDexManager.dexoptSecondaryDex(options);
9954         } else {
9955             int dexoptStatus = performDexOptWithStatus(options);
9956             return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED;
9957         }
9958     }
9959
9960     /**
9961      * Perform dexopt on the given package and return one of following result:
9962      *  {@link PackageDexOptimizer#DEX_OPT_SKIPPED}
9963      *  {@link PackageDexOptimizer#DEX_OPT_PERFORMED}
9964      *  {@link PackageDexOptimizer#DEX_OPT_FAILED}
9965      */
9966     /* package */ int performDexOptWithStatus(DexoptOptions options) {
9967         return performDexOptTraced(options);
9968     }
9969
9970     private int performDexOptTraced(DexoptOptions options) {
9971         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
9972         try {
9973             return performDexOptInternal(options);
9974         } finally {
9975             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
9976         }
9977     }
9978
9979     // Run dexopt on a given package. Returns true if dexopt did not fail, i.e.
9980     // if the package can now be considered up to date for the given filter.
9981     private int performDexOptInternal(DexoptOptions options) {
9982         PackageParser.Package p;
9983         synchronized (mPackages) {
9984             p = mPackages.get(options.getPackageName());
9985             if (p == null) {
9986                 // Package could not be found. Report failure.
9987                 return PackageDexOptimizer.DEX_OPT_FAILED;
9988             }
9989             mPackageUsage.maybeWriteAsync(mPackages);
9990             mCompilerStats.maybeWriteAsync();
9991         }
9992         long callingId = Binder.clearCallingIdentity();
9993         try {
9994             synchronized (mInstallLock) {
9995                 return performDexOptInternalWithDependenciesLI(p, options);
9996             }
9997         } finally {
9998             Binder.restoreCallingIdentity(callingId);
9999         }
10000     }
10001
10002     public ArraySet<String> getOptimizablePackages() {
10003         ArraySet<String> pkgs = new ArraySet<>();
10004         synchronized (mPackages) {
10005             for (PackageParser.Package p : mPackages.values()) {
10006                 if (PackageDexOptimizer.canOptimizePackage(p)) {
10007                     pkgs.add(p.packageName);
10008                 }
10009             }
10010         }
10011         return pkgs;
10012     }
10013
10014     private int performDexOptInternalWithDependenciesLI(PackageParser.Package p,
10015             DexoptOptions options) {
10016         // Select the dex optimizer based on the force parameter.
10017         // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to
10018         //       allocate an object here.
10019         PackageDexOptimizer pdo = options.isForce()
10020                 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer)
10021                 : mPackageDexOptimizer;
10022
10023         // Dexopt all dependencies first. Note: we ignore the return value and march on
10024         // on errors.
10025         // Note that we are going to call performDexOpt on those libraries as many times as
10026         // they are referenced in packages. When we do a batch of performDexOpt (for example
10027         // at boot, or background job), the passed 'targetCompilerFilter' stays the same,
10028         // and the first package that uses the library will dexopt it. The
10029         // others will see that the compiled code for the library is up to date.
10030         Collection<SharedLibraryInfo> deps = findSharedLibraries(p);
10031         final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo);
10032         if (!deps.isEmpty()) {
10033             DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(),
10034                     options.getCompilationReason(), options.getCompilerFilter(),
10035                     options.getSplitName(),
10036                     options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY);
10037             for (SharedLibraryInfo info : deps) {
10038                 PackageParser.Package depPackage = null;
10039                 synchronized (mPackages) {
10040                     depPackage = mPackages.get(info.getPackageName());
10041                 }
10042                 if (depPackage != null) {
10043                     // TODO: Analyze and investigate if we (should) profile libraries.
10044                     pdo.performDexOpt(depPackage, instructionSets,
10045                             getOrCreateCompilerPackageStats(depPackage),
10046                             mDexManager.getPackageUseInfoOrDefault(depPackage.packageName),
10047                             libraryOptions);
10048                 } else {
10049                     // TODO(ngeoffray): Support dexopting system shared libraries.
10050                 }
10051             }
10052         }
10053         return pdo.performDexOpt(p, instructionSets,
10054                 getOrCreateCompilerPackageStats(p),
10055                 mDexManager.getPackageUseInfoOrDefault(p.packageName), options);
10056     }
10057
10058     /**
10059      * Reconcile the information we have about the secondary dex files belonging to
10060      * {@code packageName} and the actual dex files. For all dex files that were
10061      * deleted, update the internal records and delete the generated oat files.
10062      */
10063     @Override
10064     public void reconcileSecondaryDexFiles(String packageName) {
10065         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10066             return;
10067         } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) {
10068             return;
10069         }
10070         mDexManager.reconcileSecondaryDexFiles(packageName);
10071     }
10072
10073     // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject
10074     // a reference there.
10075     /*package*/ DexManager getDexManager() {
10076         return mDexManager;
10077     }
10078
10079     /**
10080      * Execute the background dexopt job immediately.
10081      */
10082     @Override
10083     public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) {
10084         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
10085             return false;
10086         }
10087         enforceSystemOrRootOrShell("runBackgroundDexoptJob");
10088         final long identity = Binder.clearCallingIdentity();
10089         try {
10090             return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames);
10091         } finally {
10092             Binder.restoreCallingIdentity(identity);
10093         }
10094     }
10095
10096     private static List<SharedLibraryInfo> findSharedLibraries(PackageParser.Package p) {
10097         if (p.usesLibraryInfos != null) {
10098             ArrayList<SharedLibraryInfo> retValue = new ArrayList<>();
10099             Set<String> collectedNames = new HashSet<>();
10100             for (SharedLibraryInfo info : p.usesLibraryInfos) {
10101                 findSharedLibrariesRecursive(info, retValue, collectedNames);
10102             }
10103             return retValue;
10104         } else {
10105             return Collections.emptyList();
10106         }
10107     }
10108
10109     private static void findSharedLibrariesRecursive(SharedLibraryInfo info,
10110             ArrayList<SharedLibraryInfo> collected, Set<String> collectedNames) {
10111         if (!collectedNames.contains(info.getName())) {
10112             collectedNames.add(info.getName());
10113             collected.add(info);
10114
10115             if (info.getDependencies() != null) {
10116                 for (SharedLibraryInfo dep : info.getDependencies()) {
10117                     findSharedLibrariesRecursive(dep, collected, collectedNames);
10118                 }
10119             }
10120         }
10121     }
10122
10123     List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package pkg) {
10124         List<SharedLibraryInfo> deps = findSharedLibraries(pkg);
10125         if (!deps.isEmpty()) {
10126             ArrayList<PackageParser.Package> retValue = new ArrayList<>();
10127             synchronized (mPackages) {
10128                 for (SharedLibraryInfo info : deps) {
10129                     PackageParser.Package depPackage = mPackages.get(info.getPackageName());
10130                     if (depPackage != null) {
10131                         retValue.add(depPackage);
10132                     }
10133                 }
10134             }
10135             return retValue;
10136         } else {
10137             return Collections.emptyList();
10138         }
10139     }
10140
10141     @Nullable
10142     private SharedLibraryInfo getSharedLibraryInfoLPr(String name, long version) {
10143         return getSharedLibraryInfo(name, version, mSharedLibraries, null);
10144     }
10145
10146     @Nullable
10147     private static SharedLibraryInfo getSharedLibraryInfo(String name, long version,
10148             Map<String, LongSparseArray<SharedLibraryInfo>> existingLibraries,
10149             @Nullable Map<String, LongSparseArray<SharedLibraryInfo>> newLibraries) {
10150         if (newLibraries != null) {
10151             final LongSparseArray<SharedLibraryInfo> versionedLib = newLibraries.get(name);
10152             SharedLibraryInfo info = null;
10153             if (versionedLib != null) {
10154                 info = versionedLib.get(version);
10155             }
10156             if (info != null) {
10157                 return info;
10158             }
10159         }
10160         final LongSparseArray<SharedLibraryInfo> versionedLib = existingLibraries.get(name);
10161         if (versionedLib == null) {
10162             return null;
10163         }
10164         return versionedLib.get(version);
10165     }
10166
10167     private SharedLibraryInfo getLatestSharedLibraVersionLPr(PackageParser.Package pkg) {
10168         LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.get(
10169                 pkg.staticSharedLibName);
10170         if (versionedLib == null) {
10171             return null;
10172         }
10173         long previousLibVersion = -1;
10174         final int versionCount = versionedLib.size();
10175         for (int i = 0; i < versionCount; i++) {
10176             final long libVersion = versionedLib.keyAt(i);
10177             if (libVersion < pkg.staticSharedLibVersion) {
10178                 previousLibVersion = Math.max(previousLibVersion, libVersion);
10179             }
10180         }
10181         if (previousLibVersion >= 0) {
10182             return versionedLib.get(previousLibVersion);
10183         }
10184         return null;
10185     }
10186
10187
10188     @Nullable
10189     private PackageSetting getSharedLibLatestVersionSetting(@NonNull ScanResult scanResult) {
10190         PackageSetting sharedLibPackage = null;
10191         synchronized (mPackages) {
10192             final SharedLibraryInfo latestSharedLibraVersionLPr =
10193                     getLatestSharedLibraVersionLPr(scanResult.pkgSetting.pkg);
10194             if (latestSharedLibraVersionLPr != null) {
10195                 sharedLibPackage = mSettings.getPackageLPr(
10196                         latestSharedLibraVersionLPr.getPackageName());
10197             }
10198         }
10199         return sharedLibPackage;
10200     }
10201
10202     public void shutdown() {
10203         mPackageUsage.writeNow(mPackages);
10204         mCompilerStats.writeNow();
10205         mDexManager.writePackageDexUsageNow();
10206         PackageWatchdog.getInstance(mContext).writeNow();
10207
10208         // This is the last chance to write out pending restriction settings
10209         synchronized (mPackages) {
10210             if (mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
10211                 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
10212                 for (int userId : mDirtyUsers) {
10213                     mSettings.writePackageRestrictionsLPr(userId);
10214                 }
10215                 mDirtyUsers.clear();
10216             }
10217         }
10218     }
10219
10220     @Override
10221     public void dumpProfiles(String packageName) {
10222         PackageParser.Package pkg;
10223         synchronized (mPackages) {
10224             pkg = mPackages.get(packageName);
10225             if (pkg == null) {
10226                 throw new IllegalArgumentException("Unknown package: " + packageName);
10227             }
10228         }
10229         /* Only the shell, root, or the app user should be able to dump profiles. */
10230         int callingUid = Binder.getCallingUid();
10231         if (callingUid != Process.SHELL_UID &&
10232             callingUid != Process.ROOT_UID &&
10233             callingUid != pkg.applicationInfo.uid) {
10234             throw new SecurityException("dumpProfiles");
10235         }
10236
10237         synchronized (mInstallLock) {
10238             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles");
10239             mArtManagerService.dumpProfiles(pkg);
10240             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10241         }
10242     }
10243
10244     @Override
10245     public void forceDexOpt(String packageName) {
10246         enforceSystemOrRoot("forceDexOpt");
10247
10248         PackageParser.Package pkg;
10249         synchronized (mPackages) {
10250             pkg = mPackages.get(packageName);
10251             if (pkg == null) {
10252                 throw new IllegalArgumentException("Unknown package: " + packageName);
10253             }
10254         }
10255
10256         synchronized (mInstallLock) {
10257             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
10258
10259             // Whoever is calling forceDexOpt wants a compiled package.
10260             // Don't use profiles since that may cause compilation to be skipped.
10261             final int res = performDexOptInternalWithDependenciesLI(
10262                     pkg,
10263                     new DexoptOptions(packageName,
10264                             getDefaultCompilerFilter(),
10265                             DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE));
10266
10267             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10268             if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
10269                 throw new IllegalStateException("Failed to dexopt: " + res);
10270             }
10271         }
10272     }
10273
10274     @GuardedBy("mPackages")
10275     private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
10276         if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
10277             Slog.w(TAG, "Unable to update from " + oldPkg.name
10278                     + " to " + newPkg.packageName
10279                     + ": old package not in system partition");
10280             return false;
10281         } else if (mPackages.get(oldPkg.name) != null) {
10282             Slog.w(TAG, "Unable to update from " + oldPkg.name
10283                     + " to " + newPkg.packageName
10284                     + ": old package still exists");
10285             return false;
10286         }
10287         return true;
10288     }
10289
10290     @GuardedBy("mInstallLock")
10291     void removeCodePathLI(File codePath) {
10292         if (codePath.isDirectory()) {
10293             try {
10294                 mInstaller.rmPackageDir(codePath.getAbsolutePath());
10295             } catch (InstallerException e) {
10296                 Slog.w(TAG, "Failed to remove code path", e);
10297             }
10298         } else {
10299             codePath.delete();
10300         }
10301     }
10302
10303     private int[] resolveUserIds(int userId) {
10304         return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId };
10305     }
10306
10307     private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10308         if (pkg == null) {
10309             Slog.wtf(TAG, "Package was null!", new Throwable());
10310             return;
10311         }
10312         clearAppDataLeafLIF(pkg, userId, flags);
10313         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10314         for (int i = 0; i < childCount; i++) {
10315             clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10316         }
10317
10318         clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
10319     }
10320
10321     private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10322         final PackageSetting ps;
10323         synchronized (mPackages) {
10324             ps = mSettings.mPackages.get(pkg.packageName);
10325         }
10326         for (int realUserId : resolveUserIds(userId)) {
10327             final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10328             try {
10329                 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10330                         ceDataInode);
10331             } catch (InstallerException e) {
10332                 Slog.w(TAG, String.valueOf(e));
10333             }
10334         }
10335     }
10336
10337     private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
10338         if (pkg == null) {
10339             Slog.wtf(TAG, "Package was null!", new Throwable());
10340             return;
10341         }
10342         destroyAppDataLeafLIF(pkg, userId, flags);
10343         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10344         for (int i = 0; i < childCount; i++) {
10345             destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
10346         }
10347     }
10348
10349     private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
10350         final PackageSetting ps;
10351         synchronized (mPackages) {
10352             ps = mSettings.mPackages.get(pkg.packageName);
10353         }
10354         for (int realUserId : resolveUserIds(userId)) {
10355             final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0;
10356             try {
10357                 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags,
10358                         ceDataInode);
10359             } catch (InstallerException e) {
10360                 Slog.w(TAG, String.valueOf(e));
10361             }
10362             mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId);
10363         }
10364     }
10365
10366     private void destroyAppProfilesLIF(PackageParser.Package pkg) {
10367         if (pkg == null) {
10368             Slog.wtf(TAG, "Package was null!", new Throwable());
10369             return;
10370         }
10371         destroyAppProfilesLeafLIF(pkg);
10372         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10373         for (int i = 0; i < childCount; i++) {
10374             destroyAppProfilesLeafLIF(pkg.childPackages.get(i));
10375         }
10376     }
10377
10378     private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) {
10379         try {
10380             mInstaller.destroyAppProfiles(pkg.packageName);
10381         } catch (InstallerException e) {
10382             Slog.w(TAG, String.valueOf(e));
10383         }
10384     }
10385
10386     private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) {
10387         if (pkg == null) {
10388             Slog.wtf(TAG, "Package was null!", new Throwable());
10389             return;
10390         }
10391         mArtManagerService.clearAppProfiles(pkg);
10392         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10393         for (int i = 0; i < childCount; i++) {
10394             mArtManagerService.clearAppProfiles(pkg.childPackages.get(i));
10395         }
10396     }
10397
10398     private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime,
10399             long lastUpdateTime) {
10400         // Set parent install/update time
10401         PackageSetting ps = (PackageSetting) pkg.mExtras;
10402         if (ps != null) {
10403             ps.firstInstallTime = firstInstallTime;
10404             ps.lastUpdateTime = lastUpdateTime;
10405         }
10406         // Set children install/update time
10407         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10408         for (int i = 0; i < childCount; i++) {
10409             PackageParser.Package childPkg = pkg.childPackages.get(i);
10410             ps = (PackageSetting) childPkg.mExtras;
10411             if (ps != null) {
10412                 ps.firstInstallTime = firstInstallTime;
10413                 ps.lastUpdateTime = lastUpdateTime;
10414             }
10415         }
10416     }
10417
10418     @GuardedBy("mPackages")
10419     private void applyDefiningSharedLibraryUpdateLocked(
10420             PackageParser.Package pkg, SharedLibraryInfo libInfo,
10421             BiConsumer<SharedLibraryInfo, SharedLibraryInfo> action) {
10422         // Note that libraries defined by this package may be null if:
10423         // - Package manager was unable to create the shared library. The package still
10424         //   gets installed, but the shared library does not get created.
10425         // Or:
10426         // - Package manager is in a state where package isn't scanned yet. This will
10427         //   get called again after scanning to fix the dependencies.
10428         if (pkg.isLibrary()) {
10429             if (pkg.staticSharedLibName != null) {
10430                 SharedLibraryInfo definedLibrary = getSharedLibraryInfoLPr(
10431                         pkg.staticSharedLibName, pkg.staticSharedLibVersion);
10432                 if (definedLibrary != null) {
10433                     action.accept(definedLibrary, libInfo);
10434                 }
10435             } else {
10436                 for (String libraryName : pkg.libraryNames) {
10437                     SharedLibraryInfo definedLibrary = getSharedLibraryInfoLPr(
10438                             libraryName, SharedLibraryInfo.VERSION_UNDEFINED);
10439                     if (definedLibrary != null) {
10440                         action.accept(definedLibrary, libInfo);
10441                     }
10442                 }
10443             }
10444         }
10445     }
10446
10447     @GuardedBy("mPackages")
10448     private void addSharedLibraryLPr(PackageParser.Package pkg, Set<String> usesLibraryFiles,
10449             SharedLibraryInfo libInfo, PackageParser.Package changingLib) {
10450         if (libInfo.getPath() != null) {
10451             usesLibraryFiles.add(libInfo.getPath());
10452             return;
10453         }
10454         PackageParser.Package p = mPackages.get(libInfo.getPackageName());
10455         if (changingLib != null && changingLib.packageName.equals(libInfo.getPackageName())) {
10456             // If we are doing this while in the middle of updating a library apk,
10457             // then we need to make sure to use that new apk for determining the
10458             // dependencies here.  (We haven't yet finished committing the new apk
10459             // to the package manager state.)
10460             if (p == null || p.packageName.equals(changingLib.packageName)) {
10461                 p = changingLib;
10462             }
10463         }
10464         if (p != null) {
10465             usesLibraryFiles.addAll(p.getAllCodePaths());
10466             // If the package provides libraries, add the dependency to them.
10467             applyDefiningSharedLibraryUpdateLocked(pkg, libInfo, (definingLibrary, dependency) -> {
10468                 definingLibrary.addDependency(dependency);
10469             });
10470             if (p.usesLibraryFiles != null) {
10471                 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles);
10472             }
10473         }
10474     }
10475
10476     @GuardedBy("mPackages")
10477     private void updateSharedLibrariesLocked(PackageParser.Package pkg,
10478             PackageParser.Package changingLib, Map<String, PackageParser.Package> availablePackages)
10479                     throws PackageManagerException {
10480         final ArrayList<SharedLibraryInfo> sharedLibraryInfos =
10481                 collectSharedLibraryInfos(pkg, availablePackages, mSharedLibraries, null);
10482         executeSharedLibrariesUpdateLPr(pkg, changingLib, sharedLibraryInfos);
10483     }
10484
10485     private static ArrayList<SharedLibraryInfo> collectSharedLibraryInfos(PackageParser.Package pkg,
10486             Map<String, PackageParser.Package> availablePackages,
10487             @NonNull final Map<String, LongSparseArray<SharedLibraryInfo>> existingLibraries,
10488             @Nullable final Map<String, LongSparseArray<SharedLibraryInfo>> newLibraries)
10489             throws PackageManagerException {
10490         if (pkg == null) {
10491             return null;
10492         }
10493         // The collection used here must maintain the order of addition (so
10494         // that libraries are searched in the correct order) and must have no
10495         // duplicates.
10496         ArrayList<SharedLibraryInfo> usesLibraryInfos = null;
10497         if (pkg.usesLibraries != null) {
10498             usesLibraryInfos = collectSharedLibraryInfos(pkg.usesLibraries, null, null,
10499                     pkg.packageName, true, pkg.applicationInfo.targetSdkVersion, null,
10500                     availablePackages, existingLibraries, newLibraries);
10501         }
10502         if (pkg.usesStaticLibraries != null) {
10503             usesLibraryInfos = collectSharedLibraryInfos(pkg.usesStaticLibraries,
10504                     pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests,
10505                     pkg.packageName, true, pkg.applicationInfo.targetSdkVersion, usesLibraryInfos,
10506                     availablePackages, existingLibraries, newLibraries);
10507         }
10508         if (pkg.usesOptionalLibraries != null) {
10509             usesLibraryInfos = collectSharedLibraryInfos(pkg.usesOptionalLibraries,
10510                     null, null, pkg.packageName, false, pkg.applicationInfo.targetSdkVersion,
10511                     usesLibraryInfos, availablePackages, existingLibraries, newLibraries);
10512         }
10513         return usesLibraryInfos;
10514     }
10515
10516     private void executeSharedLibrariesUpdateLPr(PackageParser.Package pkg,
10517             PackageParser.Package changingLib, ArrayList<SharedLibraryInfo> usesLibraryInfos) {
10518         // If the package provides libraries, clear their old dependencies.
10519         // This method will set them up again.
10520         applyDefiningSharedLibraryUpdateLocked(pkg, null, (definingLibrary, dependency) -> {
10521             definingLibrary.clearDependencies();
10522         });
10523         if (usesLibraryInfos != null) {
10524             pkg.usesLibraryInfos = usesLibraryInfos;
10525             // Use LinkedHashSet to preserve the order of files added to
10526             // usesLibraryFiles while eliminating duplicates.
10527             Set<String> usesLibraryFiles = new LinkedHashSet<>();
10528             for (SharedLibraryInfo libInfo : usesLibraryInfos) {
10529                 addSharedLibraryLPr(pkg, usesLibraryFiles, libInfo, changingLib);
10530             }
10531             pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]);
10532         } else {
10533             pkg.usesLibraryInfos = null;
10534             pkg.usesLibraryFiles = null;
10535         }
10536     }
10537
10538     @GuardedBy("mPackages")
10539     private static ArrayList<SharedLibraryInfo> collectSharedLibraryInfos(
10540             @NonNull List<String> requestedLibraries,
10541             @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests,
10542             @NonNull String packageName, boolean required, int targetSdk,
10543             @Nullable ArrayList<SharedLibraryInfo> outUsedLibraries,
10544             @NonNull final Map<String, PackageParser.Package> availablePackages,
10545             @NonNull final Map<String, LongSparseArray<SharedLibraryInfo>> existingLibraries,
10546             @Nullable final Map<String, LongSparseArray<SharedLibraryInfo>> newLibraries)
10547             throws PackageManagerException {
10548         final int libCount = requestedLibraries.size();
10549         for (int i = 0; i < libCount; i++) {
10550             final String libName = requestedLibraries.get(i);
10551             final long libVersion = requiredVersions != null ? requiredVersions[i]
10552                     : SharedLibraryInfo.VERSION_UNDEFINED;
10553             final SharedLibraryInfo libraryInfo = getSharedLibraryInfo(libName, libVersion,
10554                     existingLibraries, newLibraries);
10555             if (libraryInfo == null) {
10556                 if (required) {
10557                     throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10558                             "Package " + packageName + " requires unavailable shared library "
10559                                     + libName + "; failing!");
10560                 } else if (DEBUG_SHARED_LIBRARIES) {
10561                     Slog.i(TAG, "Package " + packageName
10562                             + " desires unavailable shared library "
10563                             + libName + "; ignoring!");
10564                 }
10565             } else {
10566                 if (requiredVersions != null && requiredCertDigests != null) {
10567                     if (libraryInfo.getLongVersion() != requiredVersions[i]) {
10568                         throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10569                             "Package " + packageName + " requires unavailable static shared"
10570                                     + " library " + libName + " version "
10571                                     + libraryInfo.getLongVersion() + "; failing!");
10572                     }
10573                     PackageParser.Package libPkg =
10574                             availablePackages.get(libraryInfo.getPackageName());
10575                     if (libPkg == null) {
10576                         throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10577                                 "Package " + packageName + " requires unavailable static shared"
10578                                         + " library; failing!");
10579                     }
10580                     final String[] expectedCertDigests = requiredCertDigests[i];
10581                     if (expectedCertDigests.length > 1) {
10582                         // For apps targeting O MR1 we require explicit enumeration of all certs.
10583                         final String[] libCertDigests = (targetSdk >= Build.VERSION_CODES.O_MR1)
10584                                 ? PackageUtils.computeSignaturesSha256Digests(
10585                                 libPkg.mSigningDetails.signatures)
10586                                 : PackageUtils.computeSignaturesSha256Digests(
10587                                         new Signature[]{libPkg.mSigningDetails.signatures[0]});
10588
10589                         // Take a shortcut if sizes don't match. Note that if an app doesn't
10590                         // target O we don't parse the "additional-certificate" tags similarly
10591                         // how we only consider all certs only for apps targeting O (see above).
10592                         // Therefore, the size check is safe to make.
10593                         if (expectedCertDigests.length != libCertDigests.length) {
10594                             throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10595                                     "Package " + packageName + " requires differently signed" +
10596                                             " static shared library; failing!");
10597                         }
10598
10599                         // Use a predictable order as signature order may vary
10600                         Arrays.sort(libCertDigests);
10601                         Arrays.sort(expectedCertDigests);
10602
10603                         final int certCount = libCertDigests.length;
10604                         for (int j = 0; j < certCount; j++) {
10605                             if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) {
10606                                 throw new PackageManagerException(
10607                                         INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10608                                         "Package " + packageName + " requires differently signed" +
10609                                                 " static shared library; failing!");
10610                             }
10611                         }
10612                     } else {
10613                         // lib signing cert could have rotated beyond the one expected, check to see
10614                         // if the new one has been blessed by the old
10615                         if (!libPkg.mSigningDetails.hasSha256Certificate(
10616                                 ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) {
10617                             throw new PackageManagerException(
10618                                     INSTALL_FAILED_MISSING_SHARED_LIBRARY,
10619                                     "Package " + packageName + " requires differently signed" +
10620                                             " static shared library; failing!");
10621                         }
10622                     }
10623                 }
10624                 if (outUsedLibraries == null) {
10625                     outUsedLibraries = new ArrayList<>();
10626                 }
10627                 outUsedLibraries.add(libraryInfo);
10628             }
10629         }
10630         return outUsedLibraries;
10631     }
10632
10633     private static boolean hasString(List<String> list, List<String> which) {
10634         if (list == null || which == null) {
10635             return false;
10636         }
10637         for (int i=list.size()-1; i>=0; i--) {
10638             for (int j=which.size()-1; j>=0; j--) {
10639                 if (which.get(j).equals(list.get(i))) {
10640                     return true;
10641                 }
10642             }
10643         }
10644         return false;
10645     }
10646
10647     @GuardedBy("mPackages")
10648     private ArrayList<PackageParser.Package> updateAllSharedLibrariesLocked(
10649             PackageParser.Package updatedPkg,
10650             Map<String, PackageParser.Package> availablePackages) {
10651         ArrayList<PackageParser.Package> resultList = null;
10652         // Set of all descendants of a library; used to eliminate cycles
10653         ArraySet<String> descendants = null;
10654         // The current list of packages that need updating
10655         ArrayList<PackageParser.Package> needsUpdating = null;
10656         if (updatedPkg != null) {
10657             needsUpdating = new ArrayList<>(1);
10658             needsUpdating.add(updatedPkg);
10659         }
10660         do {
10661             final PackageParser.Package changingPkg =
10662                     (needsUpdating == null) ? null : needsUpdating.remove(0);
10663             for (int i = mPackages.size() - 1; i >= 0; --i) {
10664                 final PackageParser.Package pkg = mPackages.valueAt(i);
10665                 if (changingPkg != null
10666                         && !hasString(pkg.usesLibraries, changingPkg.libraryNames)
10667                         && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)
10668                         && !ArrayUtils.contains(pkg.usesStaticLibraries,
10669                                 changingPkg.staticSharedLibName)) {
10670                     continue;
10671                 }
10672                 if (resultList == null) {
10673                     resultList = new ArrayList<>();
10674                 }
10675                 resultList.add(pkg);
10676                 // if we're updating a shared library, all of its descendants must be updated
10677                 if (changingPkg != null) {
10678                     if (descendants == null) {
10679                         descendants = new ArraySet<>();
10680                     }
10681                     if (!descendants.contains(pkg.packageName)) {
10682                         descendants.add(pkg.packageName);
10683                         needsUpdating.add(pkg);
10684                     }
10685                 }
10686                 try {
10687                     updateSharedLibrariesLocked(pkg, changingPkg, availablePackages);
10688                 } catch (PackageManagerException e) {
10689                     // If a system app update or an app and a required lib missing we
10690                     // delete the package and for updated system apps keep the data as
10691                     // it is better for the user to reinstall than to be in an limbo
10692                     // state. Also libs disappearing under an app should never happen
10693                     // - just in case.
10694                     if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) {
10695                         final int flags = pkg.isUpdatedSystemApp()
10696                                 ? PackageManager.DELETE_KEEP_DATA : 0;
10697                         deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(),
10698                                 flags , null, true, null);
10699                     }
10700                     Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
10701                 }
10702             }
10703         } while (needsUpdating != null && needsUpdating.size() > 0);
10704         return resultList;
10705     }
10706
10707     @GuardedBy({"mInstallLock", "mPackages"})
10708     private List<ScanResult> scanPackageTracedLI(PackageParser.Package pkg,
10709             final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10710             @Nullable UserHandle user) throws PackageManagerException {
10711         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage");
10712         // If the package has children and this is the first dive in the function
10713         // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see
10714         // whether all packages (parent and children) would be successfully scanned
10715         // before the actual scan since scanning mutates internal state and we want
10716         // to atomically install the package and its children.
10717         if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
10718             if (pkg.childPackages != null && pkg.childPackages.size() > 0) {
10719                 scanFlags |= SCAN_CHECK_ONLY;
10720             }
10721         } else {
10722             scanFlags &= ~SCAN_CHECK_ONLY;
10723         }
10724
10725         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
10726         final List<ScanResult> scanResults = new ArrayList<>(1 + childCount);
10727         try {
10728             // Scan the parent
10729             scanResults.add(scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user));
10730             // Scan the children
10731             for (int i = 0; i < childCount; i++) {
10732                 PackageParser.Package childPkg = pkg.childPackages.get(i);
10733                 scanResults.add(scanPackageNewLI(childPkg, parseFlags,
10734                         scanFlags, currentTime, user));
10735             }
10736         } finally {
10737             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
10738         }
10739
10740         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
10741             return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user);
10742         }
10743
10744         return scanResults;
10745     }
10746
10747     /** The result of a package scan. */
10748     private static class ScanResult {
10749         /** The request that initiated the scan that produced this result. */
10750         public final ScanRequest request;
10751         /** Whether or not the package scan was successful */
10752         public final boolean success;
10753         /**
10754          * Whether or not the original PackageSetting needs to be updated with this result on
10755          * commit.
10756          */
10757         public final boolean existingSettingCopied;
10758         /**
10759          * The final package settings. This may be the same object passed in
10760          * the {@link ScanRequest}, but, with modified values.
10761          */
10762         @Nullable public final PackageSetting pkgSetting;
10763         /** ABI code paths that have changed in the package scan */
10764         @Nullable public final List<String> changedAbiCodePath;
10765
10766         public final SharedLibraryInfo staticSharedLibraryInfo;
10767
10768         public final List<SharedLibraryInfo> dynamicSharedLibraryInfos;
10769
10770         public ScanResult(
10771                 ScanRequest request, boolean success,
10772                 @Nullable PackageSetting pkgSetting,
10773                 @Nullable List<String> changedAbiCodePath, boolean existingSettingCopied,
10774                 SharedLibraryInfo staticSharedLibraryInfo,
10775                 List<SharedLibraryInfo> dynamicSharedLibraryInfos) {
10776             this.request = request;
10777             this.success = success;
10778             this.pkgSetting = pkgSetting;
10779             this.changedAbiCodePath = changedAbiCodePath;
10780             this.existingSettingCopied = existingSettingCopied;
10781             this.staticSharedLibraryInfo = staticSharedLibraryInfo;
10782             this.dynamicSharedLibraryInfos = dynamicSharedLibraryInfos;
10783         }
10784     }
10785
10786     /** A package to be scanned */
10787     private static class ScanRequest {
10788         /** The parsed package */
10789         @NonNull public final PackageParser.Package pkg;
10790         /** The package this package replaces */
10791         @Nullable public final PackageParser.Package oldPkg;
10792         /** Shared user settings, if the package has a shared user */
10793         @Nullable public final SharedUserSetting sharedUserSetting;
10794         /**
10795          * Package settings of the currently installed version.
10796          * <p><em>IMPORTANT:</em> The contents of this object may be modified
10797          * during scan.
10798          */
10799         @Nullable public final PackageSetting pkgSetting;
10800         /** A copy of the settings for the currently installed version */
10801         @Nullable public final PackageSetting oldPkgSetting;
10802         /** Package settings for the disabled version on the /system partition */
10803         @Nullable public final PackageSetting disabledPkgSetting;
10804         /** Package settings for the installed version under its original package name */
10805         @Nullable public final PackageSetting originalPkgSetting;
10806         /** The real package name of a renamed application */
10807         @Nullable public final String realPkgName;
10808         public final @ParseFlags int parseFlags;
10809         public final @ScanFlags int scanFlags;
10810         /** The user for which the package is being scanned */
10811         @Nullable public final UserHandle user;
10812         /** Whether or not the platform package is being scanned */
10813         public final boolean isPlatformPackage;
10814         public ScanRequest(
10815                 @NonNull PackageParser.Package pkg,
10816                 @Nullable SharedUserSetting sharedUserSetting,
10817                 @Nullable PackageParser.Package oldPkg,
10818                 @Nullable PackageSetting pkgSetting,
10819                 @Nullable PackageSetting disabledPkgSetting,
10820                 @Nullable PackageSetting originalPkgSetting,
10821                 @Nullable String realPkgName,
10822                 @ParseFlags int parseFlags,
10823                 @ScanFlags int scanFlags,
10824                 boolean isPlatformPackage,
10825                 @Nullable UserHandle user) {
10826             this.pkg = pkg;
10827             this.oldPkg = oldPkg;
10828             this.pkgSetting = pkgSetting;
10829             this.sharedUserSetting = sharedUserSetting;
10830             this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting);
10831             this.disabledPkgSetting = disabledPkgSetting;
10832             this.originalPkgSetting = originalPkgSetting;
10833             this.realPkgName = realPkgName;
10834             this.parseFlags = parseFlags;
10835             this.scanFlags = scanFlags;
10836             this.isPlatformPackage = isPlatformPackage;
10837             this.user = user;
10838         }
10839     }
10840
10841     /**
10842      * Returns the actual scan flags depending upon the state of the other settings.
10843      * <p>Updated system applications will not have the following flags set
10844      * by default and need to be adjusted after the fact:
10845      * <ul>
10846      * <li>{@link #SCAN_AS_SYSTEM}</li>
10847      * <li>{@link #SCAN_AS_PRIVILEGED}</li>
10848      * <li>{@link #SCAN_AS_OEM}</li>
10849      * <li>{@link #SCAN_AS_VENDOR}</li>
10850      * <li>{@link #SCAN_AS_PRODUCT}</li>
10851      * <li>{@link #SCAN_AS_PRODUCT_SERVICES}</li>
10852      * <li>{@link #SCAN_AS_INSTANT_APP}</li>
10853      * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li>
10854      * <li>{@link #SCAN_AS_ODM}</li>
10855      * </ul>
10856      */
10857     private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags,
10858             PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user,
10859             PackageParser.Package pkg) {
10860
10861         // TODO(patb): Do away entirely with disabledPkgSetting here. PkgSetting will always contain
10862         // the correct isSystem value now that we don't disable system packages before scan.
10863         final PackageSetting systemPkgSetting =
10864                 (scanFlags & SCAN_NEW_INSTALL) != 0 && disabledPkgSetting == null
10865                         && pkgSetting != null && pkgSetting.isSystem()
10866                         ? pkgSetting
10867                         : disabledPkgSetting;
10868         if (systemPkgSetting != null)  {
10869             // updated system application, must at least have SCAN_AS_SYSTEM
10870             scanFlags |= SCAN_AS_SYSTEM;
10871             if ((systemPkgSetting.pkgPrivateFlags
10872                     & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
10873                 scanFlags |= SCAN_AS_PRIVILEGED;
10874             }
10875             if ((systemPkgSetting.pkgPrivateFlags
10876                     & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) {
10877                 scanFlags |= SCAN_AS_OEM;
10878             }
10879             if ((systemPkgSetting.pkgPrivateFlags
10880                     & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) {
10881                 scanFlags |= SCAN_AS_VENDOR;
10882             }
10883             if ((systemPkgSetting.pkgPrivateFlags
10884                     & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) {
10885                 scanFlags |= SCAN_AS_PRODUCT;
10886             }
10887             if ((systemPkgSetting.pkgPrivateFlags
10888                     & ApplicationInfo.PRIVATE_FLAG_PRODUCT_SERVICES) != 0) {
10889                 scanFlags |= SCAN_AS_PRODUCT_SERVICES;
10890             }
10891             if ((systemPkgSetting.pkgPrivateFlags
10892                     & ApplicationInfo.PRIVATE_FLAG_ODM) != 0) {
10893                 scanFlags |= SCAN_AS_ODM;
10894             }
10895         }
10896         if (pkgSetting != null) {
10897             final int userId = ((user == null) ? 0 : user.getIdentifier());
10898             if (pkgSetting.getInstantApp(userId)) {
10899                 scanFlags |= SCAN_AS_INSTANT_APP;
10900             }
10901             if (pkgSetting.getVirtulalPreload(userId)) {
10902                 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
10903             }
10904         }
10905
10906         // Scan as privileged apps that share a user with a priv-app.
10907         final boolean skipVendorPrivilegeScan = ((scanFlags & SCAN_AS_VENDOR) != 0)
10908                 && SystemProperties.getInt("ro.vndk.version", 28) < 28;
10909         if (((scanFlags & SCAN_AS_PRIVILEGED) == 0)
10910                 && !pkg.isPrivileged()
10911                 && (pkg.mSharedUserId != null)
10912                 && !skipVendorPrivilegeScan) {
10913             SharedUserSetting sharedUserSetting = null;
10914             try {
10915                 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
10916             } catch (PackageManagerException ignore) {}
10917             if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
10918                 // Exempt SharedUsers signed with the platform key.
10919                 // TODO(b/72378145) Fix this exemption. Force signature apps
10920                 // to whitelist their privileged permissions just like other
10921                 // priv-apps.
10922                 synchronized (mPackages) {
10923                     PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
10924                     if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures,
10925                                 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) {
10926                         scanFlags |= SCAN_AS_PRIVILEGED;
10927                     }
10928                 }
10929             }
10930         }
10931
10932         return scanFlags;
10933     }
10934
10935     // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting
10936     // the results / removing app data needs to be moved up a level to the callers of this
10937     // method. Also, we need to solve the problem of potentially creating a new shared user
10938     // setting. That can probably be done later and patch things up after the fact.
10939     @GuardedBy({"mInstallLock", "mPackages"})
10940     private ScanResult scanPackageNewLI(@NonNull PackageParser.Package pkg,
10941             final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,
10942             @Nullable UserHandle user) throws PackageManagerException {
10943
10944         final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage);
10945         final String realPkgName = getRealPackageName(pkg, renamedPkgName);
10946         if (realPkgName != null) {
10947             ensurePackageRenamed(pkg, renamedPkgName);
10948         }
10949         final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName);
10950         final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName);
10951         final PackageSetting disabledPkgSetting =
10952                 mSettings.getDisabledSystemPkgLPr(pkg.packageName);
10953
10954         if (mTransferedPackages.contains(pkg.packageName)) {
10955             Slog.w(TAG, "Package " + pkg.packageName
10956                     + " was transferred to another, but its .apk remains");
10957         }
10958
10959         scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg);
10960         synchronized (mPackages) {
10961             applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage);
10962             assertPackageIsValid(pkg, parseFlags, scanFlags);
10963
10964             SharedUserSetting sharedUserSetting = null;
10965             if (pkg.mSharedUserId != null) {
10966                 // SIDE EFFECTS; may potentially allocate a new shared user
10967                 sharedUserSetting = mSettings.getSharedUserLPw(
10968                         pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/);
10969                 if (DEBUG_PACKAGE_SCANNING) {
10970                     if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
10971                         Log.d(TAG, "Shared UserID " + pkg.mSharedUserId
10972                                 + " (uid=" + sharedUserSetting.userId + "):"
10973                                 + " packages=" + sharedUserSetting.packages);
10974                 }
10975             }
10976             final ScanRequest request = new ScanRequest(pkg, sharedUserSetting,
10977                     pkgSetting == null ? null : pkgSetting.pkg, pkgSetting, disabledPkgSetting,
10978                     originalPkgSetting, realPkgName, parseFlags, scanFlags,
10979                     (pkg == mPlatformPackage), user);
10980             return scanPackageOnlyLI(request, mFactoryTest, currentTime);
10981         }
10982     }
10983
10984
10985     /**
10986      * Prepares the system to commit a {@link ScanResult} in a way that will not fail by registering
10987      * the app ID required for reconcile.
10988      * @return {@code true} if a new app ID was registered and will need to be cleaned up on
10989      *         failure.
10990      */
10991     private boolean optimisticallyRegisterAppId(@NonNull ScanResult result)
10992             throws PackageManagerException {
10993         if (!result.existingSettingCopied) {
10994             // THROWS: when we can't allocate a user id. add call to check if there's
10995             // enough space to ensure we won't throw; otherwise, don't modify state
10996             return mSettings.registerAppIdLPw(result.pkgSetting);
10997         }
10998         return false;
10999     }
11000
11001     /**
11002      * Reverts any app ID creation that were made by
11003      * {@link #optimisticallyRegisterAppId(ScanResult)}. Note: this is only necessary if the
11004      * referenced method returned true.
11005      */
11006     private void cleanUpAppIdCreation(@NonNull ScanResult result) {
11007         // iff we've acquired an app ID for a new package setting, remove it so that it can be
11008         // acquired by another request.
11009         if (result.pkgSetting.appId > 0) {
11010             mSettings.removeAppIdLPw(result.pkgSetting.appId);
11011         }
11012     }
11013
11014     /**
11015      * Commits the package scan and modifies system state.
11016      * <p><em>WARNING:</em> The method may throw an excpetion in the middle
11017      * of committing the package, leaving the system in an inconsistent state.
11018      * This needs to be fixed so, once we get to this point, no errors are
11019      * possible and the system is not left in an inconsistent state.
11020      */
11021     @GuardedBy({"mPackages", "mInstallLock"})
11022     private void commitReconciledScanResultLocked(@NonNull ReconciledPackage reconciledPkg) {
11023         final ScanResult result = reconciledPkg.scanResult;
11024         final ScanRequest request = result.request;
11025         final PackageParser.Package pkg = request.pkg;
11026         final PackageParser.Package oldPkg = request.oldPkg;
11027         final @ParseFlags int parseFlags = request.parseFlags;
11028         final @ScanFlags int scanFlags = request.scanFlags;
11029         final PackageSetting oldPkgSetting = request.oldPkgSetting;
11030         final PackageSetting originalPkgSetting = request.originalPkgSetting;
11031         final UserHandle user = request.user;
11032         final String realPkgName = request.realPkgName;
11033         final List<String> changedAbiCodePath = result.changedAbiCodePath;
11034         final PackageSetting pkgSetting;
11035         if (request.pkgSetting != null && request.pkgSetting.sharedUser != null
11036                 && request.pkgSetting.sharedUser != result.pkgSetting.sharedUser) {
11037             // shared user changed, remove from old shared user
11038             request.pkgSetting.sharedUser.removePackage(request.pkgSetting);
11039         }
11040         if (result.existingSettingCopied) {
11041             pkgSetting = request.pkgSetting;
11042             pkgSetting.updateFrom(result.pkgSetting);
11043             pkg.mExtras = pkgSetting;
11044         } else {
11045             pkgSetting = result.pkgSetting;
11046             if (originalPkgSetting != null) {
11047                 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name);
11048             }
11049             if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) {
11050                 mTransferedPackages.add(originalPkgSetting.name);
11051             }
11052         }
11053         if (pkgSetting.sharedUser != null) {
11054             pkgSetting.sharedUser.addPackage(pkgSetting);
11055         }
11056         // TODO(toddke): Consider a method specifically for modifying the Package object
11057         // post scan; or, moving this stuff out of the Package object since it has nothing
11058         // to do with the package on disk.
11059         // We need to have this here because addUserToSettingLPw() is sometimes responsible
11060         // for creating the application ID. If we did this earlier, we would be saving the
11061         // correct ID.
11062         pkg.applicationInfo.uid = pkgSetting.appId;
11063
11064         mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting);
11065
11066         if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) {
11067             mTransferedPackages.add(pkg.packageName);
11068         }
11069
11070         if (reconciledPkg.collectedSharedLibraryInfos != null) {
11071             executeSharedLibrariesUpdateLPr(pkg, null, reconciledPkg.collectedSharedLibraryInfos);
11072         }
11073
11074         final KeySetManagerService ksms = mSettings.mKeySetManagerService;
11075         if (reconciledPkg.removeAppKeySetData) {
11076             ksms.removeAppKeySetDataLPw(pkg.packageName);
11077         }
11078         if (reconciledPkg.sharedUserSignaturesChanged) {
11079             pkgSetting.sharedUser.signaturesChanged = Boolean.TRUE;
11080             pkgSetting.sharedUser.signatures.mSigningDetails = reconciledPkg.signingDetails;
11081         }
11082         pkgSetting.signatures.mSigningDetails = reconciledPkg.signingDetails;
11083
11084         if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) {
11085             // This package wants to adopt ownership of permissions from
11086             // another package.
11087             for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
11088                 final String origName = pkg.mAdoptPermissions.get(i);
11089                 final PackageSetting orig = mSettings.getPackageLPr(origName);
11090                 if (orig != null) {
11091                     if (verifyPackageUpdateLPr(orig, pkg)) {
11092                         Slog.i(TAG, "Adopting permissions from " + origName + " to "
11093                                 + pkg.packageName);
11094                         mSettings.mPermissions.transferPermissions(origName, pkg.packageName);
11095                     }
11096                 }
11097             }
11098         }
11099
11100         if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) {
11101             for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) {
11102                 final String codePathString = changedAbiCodePath.get(i);
11103                 try {
11104                     mInstaller.rmdex(codePathString,
11105                             getDexCodeInstructionSet(getPreferredInstructionSet()));
11106                 } catch (InstallerException ignored) {
11107                 }
11108             }
11109         }
11110
11111         if ((scanFlags & SCAN_CHECK_ONLY) != 0) {
11112             if (oldPkgSetting != null) {
11113                 synchronized (mPackages) {
11114                     mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting);
11115                 }
11116             }
11117         } else {
11118             final int userId = user == null ? 0 : user.getIdentifier();
11119             // Modify state for the given package setting
11120             commitPackageSettings(pkg, oldPkg, pkgSetting, scanFlags,
11121                     (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/, reconciledPkg);
11122             if (pkgSetting.getInstantApp(userId)) {
11123                 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId);
11124             }
11125         }
11126     }
11127
11128     /**
11129      * Returns the "real" name of the package.
11130      * <p>This may differ from the package's actual name if the application has already
11131      * been installed under one of this package's original names.
11132      */
11133     private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg,
11134             @Nullable String renamedPkgName) {
11135         if (isPackageRenamed(pkg, renamedPkgName)) {
11136             return pkg.mRealPackage;
11137         }
11138         return null;
11139     }
11140
11141     /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */
11142     private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg,
11143             @Nullable String renamedPkgName) {
11144         return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName);
11145     }
11146
11147     /**
11148      * Returns the original package setting.
11149      * <p>A package can migrate its name during an update. In this scenario, a package
11150      * designates a set of names that it considers as one of its original names.
11151      * <p>An original package must be signed identically and it must have the same
11152      * shared user [if any].
11153      */
11154     @GuardedBy("mPackages")
11155     private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg,
11156             @Nullable String renamedPkgName) {
11157         if (!isPackageRenamed(pkg, renamedPkgName)) {
11158             return null;
11159         }
11160         for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) {
11161             final PackageSetting originalPs =
11162                     mSettings.getPackageLPr(pkg.mOriginalPackages.get(i));
11163             if (originalPs != null) {
11164                 // the package is already installed under its original name...
11165                 // but, should we use it?
11166                 if (!verifyPackageUpdateLPr(originalPs, pkg)) {
11167                     // the new package is incompatible with the original
11168                     continue;
11169                 } else if (originalPs.sharedUser != null) {
11170                     if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) {
11171                         // the shared user id is incompatible with the original
11172                         Slog.w(TAG, "Unable to migrate data from " + originalPs.name
11173                                 + " to " + pkg.packageName + ": old uid "
11174                                 + originalPs.sharedUser.name
11175                                 + " differs from " + pkg.mSharedUserId);
11176                         continue;
11177                     }
11178                     // TODO: Add case when shared user id is added [b/28144775]
11179                 } else {
11180                     if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
11181                             + pkg.packageName + " to old name " + originalPs.name);
11182                 }
11183                 return originalPs;
11184             }
11185         }
11186         return null;
11187     }
11188
11189     /**
11190      * Renames the package if it was installed under a different name.
11191      * <p>When we've already installed the package under an original name, update
11192      * the new package so we can continue to have the old name.
11193      */
11194     private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg,
11195             @NonNull String renamedPackageName) {
11196         if (pkg.mOriginalPackages == null
11197                 || !pkg.mOriginalPackages.contains(renamedPackageName)
11198                 || pkg.packageName.equals(renamedPackageName)) {
11199             return;
11200         }
11201         pkg.setPackageName(renamedPackageName);
11202     }
11203
11204     /**
11205      * Just scans the package without any side effects.
11206      * <p>Not entirely true at the moment. There is still one side effect -- this
11207      * method potentially modifies a live {@link PackageSetting} object representing
11208      * the package being scanned. This will be resolved in the future.
11209      *
11210      * @param request Information about the package to be scanned
11211      * @param isUnderFactoryTest Whether or not the device is under factory test
11212      * @param currentTime The current time, in millis
11213      * @return The results of the scan
11214      */
11215     @GuardedBy("mInstallLock")
11216     private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request,
11217             boolean isUnderFactoryTest, long currentTime)
11218                     throws PackageManagerException {
11219         final PackageParser.Package pkg = request.pkg;
11220         PackageSetting pkgSetting = request.pkgSetting;
11221         final PackageSetting disabledPkgSetting = request.disabledPkgSetting;
11222         final PackageSetting originalPkgSetting = request.originalPkgSetting;
11223         final @ParseFlags int parseFlags = request.parseFlags;
11224         final @ScanFlags int scanFlags = request.scanFlags;
11225         final String realPkgName = request.realPkgName;
11226         final SharedUserSetting sharedUserSetting = request.sharedUserSetting;
11227         final UserHandle user = request.user;
11228         final boolean isPlatformPackage = request.isPlatformPackage;
11229
11230         List<String> changedAbiCodePath = null;
11231
11232         if (DEBUG_PACKAGE_SCANNING) {
11233             if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
11234                 Log.d(TAG, "Scanning package " + pkg.packageName);
11235         }
11236
11237         // Initialize package source and resource directories
11238         final File scanFile = new File(pkg.codePath);
11239         final File destCodeFile = new File(pkg.applicationInfo.getCodePath());
11240         final File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
11241
11242         // We keep references to the derived CPU Abis from settings in oder to reuse
11243         // them in the case where we're not upgrading or booting for the first time.
11244         String primaryCpuAbiFromSettings = null;
11245         String secondaryCpuAbiFromSettings = null;
11246         boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
11247         if (!needToDeriveAbi) {
11248             if (pkgSetting != null) {
11249                 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString;
11250                 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString;
11251             } else {
11252                 // Re-scanning a system package after uninstalling updates; need to derive ABI
11253                 needToDeriveAbi = true;
11254             }
11255         }
11256
11257         if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) {
11258             PackageManagerService.reportSettingsProblem(Log.WARN,
11259                     "Package " + pkg.packageName + " shared user changed from "
11260                             + (pkgSetting.sharedUser != null
11261                             ? pkgSetting.sharedUser.name : "<nothing>")
11262                             + " to "
11263                             + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>")
11264                             + "; replacing with new");
11265             pkgSetting = null;
11266         }
11267
11268         String[] usesStaticLibraries = null;
11269         if (pkg.usesStaticLibraries != null) {
11270             usesStaticLibraries = new String[pkg.usesStaticLibraries.size()];
11271             pkg.usesStaticLibraries.toArray(usesStaticLibraries);
11272         }
11273         final boolean createNewPackage = (pkgSetting == null);
11274         if (createNewPackage) {
11275             final String parentPackageName = (pkg.parentPackage != null)
11276                     ? pkg.parentPackage.packageName : null;
11277             final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
11278             final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0;
11279             // REMOVE SharedUserSetting from method; update in a separate call
11280             pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting,
11281                     disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile,
11282                     destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
11283                     pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
11284                     pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
11285                     user, true /*allowInstall*/, instantApp, virtualPreload,
11286                     parentPackageName, pkg.getChildPackageNames(),
11287                     UserManagerService.getInstance(), usesStaticLibraries,
11288                     pkg.usesStaticLibrariesVersions);
11289         } else {
11290             // make a deep copy to avoid modifying any existing system state.
11291             pkgSetting = new PackageSetting(pkgSetting);
11292             pkgSetting.pkg = pkg;
11293
11294             // REMOVE SharedUserSetting from method; update in a separate call.
11295             //
11296             // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi,
11297             // secondaryCpuAbi are not known at this point so we always update them
11298             // to null here, only to reset them at a later point.
11299             Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting,
11300                     destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir,
11301                     pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
11302                     pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
11303                     pkg.getChildPackageNames(), UserManagerService.getInstance(),
11304                     usesStaticLibraries, pkg.usesStaticLibrariesVersions);
11305         }
11306         if (createNewPackage && originalPkgSetting != null) {
11307             // This is the initial transition from the original package, so,
11308             // fix up the new package's name now. We must do this after looking
11309             // up the package under its new name, so getPackageLP takes care of
11310             // fiddling things correctly.
11311             pkg.setPackageName(originalPkgSetting.name);
11312
11313             // File a report about this.
11314             String msg = "New package " + pkgSetting.realName
11315                     + " renamed to replace old package " + pkgSetting.name;
11316             reportSettingsProblem(Log.WARN, msg);
11317         }
11318
11319         final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier());
11320         // for existing packages, change the install state; but, only if it's explicitly specified
11321         if (!createNewPackage) {
11322             final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
11323             final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0;
11324             setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
11325         }
11326         // TODO(patb): see if we can do away with disabled check here.
11327         if (disabledPkgSetting != null
11328                 || (0 != (scanFlags & SCAN_NEW_INSTALL)
11329                 && pkgSetting != null && pkgSetting.isSystem())) {
11330             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11331         }
11332
11333         // Apps which share a sharedUserId must be placed in the same selinux domain. If this
11334         // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its
11335         // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be
11336         // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the
11337         // least restrictive selinux domain.
11338         // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion
11339         // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This
11340         // ensures that all packages continue to run in the same selinux domain.
11341         final int targetSdkVersion =
11342             ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ?
11343             sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion;
11344         // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync.
11345         // They currently can be if the sharedUser apps are signed with the platform key.
11346         final boolean isPrivileged = (sharedUserSetting != null) ?
11347             sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged();
11348
11349         pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged,
11350                 pkg.applicationInfo.targetSandboxVersion, targetSdkVersion);
11351         pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState(
11352                 userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId));
11353
11354         pkg.mExtras = pkgSetting;
11355         pkg.applicationInfo.processName = fixProcessName(
11356                 pkg.applicationInfo.packageName,
11357                 pkg.applicationInfo.processName);
11358
11359         if (!isPlatformPackage) {
11360             // Get all of our default paths setup
11361             pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM);
11362         }
11363
11364         final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
11365
11366         if ((scanFlags & SCAN_NEW_INSTALL) == 0) {
11367             if (needToDeriveAbi) {
11368                 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi");
11369                 final boolean extractNativeLibs = !pkg.isLibrary();
11370                 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs);
11371                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
11372
11373                 // Some system apps still use directory structure for native libraries
11374                 // in which case we might end up not detecting abi solely based on apk
11375                 // structure. Try to detect abi based on directory structure.
11376                 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() &&
11377                         pkg.applicationInfo.primaryCpuAbi == null) {
11378                     setBundledAppAbisAndRoots(pkg, pkgSetting);
11379                     setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11380                 }
11381             } else {
11382                 // This is not a first boot or an upgrade, don't bother deriving the
11383                 // ABI during the scan. Instead, trust the value that was stored in the
11384                 // package setting.
11385                 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings;
11386                 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings;
11387
11388                 setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11389
11390                 if (DEBUG_ABI_SELECTION) {
11391                     Slog.i(TAG, "Using ABIS and native lib paths from settings : " +
11392                             pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " +
11393                             pkg.applicationInfo.secondaryCpuAbi);
11394                 }
11395             }
11396         } else {
11397             if ((scanFlags & SCAN_MOVE) != 0) {
11398                 // We haven't run dex-opt for this move (since we've moved the compiled output too)
11399                 // but we already have this packages package info in the PackageSetting. We just
11400                 // use that and derive the native library path based on the new codepath.
11401                 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString;
11402                 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString;
11403             }
11404
11405             // Set native library paths again. For moves, the path will be updated based on the
11406             // ABIs we've determined above. For non-moves, the path will be updated based on the
11407             // ABIs we determined during compilation, but the path will depend on the final
11408             // package path (after the rename away from the stage path).
11409             setNativeLibraryPaths(pkg, sAppLib32InstallDir);
11410         }
11411
11412         // This is a special case for the "system" package, where the ABI is
11413         // dictated by the zygote configuration (and init.rc). We should keep track
11414         // of this ABI so that we can deal with "normal" applications that run under
11415         // the same UID correctly.
11416         if (isPlatformPackage) {
11417             pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
11418                     Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
11419         }
11420
11421         // If there's a mismatch between the abi-override in the package setting
11422         // and the abiOverride specified for the install. Warn about this because we
11423         // would've already compiled the app without taking the package setting into
11424         // account.
11425         if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) {
11426             if (cpuAbiOverride == null && pkg.packageName != null) {
11427                 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride +
11428                         " for package " + pkg.packageName);
11429             }
11430         }
11431
11432         pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
11433         pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
11434         pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
11435
11436         // Copy the derived override back to the parsed package, so that we can
11437         // update the package settings accordingly.
11438         pkg.cpuAbiOverride = cpuAbiOverride;
11439
11440         if (DEBUG_ABI_SELECTION) {
11441             Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName
11442                     + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
11443                     + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
11444         }
11445
11446         // Push the derived path down into PackageSettings so we know what to
11447         // clean up at uninstall time.
11448         pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
11449
11450         if (DEBUG_ABI_SELECTION) {
11451             Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
11452                     " primary=" + pkg.applicationInfo.primaryCpuAbi +
11453                     " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
11454         }
11455
11456         if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
11457             // We don't do this here during boot because we can do it all
11458             // at once after scanning all existing packages.
11459             //
11460             // We also do this *before* we perform dexopt on this package, so that
11461             // we can avoid redundant dexopts, and also to make sure we've got the
11462             // code and package path correct.
11463             changedAbiCodePath =
11464                     adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg);
11465         }
11466
11467         if (isUnderFactoryTest && pkg.requestedPermissions.contains(
11468                 android.Manifest.permission.FACTORY_TEST)) {
11469             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
11470         }
11471
11472         if (isSystemApp(pkg)) {
11473             pkgSetting.isOrphaned = true;
11474         }
11475
11476         // Take care of first install / last update times.
11477         final long scanFileTime = getLastModifiedTime(pkg);
11478         if (currentTime != 0) {
11479             if (pkgSetting.firstInstallTime == 0) {
11480                 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
11481             } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) {
11482                 pkgSetting.lastUpdateTime = currentTime;
11483             }
11484         } else if (pkgSetting.firstInstallTime == 0) {
11485             // We need *something*.  Take time time stamp of the file.
11486             pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
11487         } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
11488             if (scanFileTime != pkgSetting.timeStamp) {
11489                 // A package on the system image has changed; consider this
11490                 // to be an update.
11491                 pkgSetting.lastUpdateTime = scanFileTime;
11492             }
11493         }
11494         pkgSetting.setTimeStamp(scanFileTime);
11495
11496         pkgSetting.pkg = pkg;
11497         pkgSetting.pkgFlags = pkg.applicationInfo.flags;
11498         if (pkg.getLongVersionCode() != pkgSetting.versionCode) {
11499             pkgSetting.versionCode = pkg.getLongVersionCode();
11500         }
11501         // Update volume if needed
11502         final String volumeUuid = pkg.applicationInfo.volumeUuid;
11503         if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) {
11504             Slog.i(PackageManagerService.TAG,
11505                     "Update" + (pkgSetting.isSystem() ? " system" : "")
11506                     + " package " + pkg.packageName
11507                     + " volume from " + pkgSetting.volumeUuid
11508                     + " to " + volumeUuid);
11509             pkgSetting.volumeUuid = volumeUuid;
11510         }
11511
11512         SharedLibraryInfo staticSharedLibraryInfo = null;
11513         if (!TextUtils.isEmpty(pkg.staticSharedLibName)) {
11514             staticSharedLibraryInfo = SharedLibraryInfo.createForStatic(pkg);
11515         }
11516         List<SharedLibraryInfo> dynamicSharedLibraryInfos = null;
11517         if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11518             dynamicSharedLibraryInfos = new ArrayList<>(pkg.libraryNames.size());
11519             for (String name : pkg.libraryNames) {
11520                 dynamicSharedLibraryInfos.add(SharedLibraryInfo.createForDynamic(pkg, name));
11521             }
11522         }
11523
11524         return new ScanResult(request, true, pkgSetting, changedAbiCodePath,
11525                 !createNewPackage /* existingSettingCopied */, staticSharedLibraryInfo,
11526                 dynamicSharedLibraryInfos);
11527     }
11528
11529     /**
11530      * Returns {@code true} if the given file contains code. Otherwise {@code false}.
11531      */
11532     private static boolean apkHasCode(String fileName) {
11533         StrictJarFile jarFile = null;
11534         try {
11535             jarFile = new StrictJarFile(fileName,
11536                     false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/);
11537             return jarFile.findEntry("classes.dex") != null;
11538         } catch (IOException ignore) {
11539         } finally {
11540             try {
11541                 if (jarFile != null) {
11542                     jarFile.close();
11543                 }
11544             } catch (IOException ignore) {}
11545         }
11546         return false;
11547     }
11548
11549     /**
11550      * Enforces code policy for the package. This ensures that if an APK has
11551      * declared hasCode="true" in its manifest that the APK actually contains
11552      * code.
11553      *
11554      * @throws PackageManagerException If bytecode could not be found when it should exist
11555      */
11556     private static void assertCodePolicy(PackageParser.Package pkg)
11557             throws PackageManagerException {
11558         final boolean shouldHaveCode =
11559                 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0;
11560         if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) {
11561             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11562                     "Package " + pkg.baseCodePath + " code is missing");
11563         }
11564
11565         if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
11566             for (int i = 0; i < pkg.splitCodePaths.length; i++) {
11567                 final boolean splitShouldHaveCode =
11568                         (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0;
11569                 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) {
11570                     throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11571                             "Package " + pkg.splitCodePaths[i] + " code is missing");
11572                 }
11573             }
11574         }
11575     }
11576
11577     /**
11578      * Applies policy to the parsed package based upon the given policy flags.
11579      * Ensures the package is in a good state.
11580      * <p>
11581      * Implementation detail: This method must NOT have any side effect. It would
11582      * ideally be static, but, it requires locks to read system state.
11583      */
11584     private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags,
11585             final @ScanFlags int scanFlags, PackageParser.Package platformPkg) {
11586         if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11587             pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
11588             if (pkg.applicationInfo.isDirectBootAware()) {
11589                 // we're direct boot aware; set for all components
11590                 for (PackageParser.Service s : pkg.services) {
11591                     s.info.encryptionAware = s.info.directBootAware = true;
11592                 }
11593                 for (PackageParser.Provider p : pkg.providers) {
11594                     p.info.encryptionAware = p.info.directBootAware = true;
11595                 }
11596                 for (PackageParser.Activity a : pkg.activities) {
11597                     a.info.encryptionAware = a.info.directBootAware = true;
11598                 }
11599                 for (PackageParser.Activity r : pkg.receivers) {
11600                     r.info.encryptionAware = r.info.directBootAware = true;
11601                 }
11602             }
11603             if (compressedFileExists(pkg.codePath)) {
11604                 pkg.isStub = true;
11605             }
11606         } else {
11607             // non system apps can't be flagged as core
11608             pkg.coreApp = false;
11609             // clear flags not applicable to regular apps
11610             pkg.applicationInfo.flags &=
11611                     ~ApplicationInfo.FLAG_PERSISTENT;
11612             pkg.applicationInfo.privateFlags &=
11613                     ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE;
11614             pkg.applicationInfo.privateFlags &=
11615                     ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
11616             // cap permission priorities
11617             if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) {
11618                 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) {
11619                     pkg.permissionGroups.get(i).info.priority = 0;
11620                 }
11621             }
11622         }
11623         if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
11624             // clear protected broadcasts
11625             pkg.protectedBroadcasts = null;
11626             // ignore export request for single user receivers
11627             if (pkg.receivers != null) {
11628                 for (int i = pkg.receivers.size() - 1; i >= 0; --i) {
11629                     final PackageParser.Activity receiver = pkg.receivers.get(i);
11630                     if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) {
11631                         receiver.info.exported = false;
11632                     }
11633                 }
11634             }
11635             // ignore export request for single user services
11636             if (pkg.services != null) {
11637                 for (int i = pkg.services.size() - 1; i >= 0; --i) {
11638                     final PackageParser.Service service = pkg.services.get(i);
11639                     if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) {
11640                         service.info.exported = false;
11641                     }
11642                 }
11643             }
11644             // ignore export request for single user providers
11645             if (pkg.providers != null) {
11646                 for (int i = pkg.providers.size() - 1; i >= 0; --i) {
11647                     final PackageParser.Provider provider = pkg.providers.get(i);
11648                     if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) {
11649                         provider.info.exported = false;
11650                     }
11651                 }
11652             }
11653         }
11654
11655         if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) {
11656             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
11657         }
11658
11659         if ((scanFlags & SCAN_AS_OEM) != 0) {
11660             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM;
11661         }
11662
11663         if ((scanFlags & SCAN_AS_VENDOR) != 0) {
11664             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR;
11665         }
11666
11667         if ((scanFlags & SCAN_AS_PRODUCT) != 0) {
11668             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT;
11669         }
11670
11671         if ((scanFlags & SCAN_AS_PRODUCT_SERVICES) != 0) {
11672             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT_SERVICES;
11673         }
11674
11675         if ((scanFlags & SCAN_AS_ODM) != 0) {
11676             pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_ODM;
11677         }
11678
11679         // Check if the package is signed with the same key as the platform package.
11680         if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) ||
11681                 (platformPkg != null && compareSignatures(
11682                         platformPkg.mSigningDetails.signatures,
11683                         pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) {
11684             pkg.applicationInfo.privateFlags |=
11685                 ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY;
11686         }
11687
11688         if (!isSystemApp(pkg)) {
11689             // Only system apps can use these features.
11690             pkg.mOriginalPackages = null;
11691             pkg.mRealPackage = null;
11692             pkg.mAdoptPermissions = null;
11693         }
11694
11695         PackageBackwardCompatibility.modifySharedLibraries(pkg);
11696     }
11697
11698     private static @NonNull <T> T assertNotNull(@Nullable T object, String message)
11699             throws PackageManagerException {
11700         if (object == null) {
11701             throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message);
11702         }
11703         return object;
11704     }
11705
11706     /**
11707      * Asserts the parsed package is valid according to the given policy. If the
11708      * package is invalid, for whatever reason, throws {@link PackageManagerException}.
11709      * <p>
11710      * Implementation detail: This method must NOT have any side effects. It would
11711      * ideally be static, but, it requires locks to read system state.
11712      *
11713      * @throws PackageManagerException If the package fails any of the validation checks
11714      */
11715     private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags,
11716             final @ScanFlags int scanFlags)
11717                     throws PackageManagerException {
11718         if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) {
11719             assertCodePolicy(pkg);
11720         }
11721
11722         if (pkg.applicationInfo.getCodePath() == null ||
11723                 pkg.applicationInfo.getResourcePath() == null) {
11724             // Bail out. The resource and code paths haven't been set.
11725             throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
11726                     "Code and resource paths haven't been set correctly");
11727         }
11728
11729         // Check that there is an APEX package with the same name only during install/first boot
11730         // after OTA.
11731         final boolean isUserInstall = (scanFlags & SCAN_BOOTING) == 0;
11732         final boolean isFirstBootOrUpgrade = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0;
11733         if ((isUserInstall || isFirstBootOrUpgrade)
11734                 && mApexManager.isApexPackage(pkg.packageName)) {
11735             throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11736                     pkg.packageName + " is an APEX package and can't be installed as an APK.");
11737         }
11738
11739         // Make sure we're not adding any bogus keyset info
11740         final KeySetManagerService ksms = mSettings.mKeySetManagerService;
11741         ksms.assertScannedPackageValid(pkg);
11742
11743         synchronized (mPackages) {
11744             // The special "android" package can only be defined once
11745             if (pkg.packageName.equals("android")) {
11746                 if (mAndroidApplication != null) {
11747                     Slog.w(TAG, "*************************************************");
11748                     Slog.w(TAG, "Core android package being redefined.  Skipping.");
11749                     Slog.w(TAG, " codePath=" + pkg.codePath);
11750                     Slog.w(TAG, "*************************************************");
11751                     throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11752                             "Core android package being redefined.  Skipping.");
11753                 }
11754             }
11755
11756             // A package name must be unique; don't allow duplicates
11757             if ((scanFlags & SCAN_NEW_INSTALL) == 0 && mPackages.containsKey(pkg.packageName)) {
11758                 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
11759                         "Application package " + pkg.packageName
11760                         + " already installed.  Skipping duplicate.");
11761             }
11762
11763             if (pkg.applicationInfo.isStaticSharedLibrary()) {
11764                 // Static libs have a synthetic package name containing the version
11765                 // but we still want the base name to be unique.
11766                 if ((scanFlags & SCAN_NEW_INSTALL) == 0
11767                         && mPackages.containsKey(pkg.manifestPackageName)) {
11768                     throw new PackageManagerException(
11769                             "Duplicate static shared lib provider package");
11770                 }
11771
11772                 // Static shared libraries should have at least O target SDK
11773                 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
11774                     throw new PackageManagerException(
11775                             "Packages declaring static-shared libs must target O SDK or higher");
11776                 }
11777
11778                 // Package declaring static a shared lib cannot be instant apps
11779                 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
11780                     throw new PackageManagerException(
11781                             "Packages declaring static-shared libs cannot be instant apps");
11782                 }
11783
11784                 // Package declaring static a shared lib cannot be renamed since the package
11785                 // name is synthetic and apps can't code around package manager internals.
11786                 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) {
11787                     throw new PackageManagerException(
11788                             "Packages declaring static-shared libs cannot be renamed");
11789                 }
11790
11791                 // Package declaring static a shared lib cannot declare child packages
11792                 if (!ArrayUtils.isEmpty(pkg.childPackages)) {
11793                     throw new PackageManagerException(
11794                             "Packages declaring static-shared libs cannot have child packages");
11795                 }
11796
11797                 // Package declaring static a shared lib cannot declare dynamic libs
11798                 if (!ArrayUtils.isEmpty(pkg.libraryNames)) {
11799                     throw new PackageManagerException(
11800                             "Packages declaring static-shared libs cannot declare dynamic libs");
11801                 }
11802
11803                 // Package declaring static a shared lib cannot declare shared users
11804                 if (pkg.mSharedUserId != null) {
11805                     throw new PackageManagerException(
11806                             "Packages declaring static-shared libs cannot declare shared users");
11807                 }
11808
11809                 // Static shared libs cannot declare activities
11810                 if (!pkg.activities.isEmpty()) {
11811                     throw new PackageManagerException(
11812                             "Static shared libs cannot declare activities");
11813                 }
11814
11815                 // Static shared libs cannot declare services
11816                 if (!pkg.services.isEmpty()) {
11817                     throw new PackageManagerException(
11818                             "Static shared libs cannot declare services");
11819                 }
11820
11821                 // Static shared libs cannot declare providers
11822                 if (!pkg.providers.isEmpty()) {
11823                     throw new PackageManagerException(
11824                             "Static shared libs cannot declare content providers");
11825                 }
11826
11827                 // Static shared libs cannot declare receivers
11828                 if (!pkg.receivers.isEmpty()) {
11829                     throw new PackageManagerException(
11830                             "Static shared libs cannot declare broadcast receivers");
11831                 }
11832
11833                 // Static shared libs cannot declare permission groups
11834                 if (!pkg.permissionGroups.isEmpty()) {
11835                     throw new PackageManagerException(
11836                             "Static shared libs cannot declare permission groups");
11837                 }
11838
11839                 // Static shared libs cannot declare permissions
11840                 if (!pkg.permissions.isEmpty()) {
11841                     throw new PackageManagerException(
11842                             "Static shared libs cannot declare permissions");
11843                 }
11844
11845                 // Static shared libs cannot declare protected broadcasts
11846                 if (pkg.protectedBroadcasts != null) {
11847                     throw new PackageManagerException(
11848                             "Static shared libs cannot declare protected broadcasts");
11849                 }
11850
11851                 // Static shared libs cannot be overlay targets
11852                 if (pkg.mOverlayTarget != null) {
11853                     throw new PackageManagerException(
11854                             "Static shared libs cannot be overlay targets");
11855                 }
11856
11857                 // The version codes must be ordered as lib versions
11858                 long minVersionCode = Long.MIN_VALUE;
11859                 long maxVersionCode = Long.MAX_VALUE;
11860
11861                 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.get(
11862                         pkg.staticSharedLibName);
11863                 if (versionedLib != null) {
11864                     final int versionCount = versionedLib.size();
11865                     for (int i = 0; i < versionCount; i++) {
11866                         SharedLibraryInfo libInfo = versionedLib.valueAt(i);
11867                         final long libVersionCode = libInfo.getDeclaringPackage()
11868                                 .getLongVersionCode();
11869                         if (libInfo.getLongVersion() <  pkg.staticSharedLibVersion) {
11870                             minVersionCode = Math.max(minVersionCode, libVersionCode + 1);
11871                         } else if (libInfo.getLongVersion() >  pkg.staticSharedLibVersion) {
11872                             maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1);
11873                         } else {
11874                             minVersionCode = maxVersionCode = libVersionCode;
11875                             break;
11876                         }
11877                     }
11878                 }
11879                 if (pkg.getLongVersionCode() < minVersionCode
11880                         || pkg.getLongVersionCode() > maxVersionCode) {
11881                     throw new PackageManagerException("Static shared"
11882                             + " lib version codes must be ordered as lib versions");
11883                 }
11884             }
11885
11886             // Only privileged apps and updated privileged apps can add child packages.
11887             if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) {
11888                 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) {
11889                     throw new PackageManagerException("Only privileged apps can add child "
11890                             + "packages. Ignoring package " + pkg.packageName);
11891                 }
11892                 final int childCount = pkg.childPackages.size();
11893                 for (int i = 0; i < childCount; i++) {
11894                     PackageParser.Package childPkg = pkg.childPackages.get(i);
11895                     if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName,
11896                             childPkg.packageName)) {
11897                         throw new PackageManagerException("Can't override child of "
11898                                 + "another disabled app. Ignoring package " + pkg.packageName);
11899                     }
11900                 }
11901             }
11902
11903             // If we're only installing presumed-existing packages, require that the
11904             // scanned APK is both already known and at the path previously established
11905             // for it.  Previously unknown packages we pick up normally, but if we have an
11906             // a priori expectation about this package's install presence, enforce it.
11907             // With a singular exception for new system packages. When an OTA contains
11908             // a new system package, we allow the codepath to change from a system location
11909             // to the user-installed location. If we don't allow this change, any newer,
11910             // user-installed version of the application will be ignored.
11911             if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
11912                 if (mExpectingBetter.containsKey(pkg.packageName)) {
11913                     logCriticalInfo(Log.WARN,
11914                             "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName);
11915                 } else {
11916                     PackageSetting known = mSettings.getPackageLPr(pkg.packageName);
11917                     if (known != null) {
11918                         if (DEBUG_PACKAGE_SCANNING) {
11919                             Log.d(TAG, "Examining " + pkg.codePath
11920                                     + " and requiring known paths " + known.codePathString
11921                                     + " & " + known.resourcePathString);
11922                         }
11923                         if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
11924                                 || !pkg.applicationInfo.getResourcePath().equals(
11925                                         known.resourcePathString)) {
11926                             throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
11927                                     "Application package " + pkg.packageName
11928                                     + " found at " + pkg.applicationInfo.getCodePath()
11929                                     + " but expected at " + known.codePathString
11930                                     + "; ignoring.");
11931                         }
11932                     } else {
11933                         throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11934                                 "Application package " + pkg.packageName
11935                                 + " not found; ignoring.");
11936                     }
11937                 }
11938             }
11939
11940             // Verify that this new package doesn't have any content providers
11941             // that conflict with existing packages.  Only do this if the
11942             // package isn't already installed, since we don't want to break
11943             // things that are installed.
11944             if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
11945                 mComponentResolver.assertProvidersNotDefined(pkg);
11946             }
11947
11948             // Verify that packages sharing a user with a privileged app are marked as privileged.
11949             if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) {
11950                 SharedUserSetting sharedUserSetting = null;
11951                 try {
11952                     sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false);
11953                 } catch (PackageManagerException ignore) {}
11954                 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) {
11955                     // Exempt SharedUsers signed with the platform key.
11956                     PackageSetting platformPkgSetting = mSettings.mPackages.get("android");
11957                     if ((platformPkgSetting.signatures.mSigningDetails
11958                             != PackageParser.SigningDetails.UNKNOWN)
11959                             && (compareSignatures(
11960                                     platformPkgSetting.signatures.mSigningDetails.signatures,
11961                                     pkg.mSigningDetails.signatures)
11962                                             != PackageManager.SIGNATURE_MATCH)) {
11963                         throw new PackageManagerException("Apps that share a user with a " +
11964                                 "privileged app must themselves be marked as privileged. " +
11965                                 pkg.packageName + " shares privileged user " +
11966                                 pkg.mSharedUserId + ".");
11967                     }
11968                 }
11969             }
11970
11971             // Apply policies specific for runtime resource overlays (RROs).
11972             if (pkg.mOverlayTarget != null) {
11973                 // System overlays have some restrictions on their use of the 'static' state.
11974                 if ((scanFlags & SCAN_AS_SYSTEM) != 0) {
11975                     // We are scanning a system overlay. This can be the first scan of the
11976                     // system/vendor/oem partition, or an update to the system overlay.
11977                     if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
11978                         // This must be an update to a system overlay.
11979                         final PackageSetting previousPkg = assertNotNull(
11980                                 mSettings.getPackageLPr(pkg.packageName),
11981                                 "previous package state not present");
11982
11983                         // previousPkg.pkg may be null: the package will be not be scanned if the
11984                         // package manager knows there is a newer version on /data.
11985                         // TODO[b/79435695]: Find a better way to keep track of the "static"
11986                         // property for RROs instead of having to parse packages on /system
11987                         PackageParser.Package ppkg = previousPkg.pkg;
11988                         if (ppkg == null) {
11989                             try {
11990                                 final PackageParser pp = new PackageParser();
11991                                 ppkg = pp.parsePackage(previousPkg.codePath,
11992                                         parseFlags | PackageParser.PARSE_IS_SYSTEM_DIR);
11993                             } catch (PackageParserException e) {
11994                                 Slog.w(TAG, "failed to parse " + previousPkg.codePath, e);
11995                             }
11996                         }
11997
11998                         // Static overlays cannot be updated.
11999                         if (ppkg != null && ppkg.mOverlayIsStatic) {
12000                             throw new PackageManagerException("Overlay " + pkg.packageName +
12001                                     " is static and cannot be upgraded.");
12002                         // Non-static overlays cannot be converted to static overlays.
12003                         } else if (pkg.mOverlayIsStatic) {
12004                             throw new PackageManagerException("Overlay " + pkg.packageName +
12005                                     " cannot be upgraded into a static overlay.");
12006                         }
12007                     }
12008                 } else {
12009                     // The overlay is a non-system overlay. Non-system overlays cannot be static.
12010                     if (pkg.mOverlayIsStatic) {
12011                         throw new PackageManagerException("Overlay " + pkg.packageName +
12012                                 " is static but not pre-installed.");
12013                     }
12014
12015                     // A non-preloaded overlay packages must have targetSdkVersion >= Q, or be
12016                     // signed with the platform certificate. Check this in increasing order of
12017                     // computational cost.
12018                     if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.Q) {
12019                         final PackageSetting platformPkgSetting =
12020                                 mSettings.getPackageLPr("android");
12021                         if ((platformPkgSetting.signatures.mSigningDetails
12022                                     != PackageParser.SigningDetails.UNKNOWN)
12023                                 && (compareSignatures(
12024                                         platformPkgSetting.signatures.mSigningDetails.signatures,
12025                                         pkg.mSigningDetails.signatures)
12026                                     != PackageManager.SIGNATURE_MATCH)) {
12027                             throw new PackageManagerException("Overlay " + pkg.packageName
12028                                     + " must target Q or later, "
12029                                     + "or be signed with the platform certificate");
12030                         }
12031                     }
12032
12033                     // A non-preloaded overlay package, without <overlay android:targetName>, will
12034                     // only be used if it is signed with the same certificate as its target. If the
12035                     // target is already installed, check this here to augment the last line of
12036                     // defence which is OMS.
12037                     if (pkg.mOverlayTargetName == null) {
12038                         final PackageSetting targetPkgSetting =
12039                                 mSettings.getPackageLPr(pkg.mOverlayTarget);
12040                         if (targetPkgSetting != null) {
12041                             if ((targetPkgSetting.signatures.mSigningDetails
12042                                         != PackageParser.SigningDetails.UNKNOWN)
12043                                     && (compareSignatures(
12044                                             targetPkgSetting.signatures.mSigningDetails.signatures,
12045                                             pkg.mSigningDetails.signatures)
12046                                         != PackageManager.SIGNATURE_MATCH)) {
12047                                 throw new PackageManagerException("Overlay " + pkg.packageName
12048                                         + " and target " + pkg.mOverlayTarget + " signed with"
12049                                         + " different certificates, and the overlay lacks"
12050                                         + " <overlay android:targetName>");
12051                             }
12052                         }
12053                     }
12054                 }
12055             }
12056         }
12057     }
12058
12059     @GuardedBy("mPackages")
12060     private boolean addBuiltInSharedLibraryLocked(String path, String name) {
12061         if (nonStaticSharedLibExistsLocked(name)) {
12062             return false;
12063         }
12064
12065         SharedLibraryInfo libraryInfo = new SharedLibraryInfo(path, null, null, name,
12066                 (long) SharedLibraryInfo.VERSION_UNDEFINED, SharedLibraryInfo.TYPE_BUILTIN,
12067                 new VersionedPackage(PLATFORM_PACKAGE_NAME, (long) 0),
12068                 null, null);
12069
12070         commitSharedLibraryInfoLocked(libraryInfo);
12071         return true;
12072     }
12073
12074     @GuardedBy("mPackages")
12075     private boolean nonStaticSharedLibExistsLocked(String name) {
12076         return sharedLibExists(name, SharedLibraryInfo.VERSION_UNDEFINED, mSharedLibraries);
12077     }
12078
12079     private static boolean sharedLibExists(final String name, final long version,
12080             Map<String, LongSparseArray<SharedLibraryInfo>> librarySource) {
12081         LongSparseArray<SharedLibraryInfo> versionedLib = librarySource.get(name);
12082         if (versionedLib != null && versionedLib.indexOfKey(version) >= 0) {
12083             return true;
12084         }
12085         return false;
12086     }
12087
12088     @GuardedBy("mPackages")
12089     private void commitSharedLibraryInfoLocked(SharedLibraryInfo libraryInfo) {
12090         final String name = libraryInfo.getName();
12091         LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.get(name);
12092         if (versionedLib == null) {
12093             versionedLib = new LongSparseArray<>();
12094             mSharedLibraries.put(name, versionedLib);
12095         }
12096         final String declaringPackageName = libraryInfo.getDeclaringPackage().getPackageName();
12097         if (libraryInfo.getType() == SharedLibraryInfo.TYPE_STATIC) {
12098             mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib);
12099         }
12100         versionedLib.put(libraryInfo.getLongVersion(), libraryInfo);
12101     }
12102
12103     private boolean removeSharedLibraryLPw(String name, long version) {
12104         LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.get(name);
12105         if (versionedLib == null) {
12106             return false;
12107         }
12108         final int libIdx = versionedLib.indexOfKey(version);
12109         if (libIdx < 0) {
12110             return false;
12111         }
12112         SharedLibraryInfo libraryInfo = versionedLib.valueAt(libIdx);
12113         versionedLib.remove(version);
12114         if (versionedLib.size() <= 0) {
12115             mSharedLibraries.remove(name);
12116             if (libraryInfo.getType() == SharedLibraryInfo.TYPE_STATIC) {
12117                 mStaticLibsByDeclaringPackage.remove(libraryInfo.getDeclaringPackage()
12118                         .getPackageName());
12119             }
12120         }
12121         return true;
12122     }
12123
12124     /**
12125      * Adds a scanned package to the system. When this method is finished, the package will
12126      * be available for query, resolution, etc...
12127      */
12128     private void commitPackageSettings(PackageParser.Package pkg,
12129             @Nullable PackageParser.Package oldPkg, PackageSetting pkgSetting,
12130             final @ScanFlags int scanFlags, boolean chatty, ReconciledPackage reconciledPkg) {
12131         final String pkgName = pkg.packageName;
12132         if (mCustomResolverComponentName != null &&
12133                 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
12134             setUpCustomResolverActivity(pkg);
12135         }
12136
12137         if (pkg.packageName.equals("android")) {
12138             synchronized (mPackages) {
12139                 if ((scanFlags & SCAN_CHECK_ONLY) == 0) {
12140                     // Set up information for our fall-back user intent resolution activity.
12141                     mPlatformPackage = pkg;
12142                     pkg.mVersionCode = mSdkVersion;
12143                     pkg.mVersionCodeMajor = 0;
12144                     mAndroidApplication = pkg.applicationInfo;
12145                     if (!mResolverReplaced) {
12146                         mResolveActivity.applicationInfo = mAndroidApplication;
12147                         mResolveActivity.name = ResolverActivity.class.getName();
12148                         mResolveActivity.packageName = mAndroidApplication.packageName;
12149                         mResolveActivity.processName = "system:ui";
12150                         mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12151                         mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
12152                         mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
12153                         mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert;
12154                         mResolveActivity.exported = true;
12155                         mResolveActivity.enabled = true;
12156                         mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE;
12157                         mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE
12158                                 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE
12159                                 | ActivityInfo.CONFIG_SCREEN_LAYOUT
12160                                 | ActivityInfo.CONFIG_ORIENTATION
12161                                 | ActivityInfo.CONFIG_KEYBOARD
12162                                 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN;
12163                         mResolveInfo.activityInfo = mResolveActivity;
12164                         mResolveInfo.priority = 0;
12165                         mResolveInfo.preferredOrder = 0;
12166                         mResolveInfo.match = 0;
12167                         mResolveComponentName = new ComponentName(
12168                                 mAndroidApplication.packageName, mResolveActivity.name);
12169                     }
12170                 }
12171             }
12172         }
12173
12174         ArrayList<PackageParser.Package> clientLibPkgs = null;
12175         // writer
12176         synchronized (mPackages) {
12177             if (!ArrayUtils.isEmpty(reconciledPkg.allowedSharedLibraryInfos)) {
12178                 for (SharedLibraryInfo info : reconciledPkg.allowedSharedLibraryInfos) {
12179                     commitSharedLibraryInfoLocked(info);
12180                 }
12181                 final Map<String, PackageParser.Package> combinedPackages =
12182                         reconciledPkg.getCombinedPackages();
12183                 try {
12184                     // Shared libraries for the package need to be updated.
12185                     updateSharedLibrariesLocked(pkg, null, combinedPackages);
12186                 } catch (PackageManagerException e) {
12187                     Slog.e(TAG, "updateSharedLibrariesLPr failed: ", e);
12188                 }
12189                 // Update all applications that use this library. Skip when booting
12190                 // since this will be done after all packages are scaned.
12191                 if ((scanFlags & SCAN_BOOTING) == 0) {
12192                     clientLibPkgs = updateAllSharedLibrariesLocked(pkg, combinedPackages);
12193                 }
12194             }
12195         }
12196
12197         if ((scanFlags & SCAN_BOOTING) != 0) {
12198             // No apps can run during boot scan, so they don't need to be frozen
12199         } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) {
12200             // Caller asked to not kill app, so it's probably not frozen
12201         } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) {
12202             // Caller asked us to ignore frozen check for some reason; they
12203             // probably didn't know the package name
12204         } else {
12205             // We're doing major surgery on this package, so it better be frozen
12206             // right now to keep it from launching
12207             checkPackageFrozen(pkgName);
12208         }
12209
12210         // Also need to kill any apps that are dependent on the library.
12211         if (clientLibPkgs != null) {
12212             for (int i=0; i<clientLibPkgs.size(); i++) {
12213                 PackageParser.Package clientPkg = clientLibPkgs.get(i);
12214                 killApplication(clientPkg.applicationInfo.packageName,
12215                         clientPkg.applicationInfo.uid, "update lib");
12216             }
12217         }
12218
12219         // writer
12220         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
12221
12222         synchronized (mPackages) {
12223             // We don't expect installation to fail beyond this point
12224
12225             // Add the new setting to mSettings
12226             mSettings.insertPackageSettingLPw(pkgSetting, pkg);
12227             // Add the new setting to mPackages
12228             mPackages.put(pkg.applicationInfo.packageName, pkg);
12229
12230             // Add the package's KeySets to the global KeySetManagerService
12231             KeySetManagerService ksms = mSettings.mKeySetManagerService;
12232             ksms.addScannedPackageLPw(pkg);
12233
12234             mComponentResolver.addAllComponents(pkg, chatty);
12235
12236             // Don't allow ephemeral applications to define new permissions groups.
12237             if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
12238                 Slog.w(TAG, "Permission groups from package " + pkg.packageName
12239                         + " ignored: instant apps cannot define new permission groups.");
12240             } else {
12241                 mPermissionManager.addAllPermissionGroups(pkg, chatty);
12242             }
12243
12244             // Don't allow ephemeral applications to define new permissions.
12245             if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) {
12246                 Slog.w(TAG, "Permissions from package " + pkg.packageName
12247                         + " ignored: instant apps cannot define new permissions.");
12248             } else {
12249                 mPermissionManager.addAllPermissions(pkg, chatty);
12250             }
12251
12252             int collectionSize = pkg.instrumentation.size();
12253             StringBuilder r = null;
12254             int i;
12255             for (i = 0; i < collectionSize; i++) {
12256                 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12257                 a.info.packageName = pkg.applicationInfo.packageName;
12258                 a.info.sourceDir = pkg.applicationInfo.sourceDir;
12259                 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
12260                 a.info.splitNames = pkg.splitNames;
12261                 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
12262                 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
12263                 a.info.splitDependencies = pkg.applicationInfo.splitDependencies;
12264                 a.info.dataDir = pkg.applicationInfo.dataDir;
12265                 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir;
12266                 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir;
12267                 a.info.primaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12268                 a.info.secondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi;
12269                 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
12270                 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir;
12271                 mInstrumentation.put(a.getComponentName(), a);
12272                 if (chatty) {
12273                     if (r == null) {
12274                         r = new StringBuilder(256);
12275                     } else {
12276                         r.append(' ');
12277                     }
12278                     r.append(a.info.name);
12279                 }
12280             }
12281             if (r != null) {
12282                 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
12283             }
12284
12285             if (pkg.protectedBroadcasts != null) {
12286                 collectionSize = pkg.protectedBroadcasts.size();
12287                 synchronized (mProtectedBroadcasts) {
12288                     for (i = 0; i < collectionSize; i++) {
12289                         mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
12290                     }
12291                 }
12292             }
12293
12294             if (oldPkg != null) {
12295                 // We need to call revokeRuntimePermissionsIfGroupChanged async as permission
12296                 // revoke callbacks from this method might need to kill apps which need the
12297                 // mPackages lock on a different thread. This would dead lock.
12298                 //
12299                 // Hence create a copy of all package names and pass it into
12300                 // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get
12301                 // revoked. If a new package is added before the async code runs the permission
12302                 // won't be granted yet, hence new packages are no problem.
12303                 final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet());
12304
12305                 AsyncTask.execute(() ->
12306                         mPermissionManager.revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg,
12307                                 allPackageNames, mPermissionCallback));
12308             }
12309         }
12310
12311         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12312     }
12313
12314     /**
12315      * Derive the ABI of a non-system package located at {@code scanFile}. This information
12316      * is derived purely on the basis of the contents of {@code scanFile} and
12317      * {@code cpuAbiOverride}.
12318      *
12319      * If {@code extractLibs} is true, native libraries are extracted from the app if required.
12320      */
12321     private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride,
12322             boolean extractLibs)
12323                     throws PackageManagerException {
12324         // Give ourselves some initial paths; we'll come back for another
12325         // pass once we've determined ABI below.
12326         setNativeLibraryPaths(pkg, sAppLib32InstallDir);
12327
12328         // We shouldn't attempt to extract libs from system app when it was not updated.
12329         if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
12330             extractLibs = false;
12331         }
12332
12333         final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
12334         final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
12335
12336         NativeLibraryHelper.Handle handle = null;
12337         try {
12338             handle = NativeLibraryHelper.Handle.create(pkg);
12339             // TODO(multiArch): This can be null for apps that didn't go through the
12340             // usual installation process. We can calculate it again, like we
12341             // do during install time.
12342             //
12343             // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
12344             // unnecessary.
12345             final File nativeLibraryRoot = new File(nativeLibraryRootStr);
12346
12347             // Null out the abis so that they can be recalculated.
12348             pkg.applicationInfo.primaryCpuAbi = null;
12349             pkg.applicationInfo.secondaryCpuAbi = null;
12350             if (isMultiArch(pkg.applicationInfo)) {
12351                 // Warn if we've set an abiOverride for multi-lib packages..
12352                 // By definition, we need to copy both 32 and 64 bit libraries for
12353                 // such packages.
12354                 if (pkg.cpuAbiOverride != null
12355                         && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
12356                     Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
12357                 }
12358
12359                 int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
12360                 int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
12361                 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
12362                     if (extractLibs) {
12363                         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12364                         abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12365                                 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
12366                                 useIsaSpecificSubdirs);
12367                     } else {
12368                         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12369                         abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
12370                     }
12371                     Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12372                 }
12373
12374                 // Shared library native code should be in the APK zip aligned
12375                 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) {
12376                     throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12377                             "Shared library native lib extraction not supported");
12378                 }
12379
12380                 maybeThrowExceptionForMultiArchCopy(
12381                         "Error unpackaging 32 bit native libs for multiarch app.", abi32);
12382
12383                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
12384                     if (extractLibs) {
12385                         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12386                         abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12387                                 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
12388                                 useIsaSpecificSubdirs);
12389                     } else {
12390                         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12391                         abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
12392                     }
12393                     Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12394                 }
12395
12396                 maybeThrowExceptionForMultiArchCopy(
12397                         "Error unpackaging 64 bit native libs for multiarch app.", abi64);
12398
12399                 if (abi64 >= 0) {
12400                     // Shared library native libs should be in the APK zip aligned
12401                     if (extractLibs && pkg.isLibrary()) {
12402                         throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12403                                 "Shared library native lib extraction not supported");
12404                     }
12405                     pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
12406                 }
12407
12408                 if (abi32 >= 0) {
12409                     final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
12410                     if (abi64 >= 0) {
12411                         if (pkg.use32bitAbi) {
12412                             pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi;
12413                             pkg.applicationInfo.primaryCpuAbi = abi;
12414                         } else {
12415                             pkg.applicationInfo.secondaryCpuAbi = abi;
12416                         }
12417                     } else {
12418                         pkg.applicationInfo.primaryCpuAbi = abi;
12419                     }
12420                 }
12421             } else {
12422                 String[] abiList = (cpuAbiOverride != null) ?
12423                         new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
12424
12425                 // Enable gross and lame hacks for apps that are built with old
12426                 // SDK tools. We must scan their APKs for renderscript bitcode and
12427                 // not launch them if it's present. Don't bother checking on devices
12428                 // that don't have 64 bit support.
12429                 boolean needsRenderScriptOverride = false;
12430                 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
12431                         NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
12432                     abiList = Build.SUPPORTED_32_BIT_ABIS;
12433                     needsRenderScriptOverride = true;
12434                 }
12435
12436                 final int copyRet;
12437                 if (extractLibs) {
12438                     Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries");
12439                     copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
12440                             nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
12441                 } else {
12442                     Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi");
12443                     copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
12444                 }
12445                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
12446
12447                 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
12448                     throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12449                             "Error unpackaging native libs for app, errorCode=" + copyRet);
12450                 }
12451
12452                 if (copyRet >= 0) {
12453                     // Shared libraries that have native libs must be multi-architecture
12454                     if (pkg.isLibrary()) {
12455                         throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
12456                                 "Shared library with native libs must be multiarch");
12457                     }
12458                     pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
12459                 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
12460                     pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
12461                 } else if (needsRenderScriptOverride) {
12462                     pkg.applicationInfo.primaryCpuAbi = abiList[0];
12463                 }
12464             }
12465         } catch (IOException ioe) {
12466             Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
12467         } finally {
12468             IoUtils.closeQuietly(handle);
12469         }
12470
12471         // Now that we've calculated the ABIs and determined if it's an internal app,
12472         // we will go ahead and populate the nativeLibraryPath.
12473         setNativeLibraryPaths(pkg, sAppLib32InstallDir);
12474     }
12475
12476     /**
12477      * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
12478      * i.e, so that all packages can be run inside a single process if required.
12479      *
12480      * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
12481      * this function will either try and make the ABI for all packages in {@code packagesForUser}
12482      * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
12483      * the ABI selected for {@code packagesForUser}. This variant is used when installing or
12484      * updating a package that belongs to a shared user.
12485      *
12486      * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
12487      * adds unnecessary complexity.
12488      */
12489     private static @Nullable List<String> adjustCpuAbisForSharedUserLPw(
12490             Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) {
12491         List<String> changedAbiCodePath = null;
12492         String requiredInstructionSet = null;
12493         if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
12494             requiredInstructionSet = VMRuntime.getInstructionSet(
12495                      scannedPackage.applicationInfo.primaryCpuAbi);
12496         }
12497
12498         PackageSetting requirer = null;
12499         for (PackageSetting ps : packagesForUser) {
12500             // If packagesForUser contains scannedPackage, we skip it. This will happen
12501             // when scannedPackage is an update of an existing package. Without this check,
12502             // we will never be able to change the ABI of any package belonging to a shared
12503             // user, even if it's compatible with other packages.
12504             if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12505                 if (ps.primaryCpuAbiString == null) {
12506                     continue;
12507                 }
12508
12509                 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
12510                 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
12511                     // We have a mismatch between instruction sets (say arm vs arm64) warn about
12512                     // this but there's not much we can do.
12513                     String errorMessage = "Instruction set mismatch, "
12514                             + ((requirer == null) ? "[caller]" : requirer)
12515                             + " requires " + requiredInstructionSet + " whereas " + ps
12516                             + " requires " + instructionSet;
12517                     Slog.w(TAG, errorMessage);
12518                 }
12519
12520                 if (requiredInstructionSet == null) {
12521                     requiredInstructionSet = instructionSet;
12522                     requirer = ps;
12523                 }
12524             }
12525         }
12526
12527         if (requiredInstructionSet != null) {
12528             String adjustedAbi;
12529             if (requirer != null) {
12530                 // requirer != null implies that either scannedPackage was null or that scannedPackage
12531                 // did not require an ABI, in which case we have to adjust scannedPackage to match
12532                 // the ABI of the set (which is the same as requirer's ABI)
12533                 adjustedAbi = requirer.primaryCpuAbiString;
12534                 if (scannedPackage != null) {
12535                     scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
12536                 }
12537             } else {
12538                 // requirer == null implies that we're updating all ABIs in the set to
12539                 // match scannedPackage.
12540                 adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
12541             }
12542
12543             for (PackageSetting ps : packagesForUser) {
12544                 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
12545                     if (ps.primaryCpuAbiString != null) {
12546                         continue;
12547                     }
12548
12549                     ps.primaryCpuAbiString = adjustedAbi;
12550                     if (ps.pkg != null && ps.pkg.applicationInfo != null &&
12551                             !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) {
12552                         ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
12553                         if (DEBUG_ABI_SELECTION) {
12554                             Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi
12555                                     + " (requirer="
12556                                     + (requirer != null ? requirer.pkg : "null")
12557                                     + ", scannedPackage="
12558                                     + (scannedPackage != null ? scannedPackage : "null")
12559                                     + ")");
12560                         }
12561                         if (changedAbiCodePath == null) {
12562                             changedAbiCodePath = new ArrayList<>();
12563                         }
12564                         changedAbiCodePath.add(ps.codePathString);
12565                     }
12566                 }
12567             }
12568         }
12569         return changedAbiCodePath;
12570     }
12571
12572     private void setUpCustomResolverActivity(PackageParser.Package pkg) {
12573         synchronized (mPackages) {
12574             mResolverReplaced = true;
12575             // Set up information for custom user intent resolution activity.
12576             mResolveActivity.applicationInfo = pkg.applicationInfo;
12577             mResolveActivity.name = mCustomResolverComponentName.getClassName();
12578             mResolveActivity.packageName = pkg.applicationInfo.packageName;
12579             mResolveActivity.processName = pkg.applicationInfo.packageName;
12580             mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
12581             mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
12582                     ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12583             mResolveActivity.theme = 0;
12584             mResolveActivity.exported = true;
12585             mResolveActivity.enabled = true;
12586             mResolveInfo.activityInfo = mResolveActivity;
12587             mResolveInfo.priority = 0;
12588             mResolveInfo.preferredOrder = 0;
12589             mResolveInfo.match = 0;
12590             mResolveComponentName = mCustomResolverComponentName;
12591             Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
12592                     mResolveComponentName);
12593         }
12594     }
12595
12596     private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) {
12597         if (installerActivity == null) {
12598             if (DEBUG_INSTANT) {
12599                 Slog.d(TAG, "Clear ephemeral installer activity");
12600             }
12601             mInstantAppInstallerActivity = null;
12602             return;
12603         }
12604
12605         if (DEBUG_INSTANT) {
12606             Slog.d(TAG, "Set ephemeral installer activity: "
12607                     + installerActivity.getComponentName());
12608         }
12609         // Set up information for ephemeral installer activity
12610         mInstantAppInstallerActivity = installerActivity;
12611         mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS
12612                 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
12613         mInstantAppInstallerActivity.exported = true;
12614         mInstantAppInstallerActivity.enabled = true;
12615         mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity;
12616         mInstantAppInstallerInfo.priority = 1;
12617         mInstantAppInstallerInfo.preferredOrder = 1;
12618         mInstantAppInstallerInfo.isDefault = true;
12619         mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART
12620                 | IntentFilter.MATCH_ADJUSTMENT_NORMAL;
12621     }
12622
12623     private static String calculateBundledApkRoot(final String codePathString) {
12624         final File codePath = new File(codePathString);
12625         final File codeRoot;
12626         if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
12627             codeRoot = Environment.getRootDirectory();
12628         } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
12629             codeRoot = Environment.getOemDirectory();
12630         } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
12631             codeRoot = Environment.getVendorDirectory();
12632         } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
12633             codeRoot = Environment.getOdmDirectory();
12634         } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) {
12635             codeRoot = Environment.getProductDirectory();
12636         } else if (FileUtils.contains(Environment.getProductServicesDirectory(), codePath)) {
12637             codeRoot = Environment.getProductServicesDirectory();
12638         } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) {
12639             codeRoot = Environment.getOdmDirectory();
12640         } else {
12641             // Unrecognized code path; take its top real segment as the apk root:
12642             // e.g. /something/app/blah.apk => /something
12643             try {
12644                 File f = codePath.getCanonicalFile();
12645                 File parent = f.getParentFile();    // non-null because codePath is a file
12646                 File tmp;
12647                 while ((tmp = parent.getParentFile()) != null) {
12648                     f = parent;
12649                     parent = tmp;
12650                 }
12651                 codeRoot = f;
12652                 Slog.w(TAG, "Unrecognized code path "
12653                         + codePath + " - using " + codeRoot);
12654             } catch (IOException e) {
12655                 // Can't canonicalize the code path -- shenanigans?
12656                 Slog.w(TAG, "Can't canonicalize code path " + codePath);
12657                 return Environment.getRootDirectory().getPath();
12658             }
12659         }
12660         return codeRoot.getPath();
12661     }
12662
12663     /**
12664      * Derive and set the location of native libraries for the given package,
12665      * which varies depending on where and how the package was installed.
12666      */
12667     private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) {
12668         final ApplicationInfo info = pkg.applicationInfo;
12669         final String codePath = pkg.codePath;
12670         final File codeFile = new File(codePath);
12671         final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
12672
12673         info.nativeLibraryRootDir = null;
12674         info.nativeLibraryRootRequiresIsa = false;
12675         info.nativeLibraryDir = null;
12676         info.secondaryNativeLibraryDir = null;
12677
12678         if (isApkFile(codeFile)) {
12679             // Monolithic install
12680             if (bundledApp) {
12681                 // If "/system/lib64/apkname" exists, assume that is the per-package
12682                 // native library directory to use; otherwise use "/system/lib/apkname".
12683                 final String apkRoot = calculateBundledApkRoot(info.sourceDir);
12684                 final boolean is64Bit = VMRuntime.is64BitInstructionSet(
12685                         getPrimaryInstructionSet(info));
12686
12687                 // This is a bundled system app so choose the path based on the ABI.
12688                 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
12689                 // is just the default path.
12690                 final String apkName = deriveCodePathName(codePath);
12691                 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
12692                 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
12693                         apkName).getAbsolutePath();
12694
12695                 if (info.secondaryCpuAbi != null) {
12696                     final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
12697                     info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
12698                             secondaryLibDir, apkName).getAbsolutePath();
12699                 }
12700             } else {
12701                 final String apkName = deriveCodePathName(codePath);
12702                 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName)
12703                         .getAbsolutePath();
12704             }
12705
12706             info.nativeLibraryRootRequiresIsa = false;
12707             info.nativeLibraryDir = info.nativeLibraryRootDir;
12708         } else {
12709             // Cluster install
12710             info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
12711             info.nativeLibraryRootRequiresIsa = true;
12712
12713             info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
12714                     getPrimaryInstructionSet(info)).getAbsolutePath();
12715
12716             if (info.secondaryCpuAbi != null) {
12717                 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
12718                         VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
12719             }
12720         }
12721     }
12722
12723     /**
12724      * Calculate the abis and roots for a bundled app. These can uniquely
12725      * be determined from the contents of the system partition, i.e whether
12726      * it contains 64 or 32 bit shared libraries etc. We do not validate any
12727      * of this information, and instead assume that the system was built
12728      * sensibly.
12729      */
12730     private static void setBundledAppAbisAndRoots(PackageParser.Package pkg,
12731                                            PackageSetting pkgSetting) {
12732         final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
12733
12734         // If "/system/lib64/apkname" exists, assume that is the per-package
12735         // native library directory to use; otherwise use "/system/lib/apkname".
12736         final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
12737         setBundledAppAbi(pkg, apkRoot, apkName);
12738         // pkgSetting might be null during rescan following uninstall of updates
12739         // to a bundled app, so accommodate that possibility.  The settings in
12740         // that case will be established later from the parsed package.
12741         //
12742         // If the settings aren't null, sync them up with what we've just derived.
12743         // note that apkRoot isn't stored in the package settings.
12744         if (pkgSetting != null) {
12745             pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
12746             pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
12747         }
12748     }
12749
12750     /**
12751      * Deduces the ABI of a bundled app and sets the relevant fields on the
12752      * parsed pkg object.
12753      *
12754      * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
12755      *        under which system libraries are installed.
12756      * @param apkName the name of the installed package.
12757      */
12758     private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
12759         final File codeFile = new File(pkg.codePath);
12760
12761         final boolean has64BitLibs;
12762         final boolean has32BitLibs;
12763         if (isApkFile(codeFile)) {
12764             // Monolithic install
12765             has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
12766             has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
12767         } else {
12768             // Cluster install
12769             final File rootDir = new File(codeFile, LIB_DIR_NAME);
12770             if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
12771                     && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
12772                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
12773                 has64BitLibs = (new File(rootDir, isa)).exists();
12774             } else {
12775                 has64BitLibs = false;
12776             }
12777             if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
12778                     && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
12779                 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
12780                 has32BitLibs = (new File(rootDir, isa)).exists();
12781             } else {
12782                 has32BitLibs = false;
12783             }
12784         }
12785
12786         if (has64BitLibs && !has32BitLibs) {
12787             // The package has 64 bit libs, but not 32 bit libs. Its primary
12788             // ABI should be 64 bit. We can safely assume here that the bundled
12789             // native libraries correspond to the most preferred ABI in the list.
12790
12791             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12792             pkg.applicationInfo.secondaryCpuAbi = null;
12793         } else if (has32BitLibs && !has64BitLibs) {
12794             // The package has 32 bit libs but not 64 bit libs. Its primary
12795             // ABI should be 32 bit.
12796
12797             pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12798             pkg.applicationInfo.secondaryCpuAbi = null;
12799         } else if (has32BitLibs && has64BitLibs) {
12800             // The application has both 64 and 32 bit bundled libraries. We check
12801             // here that the app declares multiArch support, and warn if it doesn't.
12802             //
12803             // We will be lenient here and record both ABIs. The primary will be the
12804             // ABI that's higher on the list, i.e, a device that's configured to prefer
12805             // 64 bit apps will see a 64 bit primary ABI,
12806
12807             if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
12808                 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch.");
12809             }
12810
12811             if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
12812                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12813                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12814             } else {
12815                 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
12816                 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
12817             }
12818         } else {
12819             pkg.applicationInfo.primaryCpuAbi = null;
12820             pkg.applicationInfo.secondaryCpuAbi = null;
12821         }
12822     }
12823
12824     private void killApplication(String pkgName, int appId, String reason) {
12825         killApplication(pkgName, appId, UserHandle.USER_ALL, reason);
12826     }
12827
12828     private void killApplication(String pkgName, int appId, int userId, String reason) {
12829         // Request the ActivityManager to kill the process(only for existing packages)
12830         // so that we do not end up in a confused state while the user is still using the older
12831         // version of the application while the new one gets installed.
12832         final long token = Binder.clearCallingIdentity();
12833         try {
12834             IActivityManager am = ActivityManager.getService();
12835             if (am != null) {
12836                 try {
12837                     am.killApplication(pkgName, appId, userId, reason);
12838                 } catch (RemoteException e) {
12839                 }
12840             }
12841         } finally {
12842             Binder.restoreCallingIdentity(token);
12843         }
12844     }
12845
12846     private void removePackageLI(PackageParser.Package pkg, boolean chatty) {
12847         // Remove the parent package setting
12848         PackageSetting ps = (PackageSetting) pkg.mExtras;
12849         if (ps != null) {
12850             removePackageLI(ps.name, chatty);
12851         } else if (DEBUG_REMOVE && chatty) {
12852             Log.d(TAG, "Not removing package " + pkg.packageName + "; mExtras == null");
12853         }
12854         // Remove the child package setting
12855         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12856         for (int i = 0; i < childCount; i++) {
12857             PackageParser.Package childPkg = pkg.childPackages.get(i);
12858             ps = (PackageSetting) childPkg.mExtras;
12859             if (ps != null) {
12860                 removePackageLI(ps.name, chatty);
12861             }
12862         }
12863     }
12864
12865     void removePackageLI(String packageName, boolean chatty) {
12866         if (DEBUG_INSTALL) {
12867             if (chatty)
12868                 Log.d(TAG, "Removing package " + packageName);
12869         }
12870
12871         // writer
12872         synchronized (mPackages) {
12873             final PackageParser.Package removedPackage = mPackages.remove(packageName);
12874             if (removedPackage != null) {
12875                 cleanPackageDataStructuresLILPw(removedPackage, chatty);
12876             }
12877         }
12878     }
12879
12880     void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
12881         if (DEBUG_INSTALL) {
12882             if (chatty)
12883                 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
12884         }
12885
12886         // writer
12887         synchronized (mPackages) {
12888             // Remove the parent package
12889             mPackages.remove(pkg.applicationInfo.packageName);
12890             cleanPackageDataStructuresLILPw(pkg, chatty);
12891
12892             // Remove the child packages
12893             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
12894             for (int i = 0; i < childCount; i++) {
12895                 PackageParser.Package childPkg = pkg.childPackages.get(i);
12896                 mPackages.remove(childPkg.applicationInfo.packageName);
12897                 cleanPackageDataStructuresLILPw(childPkg, chatty);
12898             }
12899         }
12900     }
12901
12902     void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
12903         mComponentResolver.removeAllComponents(pkg, chatty);
12904
12905         mPermissionManager.removeAllPermissions(pkg, chatty);
12906
12907         final int instrumentationSize = pkg.instrumentation.size();
12908         StringBuilder r = null;
12909         int i;
12910         for (i = 0; i < instrumentationSize; i++) {
12911             PackageParser.Instrumentation a = pkg.instrumentation.get(i);
12912             mInstrumentation.remove(a.getComponentName());
12913             if (DEBUG_REMOVE && chatty) {
12914                 if (r == null) {
12915                     r = new StringBuilder(256);
12916                 } else {
12917                     r.append(' ');
12918                 }
12919                 r.append(a.info.name);
12920             }
12921         }
12922         if (r != null) {
12923             if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
12924         }
12925
12926         r = null;
12927         if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
12928             // Only system apps can hold shared libraries.
12929             if (pkg.libraryNames != null) {
12930                 final int libraryNamesSize = pkg.libraryNames.size();
12931                 for (i = 0; i < libraryNamesSize; i++) {
12932                     String name = pkg.libraryNames.get(i);
12933                     if (removeSharedLibraryLPw(name, 0)) {
12934                         if (DEBUG_REMOVE && chatty) {
12935                             if (r == null) {
12936                                 r = new StringBuilder(256);
12937                             } else {
12938                                 r.append(' ');
12939                             }
12940                             r.append(name);
12941                         }
12942                     }
12943                 }
12944             }
12945         }
12946
12947         r = null;
12948
12949         // Any package can hold static shared libraries.
12950         if (pkg.staticSharedLibName != null) {
12951             if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) {
12952                 if (DEBUG_REMOVE && chatty) {
12953                     if (r == null) {
12954                         r = new StringBuilder(256);
12955                     } else {
12956                         r.append(' ');
12957                     }
12958                     r.append(pkg.staticSharedLibName);
12959                 }
12960             }
12961         }
12962
12963         if (r != null) {
12964             if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
12965         }
12966     }
12967
12968     @Override
12969     public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras,
12970             final int flags, final String targetPkg, final IIntentReceiver finishedReceiver,
12971             final int[] userIds, int[] instantUserIds) {
12972         mHandler.post(() -> {
12973             try {
12974                 final IActivityManager am = ActivityManager.getService();
12975                 if (am == null) return;
12976                 final int[] resolvedUserIds;
12977                 if (userIds == null) {
12978                     resolvedUserIds = am.getRunningUserIds();
12979                 } else {
12980                     resolvedUserIds = userIds;
12981                 }
12982                 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
12983                         resolvedUserIds, false);
12984                 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) {
12985                     doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver,
12986                             instantUserIds, true);
12987                 }
12988             } catch (RemoteException ex) {
12989             }
12990         });
12991     }
12992
12993     @Override
12994     public void notifyPackageAdded(String packageName, int uid) {
12995         final PackageListObserver[] observers;
12996         synchronized (mPackages) {
12997             if (mPackageListObservers.size() == 0) {
12998                 return;
12999             }
13000             final PackageListObserver[] observerArray =
13001                     new PackageListObserver[mPackageListObservers.size()];
13002             observers = mPackageListObservers.toArray(observerArray);
13003         }
13004         for (int i = observers.length - 1; i >= 0; --i) {
13005             observers[i].onPackageAdded(packageName, uid);
13006         }
13007     }
13008
13009     @Override
13010     public void notifyPackageChanged(String packageName, int uid) {
13011         final PackageListObserver[] observers;
13012         synchronized (mPackages) {
13013             if (mPackageListObservers.size() == 0) {
13014                 return;
13015             }
13016             final PackageListObserver[] observerArray =
13017                     new PackageListObserver[mPackageListObservers.size()];
13018             observers = mPackageListObservers.toArray(observerArray);
13019         }
13020         for (int i = observers.length - 1; i >= 0; --i) {
13021             observers[i].onPackageChanged(packageName, uid);
13022         }
13023     }
13024
13025     private static final Comparator<ProviderInfo> sProviderInitOrderSorter = (p1, p2) -> {
13026         final int v1 = p1.initOrder;
13027         final int v2 = p2.initOrder;
13028         return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
13029     };
13030
13031     @Override
13032     public void notifyPackageRemoved(String packageName, int uid) {
13033         final PackageListObserver[] observers;
13034         synchronized (mPackages) {
13035             if (mPackageListObservers.size() == 0) {
13036                 return;
13037             }
13038             final PackageListObserver[] observerArray =
13039                     new PackageListObserver[mPackageListObservers.size()];
13040             observers = mPackageListObservers.toArray(observerArray);
13041         }
13042         for (int i = observers.length - 1; i >= 0; --i) {
13043             observers[i].onPackageRemoved(packageName, uid);
13044         }
13045     }
13046
13047     /**
13048      * Sends a broadcast for the given action.
13049      * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with
13050      * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows
13051      * the system and applications allowed to see instant applications to receive package
13052      * lifecycle events for instant applications.
13053      */
13054     private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras,
13055             int flags, String targetPkg, IIntentReceiver finishedReceiver,
13056             int[] userIds, boolean isInstantApp)
13057                     throws RemoteException {
13058         for (int id : userIds) {
13059             final Intent intent = new Intent(action,
13060                     pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null);
13061             final String[] requiredPermissions =
13062                     isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null;
13063             if (extras != null) {
13064                 intent.putExtras(extras);
13065             }
13066             if (targetPkg != null) {
13067                 intent.setPackage(targetPkg);
13068             }
13069             // Modify the UID when posting to other users
13070             int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
13071             if (uid > 0 && UserHandle.getUserId(uid) != id) {
13072                 uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
13073                 intent.putExtra(Intent.EXTRA_UID, uid);
13074             }
13075             intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
13076             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags);
13077             if (DEBUG_BROADCASTS) {
13078                 RuntimeException here = new RuntimeException("here");
13079                 here.fillInStackTrace();
13080                 Slog.d(TAG, "Sending to user " + id + ": "
13081                         + intent.toShortString(false, true, false, false)
13082                         + " " + intent.getExtras(), here);
13083             }
13084             am.broadcastIntent(null, intent, null, finishedReceiver,
13085                     0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE,
13086                     null, finishedReceiver != null, false, id);
13087         }
13088     }
13089
13090     /**
13091      * Check if the external storage media is available. This is true if there
13092      * is a mounted external storage medium or if the external storage is
13093      * emulated.
13094      */
13095     private boolean isExternalMediaAvailable() {
13096         return mMediaMounted || Environment.isExternalStorageEmulated();
13097     }
13098
13099     /**
13100      * Ensure that the install reason matches what we know about the package installer (e.g. whether
13101      * it is acting on behalf on an enterprise or the user).
13102      *
13103      * Note that the ordering of the conditionals in this method is important. The checks we perform
13104      * are as follows, in this order:
13105      *
13106      * 1) If the install is being performed by a system app, we can trust the app to have set the
13107      *    install reason correctly. Thus, we pass through the install reason unchanged, no matter
13108      *    what it is.
13109      * 2) If the install is being performed by a device or profile owner app, the install reason
13110      *    should be enterprise policy. However, we cannot be sure that the device or profile owner
13111      *    set the install reason correctly. If the app targets an older SDK version where install
13112      *    reasons did not exist yet, or if the app author simply forgot, the install reason may be
13113      *    unset or wrong. Thus, we force the install reason to be enterprise policy.
13114      * 3) In all other cases, the install is being performed by a regular app that is neither part
13115      *    of the system nor a device or profile owner. We have no reason to believe that this app is
13116      *    acting on behalf of the enterprise admin. Thus, we check whether the install reason was
13117      *    set to enterprise policy and if so, change it to unknown instead.
13118      */
13119     private int fixUpInstallReason(String installerPackageName, int installerUid,
13120             int installReason) {
13121         if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid)
13122                 == PERMISSION_GRANTED) {
13123             // If the install is being performed by a system app, we trust that app to have set the
13124             // install reason correctly.
13125             return installReason;
13126         }
13127         final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(
13128                 UserHandle.getUserId(installerUid));
13129         if (ownerPackage != null && ownerPackage.equals(installerPackageName)) {
13130             // If the install is being performed by a device or profile owner, the install
13131             // reason should be enterprise policy.
13132             return PackageManager.INSTALL_REASON_POLICY;
13133         }
13134
13135
13136         if (installReason == PackageManager.INSTALL_REASON_POLICY) {
13137             // If the install is being performed by a regular app (i.e. neither system app nor
13138             // device or profile owner), we have no reason to believe that the app is acting on
13139             // behalf of an enterprise. If the app set the install reason to enterprise policy,
13140             // change it to unknown instead.
13141             return PackageManager.INSTALL_REASON_UNKNOWN;
13142         }
13143
13144         // If the install is being performed by a regular app and the install reason was set to any
13145         // value but enterprise policy, leave the install reason unchanged.
13146         return installReason;
13147     }
13148
13149     void installStage(ActiveInstallSession activeInstallSession) {
13150         if (DEBUG_INSTANT) {
13151             if ((activeInstallSession.getSessionParams().installFlags
13152                     & PackageManager.INSTALL_INSTANT_APP) != 0) {
13153                 Slog.d(TAG, "Ephemeral install of " + activeInstallSession.getPackageName());
13154             }
13155         }
13156         final Message msg = mHandler.obtainMessage(INIT_COPY);
13157         final InstallParams params = new InstallParams(activeInstallSession);
13158         params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
13159         msg.obj = params;
13160
13161         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
13162                 System.identityHashCode(msg.obj));
13163         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13164                 System.identityHashCode(msg.obj));
13165
13166         mHandler.sendMessage(msg);
13167     }
13168
13169     void installStage(List<ActiveInstallSession> children)
13170             throws PackageManagerException {
13171         final Message msg = mHandler.obtainMessage(INIT_COPY);
13172         final MultiPackageInstallParams params =
13173                 new MultiPackageInstallParams(UserHandle.ALL, children);
13174         params.setTraceMethod("installStageMultiPackage")
13175                 .setTraceCookie(System.identityHashCode(params));
13176         msg.obj = params;
13177
13178         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStageMultiPackage",
13179                 System.identityHashCode(msg.obj));
13180         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
13181                 System.identityHashCode(msg.obj));
13182         mHandler.sendMessage(msg);
13183     }
13184
13185     private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting,
13186             int userId) {
13187         final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
13188         final boolean isInstantApp = pkgSetting.getInstantApp(userId);
13189         final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
13190         final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
13191         sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/,
13192                 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds);
13193
13194         // Send a session commit broadcast
13195         final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo();
13196         info.installReason = pkgSetting.getInstallReason(userId);
13197         info.appPackageName = packageName;
13198         sendSessionCommitBroadcast(info, userId);
13199     }
13200
13201     @Override
13202     public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
13203             boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) {
13204         if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) {
13205             return;
13206         }
13207         Bundle extras = new Bundle(1);
13208         // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast
13209         final int uid = UserHandle.getUid(
13210                 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId);
13211         extras.putInt(Intent.EXTRA_UID, uid);
13212
13213         sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
13214                 packageName, extras, 0, null, null, userIds, instantUserIds);
13215         if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) {
13216             mHandler.post(() -> {
13217                         for (int userId : userIds) {
13218                             sendBootCompletedBroadcastToSystemApp(
13219                                     packageName, includeStopped, userId);
13220                         }
13221                     }
13222             );
13223         }
13224     }
13225
13226     /**
13227      * The just-installed/enabled app is bundled on the system, so presumed to be able to run
13228      * automatically without needing an explicit launch.
13229      * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones.
13230      */
13231     private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped,
13232             int userId) {
13233         // If user is not running, the app didn't miss any broadcast
13234         if (!mUserManagerInternal.isUserRunning(userId)) {
13235             return;
13236         }
13237         final IActivityManager am = ActivityManager.getService();
13238         try {
13239             // Deliver LOCKED_BOOT_COMPLETED first
13240             Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED)
13241                     .setPackage(packageName);
13242             if (includeStopped) {
13243                 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13244             }
13245             final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED};
13246             am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions,
13247                     android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13248
13249             // Deliver BOOT_COMPLETED only if user is unlocked
13250             if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) {
13251                 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName);
13252                 if (includeStopped) {
13253                     bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
13254                 }
13255                 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions,
13256                         android.app.AppOpsManager.OP_NONE, null, false, false, userId);
13257             }
13258         } catch (RemoteException e) {
13259             throw e.rethrowFromSystemServer();
13260         }
13261     }
13262
13263     @Override
13264     public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
13265             int userId) {
13266         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13267         PackageSetting pkgSetting;
13268         final int callingUid = Binder.getCallingUid();
13269         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13270                 true /* requireFullPermission */, true /* checkShell */,
13271                 "setApplicationHiddenSetting for user " + userId);
13272
13273         if (hidden && isPackageDeviceAdmin(packageName, userId)) {
13274             Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
13275             return false;
13276         }
13277
13278         long callingId = Binder.clearCallingIdentity();
13279         try {
13280             boolean sendAdded = false;
13281             boolean sendRemoved = false;
13282             // writer
13283             synchronized (mPackages) {
13284                 pkgSetting = mSettings.mPackages.get(packageName);
13285                 if (pkgSetting == null) {
13286                     return false;
13287                 }
13288                 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13289                     return false;
13290                 }
13291                 // Do not allow "android" is being disabled
13292                 if ("android".equals(packageName)) {
13293                     Slog.w(TAG, "Cannot hide package: android");
13294                     return false;
13295                 }
13296                 // Cannot hide static shared libs as they are considered
13297                 // a part of the using app (emulating static linking). Also
13298                 // static libs are installed always on internal storage.
13299                 PackageParser.Package pkg = mPackages.get(packageName);
13300                 if (pkg != null && pkg.staticSharedLibName != null) {
13301                     Slog.w(TAG, "Cannot hide package: " + packageName
13302                             + " providing static shared library: "
13303                             + pkg.staticSharedLibName);
13304                     return false;
13305                 }
13306                 // Only allow protected packages to hide themselves.
13307                 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId)
13308                         && mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13309                     Slog.w(TAG, "Not hiding protected package: " + packageName);
13310                     return false;
13311                 }
13312
13313                 if (pkgSetting.getHidden(userId) != hidden) {
13314                     pkgSetting.setHidden(hidden, userId);
13315                     mSettings.writePackageRestrictionsLPr(userId);
13316                     if (hidden) {
13317                         sendRemoved = true;
13318                     } else {
13319                         sendAdded = true;
13320                     }
13321                 }
13322             }
13323             if (sendAdded) {
13324                 sendPackageAddedForUser(packageName, pkgSetting, userId);
13325                 return true;
13326             }
13327             if (sendRemoved) {
13328                 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
13329                         "hiding pkg");
13330                 sendApplicationHiddenForUser(packageName, pkgSetting, userId);
13331                 return true;
13332             }
13333         } finally {
13334             Binder.restoreCallingIdentity(callingId);
13335         }
13336         return false;
13337     }
13338
13339     @Override
13340     public void setSystemAppHiddenUntilInstalled(String packageName, boolean hidden) {
13341         enforceSystemOrPhoneCaller("setSystemAppHiddenUntilInstalled");
13342         synchronized (mPackages) {
13343             final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13344             if (pkgSetting == null || !pkgSetting.isSystem()) {
13345                 return;
13346             }
13347             PackageParser.Package pkg = pkgSetting.pkg;
13348             if (pkg != null && pkg.applicationInfo != null) {
13349                 pkg.applicationInfo.hiddenUntilInstalled = hidden;
13350             }
13351             final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(packageName);
13352             if (disabledPs == null) {
13353                 return;
13354             }
13355             pkg = disabledPs.pkg;
13356             if (pkg != null && pkg.applicationInfo != null) {
13357                 pkg.applicationInfo.hiddenUntilInstalled = hidden;
13358             }
13359         }
13360     }
13361
13362     @Override
13363     public boolean setSystemAppInstallState(String packageName, boolean installed, int userId) {
13364         enforceSystemOrPhoneCaller("setSystemAppInstallState");
13365         synchronized (mPackages) {
13366             final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
13367             // The target app should always be in system
13368             if (pkgSetting == null || !pkgSetting.isSystem()) {
13369                 return false;
13370             }
13371             // Check if the install state is the same
13372             if (pkgSetting.getInstalled(userId) == installed) {
13373                 return false;
13374             }
13375         }
13376
13377         final long callingId = Binder.clearCallingIdentity();
13378         try {
13379             if (installed) {
13380                 // install the app from uninstalled state
13381                 installExistingPackageAsUser(
13382                         packageName,
13383                         userId,
13384                         PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS,
13385                         PackageManager.INSTALL_REASON_DEVICE_SETUP,
13386                         null);
13387                 return true;
13388             }
13389
13390             // uninstall the app from installed state
13391             deletePackageVersioned(
13392                     new VersionedPackage(packageName, PackageManager.VERSION_CODE_HIGHEST),
13393                     new LegacyPackageDeleteObserver(null).getBinder(),
13394                     userId,
13395                     PackageManager.DELETE_SYSTEM_APP);
13396             return true;
13397         } finally {
13398             Binder.restoreCallingIdentity(callingId);
13399         }
13400     }
13401
13402     private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
13403             int userId) {
13404         final PackageRemovedInfo info = new PackageRemovedInfo(this);
13405         info.removedPackage = packageName;
13406         info.installerPackageName = pkgSetting.installerPackageName;
13407         info.removedUsers = new int[] {userId};
13408         info.broadcastUsers = new int[] {userId};
13409         info.uid = UserHandle.getUid(userId, pkgSetting.appId);
13410         info.sendPackageRemovedBroadcasts(true /*killApp*/);
13411     }
13412
13413     private void sendDistractingPackagesChanged(String[] pkgList, int[] uidList, int userId,
13414             int distractionFlags) {
13415         final Bundle extras = new Bundle(3);
13416         extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13417         extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidList);
13418         extras.putInt(Intent.EXTRA_DISTRACTION_RESTRICTIONS, distractionFlags);
13419         sendPackageBroadcast(Intent.ACTION_DISTRACTING_PACKAGES_CHANGED, null, extras,
13420                 Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, new int[]{userId}, null);
13421     }
13422
13423     private void sendPackagesSuspendedForUser(String[] pkgList, int[] uidList, int userId,
13424             boolean suspended, PersistableBundle launcherExtras) {
13425         final Bundle extras = new Bundle(3);
13426         extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
13427         extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidList);
13428         if (launcherExtras != null) {
13429             extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS,
13430                     new Bundle(launcherExtras.deepCopy()));
13431         }
13432         sendPackageBroadcast(
13433                 suspended ? Intent.ACTION_PACKAGES_SUSPENDED
13434                         : Intent.ACTION_PACKAGES_UNSUSPENDED,
13435                 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null,
13436                 new int[] {userId}, null);
13437     }
13438
13439     /**
13440      * Returns true if application is not found or there was an error. Otherwise it returns
13441      * the hidden state of the package for the given user.
13442      */
13443     @Override
13444     public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
13445         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
13446         final int callingUid = Binder.getCallingUid();
13447         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13448                 true /* requireFullPermission */, false /* checkShell */,
13449                 "getApplicationHidden for user " + userId);
13450         PackageSetting ps;
13451         long callingId = Binder.clearCallingIdentity();
13452         try {
13453             // writer
13454             synchronized (mPackages) {
13455                 ps = mSettings.mPackages.get(packageName);
13456                 if (ps == null) {
13457                     return true;
13458                 }
13459                 if (filterAppAccessLPr(ps, callingUid, userId)) {
13460                     return true;
13461                 }
13462                 return ps.getHidden(userId);
13463             }
13464         } finally {
13465             Binder.restoreCallingIdentity(callingId);
13466         }
13467     }
13468
13469     /**
13470      * @hide
13471      */
13472     @Override
13473     public int installExistingPackageAsUser(String packageName, int userId, int installFlags,
13474             int installReason, List<String> whiteListedPermissions) {
13475         return installExistingPackageAsUser(packageName, userId, installFlags, installReason,
13476                 whiteListedPermissions, null);
13477     }
13478
13479     int installExistingPackageAsUser(@Nullable String packageName, @UserIdInt int userId,
13480             @PackageManager.InstallFlags int installFlags,
13481             @PackageManager.InstallReason int installReason,
13482             @Nullable List<String> whiteListedPermissions, @Nullable IntentSender intentSender) {
13483         if (DEBUG_INSTALL) {
13484             Log.v(TAG, "installExistingPackageAsUser package=" + packageName + " userId=" + userId
13485                     + " installFlags=" + installFlags + " installReason=" + installReason
13486                     + " whiteListedPermissions=" + whiteListedPermissions);
13487         }
13488
13489         final int callingUid = Binder.getCallingUid();
13490         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES)
13491                 != PackageManager.PERMISSION_GRANTED
13492                 && mContext.checkCallingOrSelfPermission(
13493                         android.Manifest.permission.INSTALL_EXISTING_PACKAGES)
13494                 != PackageManager.PERMISSION_GRANTED) {
13495             throw new SecurityException("Neither user " + callingUid + " nor current process has "
13496                     + android.Manifest.permission.INSTALL_PACKAGES + ".");
13497         }
13498         PackageSetting pkgSetting;
13499         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13500                 true /* requireFullPermission */, true /* checkShell */,
13501                 "installExistingPackage for user " + userId);
13502         if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
13503             return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
13504         }
13505
13506         long callingId = Binder.clearCallingIdentity();
13507         try {
13508             boolean installed = false;
13509             final boolean instantApp =
13510                     (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
13511             final boolean fullApp =
13512                     (installFlags & PackageManager.INSTALL_FULL_APP) != 0;
13513
13514             // writer
13515             synchronized (mPackages) {
13516                 pkgSetting = mSettings.mPackages.get(packageName);
13517                 if (pkgSetting == null) {
13518                     return PackageManager.INSTALL_FAILED_INVALID_URI;
13519                 }
13520                 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) {
13521                     // only allow the existing package to be used if it's installed as a full
13522                     // application for at least one user
13523                     boolean installAllowed = false;
13524                     for (int checkUserId : sUserManager.getUserIds()) {
13525                         installAllowed = !pkgSetting.getInstantApp(checkUserId);
13526                         if (installAllowed) {
13527                             break;
13528                         }
13529                     }
13530                     if (!installAllowed) {
13531                         return PackageManager.INSTALL_FAILED_INVALID_URI;
13532                     }
13533                 }
13534                 if (!pkgSetting.getInstalled(userId)) {
13535                     pkgSetting.setInstalled(true, userId);
13536                     pkgSetting.setHidden(false, userId);
13537                     pkgSetting.setInstallReason(installReason, userId);
13538                     mSettings.writePackageRestrictionsLPr(userId);
13539                     mSettings.writeKernelMappingLPr(pkgSetting);
13540                     installed = true;
13541                 } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13542                     // upgrade app from instant to full; we don't allow app downgrade
13543                     installed = true;
13544                 }
13545                 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp);
13546             }
13547
13548             if (installed) {
13549                 if ((installFlags & PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS)
13550                         != 0 && pkgSetting.pkg != null) {
13551                     whiteListedPermissions = pkgSetting.pkg.requestedPermissions;
13552                 }
13553                 setWhitelistedRestrictedPermissions(packageName, whiteListedPermissions,
13554                         PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER, userId);
13555
13556                 if (pkgSetting.pkg != null) {
13557                     synchronized (mInstallLock) {
13558                         // We don't need to freeze for a brand new install
13559                         prepareAppDataAfterInstallLIF(pkgSetting.pkg);
13560                     }
13561                 }
13562                 sendPackageAddedForUser(packageName, pkgSetting, userId);
13563                 synchronized (mPackages) {
13564                     updateSequenceNumberLP(pkgSetting, new int[]{ userId });
13565                 }
13566                 // start async restore with no post-install since we finish install here
13567                 PackageInstalledInfo res =
13568                         createPackageInstalledInfo(PackageManager.INSTALL_SUCCEEDED);
13569                 res.pkg = pkgSetting.pkg;
13570                 res.newUsers = new int[]{ userId };
13571                 PostInstallData postInstallData = intentSender == null ? null :
13572                         new PostInstallData(null, res, () -> onRestoreComplete(res.returnCode,
13573                               mContext, intentSender));
13574                 restoreAndPostInstall(userId, res, postInstallData);
13575             }
13576         } finally {
13577             Binder.restoreCallingIdentity(callingId);
13578         }
13579
13580         return PackageManager.INSTALL_SUCCEEDED;
13581     }
13582
13583     static void onRestoreComplete(int returnCode, Context context, IntentSender target) {
13584         Intent fillIn = new Intent();
13585         fillIn.putExtra(PackageInstaller.EXTRA_STATUS,
13586                 PackageManager.installStatusToPublicStatus(returnCode));
13587         try {
13588             target.sendIntent(context, 0, fillIn, null, null);
13589         } catch (SendIntentException ignored) {
13590         }
13591     }
13592
13593     static void setInstantAppForUser(PackageSetting pkgSetting, int userId,
13594             boolean instantApp, boolean fullApp) {
13595         // no state specified; do nothing
13596         if (!instantApp && !fullApp) {
13597             return;
13598         }
13599         if (userId != UserHandle.USER_ALL) {
13600             if (instantApp && !pkgSetting.getInstantApp(userId)) {
13601                 pkgSetting.setInstantApp(true /*instantApp*/, userId);
13602             } else if (fullApp && pkgSetting.getInstantApp(userId)) {
13603                 pkgSetting.setInstantApp(false /*instantApp*/, userId);
13604             }
13605         } else {
13606             for (int currentUserId : sUserManager.getUserIds()) {
13607                 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) {
13608                     pkgSetting.setInstantApp(true /*instantApp*/, currentUserId);
13609                 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) {
13610                     pkgSetting.setInstantApp(false /*instantApp*/, currentUserId);
13611                 }
13612             }
13613         }
13614     }
13615
13616     boolean isUserRestricted(int userId, String restrictionKey) {
13617         Bundle restrictions = sUserManager.getUserRestrictions(userId);
13618         if (restrictions.getBoolean(restrictionKey, false)) {
13619             Log.w(TAG, "User is restricted: " + restrictionKey);
13620             return true;
13621         }
13622         return false;
13623     }
13624
13625     @Override
13626     public String[] setDistractingPackageRestrictionsAsUser(String[] packageNames,
13627             int restrictionFlags, int userId) {
13628         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS,
13629                 "setDistractingPackageRestrictionsAsUser");
13630
13631         final int callingUid = Binder.getCallingUid();
13632         if (callingUid != Process.ROOT_UID && callingUid != Process.SYSTEM_UID
13633                 && UserHandle.getUserId(callingUid) != userId) {
13634             throw new SecurityException("Calling uid " + callingUid + " cannot call for user "
13635                     + userId);
13636         }
13637         Preconditions.checkNotNull(packageNames, "packageNames cannot be null");
13638
13639         final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
13640         final IntArray changedUids = new IntArray(packageNames.length);
13641         final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13642         final boolean[] canRestrict = (restrictionFlags != 0) ? canSuspendPackageForUserInternal(
13643                 packageNames, userId) : null;
13644
13645         for (int i = 0; i < packageNames.length; i++) {
13646             final String packageName = packageNames[i];
13647             final PackageSetting pkgSetting;
13648             synchronized (mPackages) {
13649                 pkgSetting = mSettings.mPackages.get(packageName);
13650                 if (pkgSetting == null || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13651                     Slog.w(TAG, "Could not find package setting for package: " + packageName
13652                             + ". Skipping...");
13653                     unactionedPackages.add(packageName);
13654                     continue;
13655                 }
13656             }
13657             if (canRestrict != null && !canRestrict[i]) {
13658                 unactionedPackages.add(packageName);
13659                 continue;
13660             }
13661             synchronized (mPackages) {
13662                 final int oldDistractionFlags = pkgSetting.getDistractionFlags(userId);
13663                 if (restrictionFlags != oldDistractionFlags) {
13664                     pkgSetting.setDistractionFlags(restrictionFlags, userId);
13665                     changedPackagesList.add(packageName);
13666                     changedUids.add(UserHandle.getUid(userId, pkgSetting.appId));
13667                 }
13668             }
13669         }
13670
13671         if (!changedPackagesList.isEmpty()) {
13672             final String[] changedPackages = changedPackagesList.toArray(
13673                     new String[changedPackagesList.size()]);
13674             sendDistractingPackagesChanged(changedPackages, changedUids.toArray(), userId,
13675                     restrictionFlags);
13676             synchronized (mPackages) {
13677                 scheduleWritePackageRestrictionsLocked(userId);
13678             }
13679         }
13680         return unactionedPackages.toArray(new String[0]);
13681     }
13682
13683     private void enforceCanSetPackagesSuspendedAsUser(String callingPackage, int callingUid,
13684             int userId, String callingMethod) {
13685         if (callingUid == Process.ROOT_UID || callingUid == Process.SYSTEM_UID) {
13686             return;
13687         }
13688
13689         final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(userId);
13690         if (ownerPackage != null) {
13691             final int ownerUid = getPackageUid(ownerPackage, 0, userId);
13692             if (ownerUid == callingUid) {
13693                 return;
13694             }
13695             throw new UnsupportedOperationException("Cannot suspend/unsuspend packages. User "
13696                     + userId + " has an active DO or PO");
13697         }
13698
13699         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS,
13700                 callingMethod);
13701
13702         final int packageUid = getPackageUid(callingPackage, 0, userId);
13703         final boolean allowedPackageUid = packageUid == callingUid;
13704         final boolean allowedShell = callingUid == SHELL_UID
13705                 && UserHandle.isSameApp(packageUid, callingUid);
13706
13707         if (!allowedShell && !allowedPackageUid) {
13708             throw new SecurityException("Calling package " + callingPackage + " in user "
13709                     + userId + " does not belong to calling uid " + callingUid);
13710         }
13711     }
13712
13713     @Override
13714     public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended,
13715             PersistableBundle appExtras, PersistableBundle launcherExtras,
13716             SuspendDialogInfo dialogInfo, String callingPackage, int userId) {
13717         final int callingUid = Binder.getCallingUid();
13718         enforceCanSetPackagesSuspendedAsUser(callingPackage, callingUid, userId,
13719                 "setPackagesSuspendedAsUser");
13720
13721         if (ArrayUtils.isEmpty(packageNames)) {
13722             return packageNames;
13723         }
13724
13725         final List<String> changedPackagesList = new ArrayList<>(packageNames.length);
13726         final IntArray changedUids = new IntArray(packageNames.length);
13727         final List<String> unactionedPackages = new ArrayList<>(packageNames.length);
13728         final boolean[] canSuspend = suspended ? canSuspendPackageForUserInternal(packageNames,
13729                 userId) : null;
13730
13731         for (int i = 0; i < packageNames.length; i++) {
13732             final String packageName = packageNames[i];
13733             if (callingPackage.equals(packageName)) {
13734                 Slog.w(TAG, "Calling package: " + callingPackage + " trying to "
13735                         + (suspended ? "" : "un") + "suspend itself. Ignoring");
13736                 unactionedPackages.add(packageName);
13737                 continue;
13738             }
13739             final PackageSetting pkgSetting;
13740             synchronized (mPackages) {
13741                 pkgSetting = mSettings.mPackages.get(packageName);
13742                 if (pkgSetting == null || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
13743                     Slog.w(TAG, "Could not find package setting for package: " + packageName
13744                             + ". Skipping suspending/un-suspending.");
13745                     unactionedPackages.add(packageName);
13746                     continue;
13747                 }
13748             }
13749             if (canSuspend != null && !canSuspend[i]) {
13750                 unactionedPackages.add(packageName);
13751                 continue;
13752             }
13753             synchronized (mPackages) {
13754                 pkgSetting.setSuspended(suspended, callingPackage, dialogInfo, appExtras,
13755                         launcherExtras, userId);
13756             }
13757             changedPackagesList.add(packageName);
13758             changedUids.add(UserHandle.getUid(userId, pkgSetting.appId));
13759         }
13760
13761         if (!changedPackagesList.isEmpty()) {
13762             final String[] changedPackages = changedPackagesList.toArray(
13763                     new String[changedPackagesList.size()]);
13764             sendPackagesSuspendedForUser(
13765                     changedPackages, changedUids.toArray(), userId, suspended, launcherExtras);
13766             sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId);
13767             synchronized (mPackages) {
13768                 scheduleWritePackageRestrictionsLocked(userId);
13769             }
13770         }
13771         return unactionedPackages.toArray(new String[unactionedPackages.size()]);
13772     }
13773
13774     @Override
13775     public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) {
13776         final int callingUid = Binder.getCallingUid();
13777         if (getPackageUid(packageName, 0, userId) != callingUid) {
13778             throw new SecurityException("Calling package " + packageName
13779                     + " does not belong to calling uid " + callingUid);
13780         }
13781         synchronized (mPackages) {
13782             final PackageSetting ps = mSettings.mPackages.get(packageName);
13783             if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13784                 throw new IllegalArgumentException("Unknown target package: " + packageName);
13785             }
13786             final PackageUserState packageUserState = ps.readUserState(userId);
13787             if (packageUserState.suspended) {
13788                 return packageUserState.suspendedAppExtras;
13789             }
13790             return null;
13791         }
13792     }
13793
13794     private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended,
13795             PersistableBundle appExtras, int userId) {
13796         final String action;
13797         final Bundle intentExtras = new Bundle();
13798         if (suspended) {
13799             action = Intent.ACTION_MY_PACKAGE_SUSPENDED;
13800             if (appExtras != null) {
13801                 final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy());
13802                 intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras);
13803             }
13804         } else {
13805             action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED;
13806         }
13807         mHandler.post(() -> {
13808             try {
13809                 final IActivityManager am = ActivityManager.getService();
13810                 if (am == null) {
13811                     Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ "
13812                             + (suspended ? "" : "UN") + "SUSPENDED broadcasts");
13813                     return;
13814                 }
13815                 final int[] targetUserIds = new int[] {userId};
13816                 for (String packageName : affectedPackages) {
13817                     doSendBroadcast(am, action, null, intentExtras,
13818                             Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null,
13819                             targetUserIds, false);
13820                 }
13821             } catch (RemoteException ex) {
13822                 // Shouldn't happen as AMS is in the same process.
13823             }
13824         });
13825     }
13826
13827     @Override
13828     public boolean isPackageSuspendedForUser(String packageName, int userId) {
13829         final int callingUid = Binder.getCallingUid();
13830         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
13831                 true /* requireFullPermission */, false /* checkShell */,
13832                 "isPackageSuspendedForUser for user " + userId);
13833         synchronized (mPackages) {
13834             final PackageSetting ps = mSettings.mPackages.get(packageName);
13835             if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) {
13836                 throw new IllegalArgumentException("Unknown target package: " + packageName);
13837             }
13838             return ps.getSuspended(userId);
13839         }
13840     }
13841
13842     /**
13843      * Immediately unsuspends any packages suspended by the given package. To be called
13844      * when such a package's data is cleared or it is removed from the device.
13845      *
13846      * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk
13847      * synchronously
13848      *
13849      * @param packageName The package holding {@link Manifest.permission#SUSPEND_APPS} permission
13850      * @param affectedUser The user for which the changes are taking place.
13851      */
13852     void unsuspendForSuspendingPackage(final String packageName, int affectedUser) {
13853         final int[] userIds = (affectedUser == UserHandle.USER_ALL) ? sUserManager.getUserIds()
13854                 : new int[] {affectedUser};
13855         for (int userId : userIds) {
13856             unsuspendForSuspendingPackages(packageName::equals, userId);
13857         }
13858     }
13859
13860     /**
13861      * Immediately unsuspends any packages in the given users not suspended by the platform or root.
13862      * To be called when a profile owner or a device owner is added.
13863      *
13864      * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk
13865      * synchronously
13866      *
13867      * @param userIds The users for which to unsuspend packages
13868      */
13869     void unsuspendForNonSystemSuspendingPackages(ArraySet<Integer> userIds) {
13870         final int sz = userIds.size();
13871         for (int i = 0; i < sz; i++) {
13872             unsuspendForSuspendingPackages(
13873                     (suspendingPackage) -> !PLATFORM_PACKAGE_NAME.equals(suspendingPackage),
13874                     userIds.valueAt(i));
13875         }
13876     }
13877
13878     private void unsuspendForSuspendingPackages(Predicate<String> packagePredicate, int userId) {
13879         final List<String> affectedPackages = new ArrayList<>();
13880         final IntArray affectedUids = new IntArray();
13881         synchronized (mPackages) {
13882             for (PackageSetting ps : mSettings.mPackages.values()) {
13883                 final PackageUserState pus = ps.readUserState(userId);
13884                 if (pus.suspended && packagePredicate.test(pus.suspendingPackage)) {
13885                     ps.setSuspended(false, null, null, null, null, userId);
13886                     affectedPackages.add(ps.name);
13887                     affectedUids.add(UserHandle.getUid(userId, ps.getAppId()));
13888                 }
13889             }
13890         }
13891         if (!affectedPackages.isEmpty()) {
13892             final String[] packageArray = affectedPackages.toArray(
13893                     new String[affectedPackages.size()]);
13894             sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId);
13895             sendPackagesSuspendedForUser(
13896                     packageArray, affectedUids.toArray(), userId, false, null);
13897             // Write package restrictions immediately to avoid an inconsistent state.
13898             mSettings.writePackageRestrictionsLPr(userId);
13899         }
13900     }
13901
13902     @Override
13903     public String[] getUnsuspendablePackagesForUser(String[] packageNames, int userId) {
13904         Preconditions.checkNotNull("packageNames cannot be null", packageNames);
13905         mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS,
13906                 "getUnsuspendablePackagesForUser");
13907         final int callingUid = Binder.getCallingUid();
13908         if (UserHandle.getUserId(callingUid) != userId) {
13909             throw new SecurityException("Calling uid " + callingUid
13910                     + " cannot query getUnsuspendablePackagesForUser for user " + userId);
13911         }
13912         final ArraySet<String> unactionablePackages = new ArraySet<>();
13913         final boolean[] canSuspend = canSuspendPackageForUserInternal(packageNames, userId);
13914         for (int i = 0; i < packageNames.length; i++) {
13915             if (!canSuspend[i]) {
13916                 unactionablePackages.add(packageNames[i]);
13917             }
13918         }
13919         return unactionablePackages.toArray(new String[unactionablePackages.size()]);
13920     }
13921
13922     /**
13923      * Returns an array of booleans, such that the ith boolean denotes whether the ith package can
13924      * be suspended or not.
13925      *
13926      * @param packageNames  The package names to check suspendability for.
13927      * @param userId The user to check in
13928      * @return An array containing results of the checks
13929      */
13930     @NonNull
13931     private boolean[] canSuspendPackageForUserInternal(@NonNull String[] packageNames, int userId) {
13932         final boolean[] canSuspend = new boolean[packageNames.length];
13933         final long callingId = Binder.clearCallingIdentity();
13934         try {
13935             final String activeLauncherPackageName = getActiveLauncherPackageName(userId);
13936             final String dialerPackageName = getDefaultDialerPackageName(userId);
13937             for (int i = 0; i < packageNames.length; i++) {
13938                 canSuspend[i] = false;
13939                 final String packageName = packageNames[i];
13940
13941                 if (isPackageDeviceAdmin(packageName, userId)) {
13942                     Slog.w(TAG, "Cannot suspend package \"" + packageName
13943                             + "\": has an active device admin");
13944                     continue;
13945                 }
13946                 if (packageName.equals(activeLauncherPackageName)) {
13947                     Slog.w(TAG, "Cannot suspend package \"" + packageName
13948                             + "\": contains the active launcher");
13949                     continue;
13950                 }
13951                 if (packageName.equals(mRequiredInstallerPackage)) {
13952                     Slog.w(TAG, "Cannot suspend package \"" + packageName
13953                             + "\": required for package installation");
13954                     continue;
13955                 }
13956                 if (packageName.equals(mRequiredUninstallerPackage)) {
13957                     Slog.w(TAG, "Cannot suspend package \"" + packageName
13958                             + "\": required for package uninstallation");
13959                     continue;
13960                 }
13961                 if (packageName.equals(mRequiredVerifierPackage)) {
13962                     Slog.w(TAG, "Cannot suspend package \"" + packageName
13963                             + "\": required for package verification");
13964                     continue;
13965                 }
13966                 if (packageName.equals(dialerPackageName)) {
13967                     Slog.w(TAG, "Cannot suspend package \"" + packageName
13968                             + "\": is the default dialer");
13969                     continue;
13970                 }
13971                 if (packageName.equals(mRequiredPermissionControllerPackage)) {
13972                     Slog.w(TAG, "Cannot suspend package \"" + packageName
13973                             + "\": required for permissions management");
13974                     continue;
13975                 }
13976                 synchronized (mPackages) {
13977                     if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
13978                         Slog.w(TAG, "Cannot suspend package \"" + packageName
13979                                 + "\": protected package");
13980                         continue;
13981                     }
13982
13983                     // Cannot suspend static shared libs as they are considered
13984                     // a part of the using app (emulating static linking). Also
13985                     // static libs are installed always on internal storage.
13986                     PackageParser.Package pkg = mPackages.get(packageName);
13987                     if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) {
13988                         Slog.w(TAG, "Cannot suspend package: " + packageName
13989                                 + " providing static shared library: "
13990                                 + pkg.staticSharedLibName);
13991                         continue;
13992                     }
13993                 }
13994                 if (PLATFORM_PACKAGE_NAME.equals(packageName)) {
13995                     Slog.w(TAG, "Cannot suspend the platform package: " + packageName);
13996                     continue;
13997                 }
13998                 canSuspend[i] = true;
13999             }
14000         } finally {
14001             Binder.restoreCallingIdentity(callingId);
14002         }
14003         return canSuspend;
14004     }
14005
14006     private String getActiveLauncherPackageName(int userId) {
14007         Intent intent = new Intent(Intent.ACTION_MAIN);
14008         intent.addCategory(Intent.CATEGORY_HOME);
14009         ResolveInfo resolveInfo = resolveIntent(
14010                 intent,
14011                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
14012                 PackageManager.MATCH_DEFAULT_ONLY,
14013                 userId);
14014
14015         return resolveInfo == null ? null : resolveInfo.activityInfo.packageName;
14016     }
14017
14018     @Nullable
14019     private String getDefaultDialerPackageName(@UserIdInt int userId) {
14020         PackageManagerInternal.DefaultDialerProvider provider;
14021         synchronized (mPackages) {
14022             provider = mDefaultDialerProvider;
14023         }
14024         if (provider == null) {
14025             Slog.e(TAG, "mDefaultDialerProvider is null");
14026             return null;
14027         }
14028         return provider.getDefaultDialer(userId);
14029     }
14030
14031     @Override
14032     public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
14033         mContext.enforceCallingOrSelfPermission(
14034                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14035                 "Only package verification agents can verify applications");
14036
14037         final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14038         final PackageVerificationResponse response = new PackageVerificationResponse(
14039                 verificationCode, Binder.getCallingUid());
14040         msg.arg1 = id;
14041         msg.obj = response;
14042         mHandler.sendMessage(msg);
14043     }
14044
14045     @Override
14046     public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
14047             long millisecondsToDelay) {
14048         mContext.enforceCallingOrSelfPermission(
14049                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14050                 "Only package verification agents can extend verification timeouts");
14051
14052         final PackageVerificationState state = mPendingVerification.get(id);
14053         final PackageVerificationResponse response = new PackageVerificationResponse(
14054                 verificationCodeAtTimeout, Binder.getCallingUid());
14055
14056         if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
14057             millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
14058         }
14059         if (millisecondsToDelay < 0) {
14060             millisecondsToDelay = 0;
14061         }
14062         if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
14063                 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
14064             verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
14065         }
14066
14067         if ((state != null) && !state.timeoutExtended()) {
14068             state.extendTimeout();
14069
14070             final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
14071             msg.arg1 = id;
14072             msg.obj = response;
14073             mHandler.sendMessageDelayed(msg, millisecondsToDelay);
14074         }
14075     }
14076
14077     private void broadcastPackageVerified(int verificationId, Uri packageUri,
14078             int verificationCode, UserHandle user) {
14079         final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
14080         intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
14081         intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
14082         intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
14083         intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
14084
14085         mContext.sendBroadcastAsUser(intent, user,
14086                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
14087     }
14088
14089     private ComponentName matchComponentForVerifier(String packageName,
14090             List<ResolveInfo> receivers) {
14091         ActivityInfo targetReceiver = null;
14092
14093         final int NR = receivers.size();
14094         for (int i = 0; i < NR; i++) {
14095             final ResolveInfo info = receivers.get(i);
14096             if (info.activityInfo == null) {
14097                 continue;
14098             }
14099
14100             if (packageName.equals(info.activityInfo.packageName)) {
14101                 targetReceiver = info.activityInfo;
14102                 break;
14103             }
14104         }
14105
14106         if (targetReceiver == null) {
14107             return null;
14108         }
14109
14110         return new ComponentName(targetReceiver.packageName, targetReceiver.name);
14111     }
14112
14113     private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
14114             List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
14115         if (pkgInfo.verifiers.length == 0) {
14116             return null;
14117         }
14118
14119         final int N = pkgInfo.verifiers.length;
14120         final List<ComponentName> sufficientVerifiers = new ArrayList<>(N + 1);
14121         for (int i = 0; i < N; i++) {
14122             final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
14123
14124             final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
14125                     receivers);
14126             if (comp == null) {
14127                 continue;
14128             }
14129
14130             final int verifierUid = getUidForVerifier(verifierInfo);
14131             if (verifierUid == -1) {
14132                 continue;
14133             }
14134
14135             if (DEBUG_VERIFY) {
14136                 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
14137                         + " with the correct signature");
14138             }
14139             sufficientVerifiers.add(comp);
14140             verificationState.addSufficientVerifier(verifierUid);
14141         }
14142
14143         return sufficientVerifiers;
14144     }
14145
14146     private int getUidForVerifier(VerifierInfo verifierInfo) {
14147         synchronized (mPackages) {
14148             final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
14149             if (pkg == null) {
14150                 return -1;
14151             } else if (pkg.mSigningDetails.signatures.length != 1) {
14152                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14153                         + " has more than one signature; ignoring");
14154                 return -1;
14155             }
14156
14157             /*
14158              * If the public key of the package's signature does not match
14159              * our expected public key, then this is a different package and
14160              * we should skip.
14161              */
14162
14163             final byte[] expectedPublicKey;
14164             try {
14165                 final Signature verifierSig = pkg.mSigningDetails.signatures[0];
14166                 final PublicKey publicKey = verifierSig.getPublicKey();
14167                 expectedPublicKey = publicKey.getEncoded();
14168             } catch (CertificateException e) {
14169                 return -1;
14170             }
14171
14172             final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
14173
14174             if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
14175                 Slog.i(TAG, "Verifier package " + verifierInfo.packageName
14176                         + " does not have the expected public key; ignoring");
14177                 return -1;
14178             }
14179
14180             return pkg.applicationInfo.uid;
14181         }
14182     }
14183
14184     private void setEnableRollbackCode(int token, int enableRollbackCode) {
14185         final Message msg = mHandler.obtainMessage(ENABLE_ROLLBACK_STATUS);
14186         msg.arg1 = token;
14187         msg.arg2 = enableRollbackCode;
14188         mHandler.sendMessage(msg);
14189     }
14190
14191     @Override
14192     public void finishPackageInstall(int token, boolean didLaunch) {
14193         enforceSystemOrRoot("Only the system is allowed to finish installs");
14194
14195         if (DEBUG_INSTALL) {
14196             Slog.v(TAG, "BM finishing package install for " + token);
14197         }
14198         Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14199
14200         final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0);
14201         mHandler.sendMessage(msg);
14202     }
14203
14204     /**
14205      * Get the verification agent timeout.  Used for both the APK verifier and the
14206      * intent filter verifier.
14207      *
14208      * @return verification timeout in milliseconds
14209      */
14210     private long getVerificationTimeout() {
14211         return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
14212                 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
14213                 DEFAULT_VERIFICATION_TIMEOUT);
14214     }
14215
14216     /**
14217      * Get the default verification agent response code.
14218      *
14219      * @return default verification response code
14220      */
14221     private int getDefaultVerificationResponse(UserHandle user) {
14222         if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) {
14223             return PackageManager.VERIFICATION_REJECT;
14224         }
14225         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14226                 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
14227                 DEFAULT_VERIFICATION_RESPONSE);
14228     }
14229
14230     /**
14231      * Check whether or not package verification has been enabled.
14232      *
14233      * @return true if verification should be performed
14234      */
14235     private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) {
14236         if (!DEFAULT_VERIFY_ENABLE) {
14237             return false;
14238         }
14239
14240         if ((installFlags & PackageManager.INSTALL_DISABLE_VERIFICATION) != 0) {
14241             return false;
14242         }
14243
14244         boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
14245
14246         // Check if installing from ADB
14247         if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
14248             // Do not run verification in a test harness environment
14249             if (ActivityManager.isRunningInTestHarness()) {
14250                 return false;
14251             }
14252             if (ensureVerifyAppsEnabled) {
14253                 return true;
14254             }
14255             // Check if the developer does not want package verification for ADB installs
14256             if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14257                     android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
14258                 return false;
14259             }
14260         } else {
14261             // only when not installed from ADB, skip verification for instant apps when
14262             // the installer and verifier are the same.
14263             if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) {
14264                 if (mInstantAppInstallerActivity != null
14265                         && mInstantAppInstallerActivity.packageName.equals(
14266                                 mRequiredVerifierPackage)) {
14267                     try {
14268                         mContext.getSystemService(AppOpsManager.class)
14269                                 .checkPackage(installerUid, mRequiredVerifierPackage);
14270                         if (DEBUG_VERIFY) {
14271                             Slog.i(TAG, "disable verification for instant app");
14272                         }
14273                         return false;
14274                     } catch (SecurityException ignore) { }
14275                 }
14276             }
14277         }
14278
14279         if (ensureVerifyAppsEnabled) {
14280             return true;
14281         }
14282
14283         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14284                 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
14285     }
14286
14287     @Override
14288     public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
14289             throws RemoteException {
14290         mContext.enforceCallingOrSelfPermission(
14291                 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
14292                 "Only intentfilter verification agents can verify applications");
14293
14294         final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
14295         final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
14296                 Binder.getCallingUid(), verificationCode, failedDomains);
14297         msg.arg1 = id;
14298         msg.obj = response;
14299         mHandler.sendMessage(msg);
14300     }
14301
14302     @Override
14303     public int getIntentVerificationStatus(String packageName, int userId) {
14304         final int callingUid = Binder.getCallingUid();
14305         if (UserHandle.getUserId(callingUid) != userId) {
14306             mContext.enforceCallingOrSelfPermission(
14307                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
14308                     "getIntentVerificationStatus" + userId);
14309         }
14310         if (getInstantAppPackageName(callingUid) != null) {
14311             return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14312         }
14313         synchronized (mPackages) {
14314             final PackageSetting ps = mSettings.mPackages.get(packageName);
14315             if (ps == null
14316                     || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14317                 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
14318             }
14319             return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
14320         }
14321     }
14322
14323     @Override
14324     public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
14325         mContext.enforceCallingOrSelfPermission(
14326                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14327
14328         boolean result = false;
14329         synchronized (mPackages) {
14330             final PackageSetting ps = mSettings.mPackages.get(packageName);
14331             if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14332                 return false;
14333             }
14334             result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
14335         }
14336         if (result) {
14337             scheduleWritePackageRestrictionsLocked(userId);
14338         }
14339         return result;
14340     }
14341
14342     @Override
14343     public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications(
14344             String packageName) {
14345         final int callingUid = Binder.getCallingUid();
14346         if (getInstantAppPackageName(callingUid) != null) {
14347             return ParceledListSlice.emptyList();
14348         }
14349         synchronized (mPackages) {
14350             final PackageSetting ps = mSettings.mPackages.get(packageName);
14351             if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
14352                 return ParceledListSlice.emptyList();
14353             }
14354             return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName));
14355         }
14356     }
14357
14358     @Override
14359     public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) {
14360         if (TextUtils.isEmpty(packageName)) {
14361             return ParceledListSlice.emptyList();
14362         }
14363         final int callingUid = Binder.getCallingUid();
14364         final int callingUserId = UserHandle.getUserId(callingUid);
14365         synchronized (mPackages) {
14366             PackageParser.Package pkg = mPackages.get(packageName);
14367             if (pkg == null || pkg.activities == null) {
14368                 return ParceledListSlice.emptyList();
14369             }
14370             if (pkg.mExtras == null) {
14371                 return ParceledListSlice.emptyList();
14372             }
14373             final PackageSetting ps = (PackageSetting) pkg.mExtras;
14374             if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
14375                 return ParceledListSlice.emptyList();
14376             }
14377             final int count = pkg.activities.size();
14378             ArrayList<IntentFilter> result = new ArrayList<>();
14379             for (int n=0; n<count; n++) {
14380                 PackageParser.Activity activity = pkg.activities.get(n);
14381                 if (activity.intents != null && activity.intents.size() > 0) {
14382                     result.addAll(activity.intents);
14383                 }
14384             }
14385             return new ParceledListSlice<>(result);
14386         }
14387     }
14388
14389     @Override
14390     public boolean setDefaultBrowserPackageName(String packageName, int userId) {
14391         mContext.enforceCallingOrSelfPermission(
14392                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
14393         if (UserHandle.getCallingUserId() != userId) {
14394             mContext.enforceCallingOrSelfPermission(
14395                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14396         }
14397         if (userId == UserHandle.USER_ALL) {
14398             return false;
14399         }
14400         PackageManagerInternal.DefaultBrowserProvider provider;
14401         synchronized (mPackages) {
14402             provider = mDefaultBrowserProvider;
14403         }
14404         if (provider == null) {
14405             Slog.e(TAG, "mDefaultBrowserProvider is null");
14406             return false;
14407         }
14408         boolean successful = provider.setDefaultBrowser(packageName, userId);
14409         if (!successful) {
14410             return false;
14411         }
14412         if (packageName != null) {
14413             synchronized (mPackages) {
14414                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(packageName,
14415                         userId);
14416             }
14417         }
14418         return true;
14419     }
14420
14421     private void setDefaultBrowserAsyncLPw(@Nullable String packageName, @UserIdInt int userId) {
14422         if (userId == UserHandle.USER_ALL) {
14423             return;
14424         }
14425         if (mDefaultBrowserProvider == null) {
14426             Slog.e(TAG, "mDefaultBrowserProvider is null");
14427             return;
14428         }
14429         mDefaultBrowserProvider.setDefaultBrowserAsync(packageName, userId);
14430         if (packageName != null) {
14431             synchronized (mPackages) {
14432                 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(packageName,
14433                         userId);
14434             }
14435         }
14436     }
14437
14438     @Override
14439     public String getDefaultBrowserPackageName(int userId) {
14440         if (UserHandle.getCallingUserId() != userId) {
14441             mContext.enforceCallingOrSelfPermission(
14442                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
14443         }
14444         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14445             return null;
14446         }
14447         PackageManagerInternal.DefaultBrowserProvider provider;
14448         synchronized (mPackages) {
14449             provider = mDefaultBrowserProvider;
14450         }
14451         if (provider == null) {
14452             Slog.e(TAG, "mDefaultBrowserProvider is null");
14453             return null;
14454         }
14455         return provider.getDefaultBrowser(userId);
14456     }
14457
14458     /**
14459      * Get the "allow unknown sources" setting.
14460      *
14461      * @return the current "allow unknown sources" setting
14462      */
14463     private int getUnknownSourcesSettings() {
14464         return android.provider.Settings.Secure.getInt(mContext.getContentResolver(),
14465                 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS,
14466                 -1);
14467     }
14468
14469     @Override
14470     public void setInstallerPackageName(String targetPackage, String installerPackageName) {
14471         final int callingUid = Binder.getCallingUid();
14472         if (getInstantAppPackageName(callingUid) != null) {
14473             return;
14474         }
14475         // writer
14476         synchronized (mPackages) {
14477             PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
14478             if (targetPackageSetting == null
14479                     || filterAppAccessLPr(
14480                             targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) {
14481                 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
14482             }
14483
14484             PackageSetting installerPackageSetting;
14485             if (installerPackageName != null) {
14486                 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
14487                 if (installerPackageSetting == null) {
14488                     throw new IllegalArgumentException("Unknown installer package: "
14489                             + installerPackageName);
14490                 }
14491             } else {
14492                 installerPackageSetting = null;
14493             }
14494
14495             Signature[] callerSignature;
14496             final int appId = UserHandle.getAppId(callingUid);
14497             final Object obj = mSettings.getSettingLPr(appId);
14498             if (obj != null) {
14499                 if (obj instanceof SharedUserSetting) {
14500                     callerSignature =
14501                             ((SharedUserSetting)obj).signatures.mSigningDetails.signatures;
14502                 } else if (obj instanceof PackageSetting) {
14503                     callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures;
14504                 } else {
14505                     throw new SecurityException("Bad object " + obj + " for uid " + callingUid);
14506                 }
14507             } else {
14508                 throw new SecurityException("Unknown calling UID: " + callingUid);
14509             }
14510
14511             // Verify: can't set installerPackageName to a package that is
14512             // not signed with the same cert as the caller.
14513             if (installerPackageSetting != null) {
14514                 if (compareSignatures(callerSignature,
14515                         installerPackageSetting.signatures.mSigningDetails.signatures)
14516                         != PackageManager.SIGNATURE_MATCH) {
14517                     throw new SecurityException(
14518                             "Caller does not have same cert as new installer package "
14519                             + installerPackageName);
14520                 }
14521             }
14522
14523             // Verify: if target already has an installer package, it must
14524             // be signed with the same cert as the caller.
14525             if (targetPackageSetting.installerPackageName != null) {
14526                 PackageSetting setting = mSettings.mPackages.get(
14527                         targetPackageSetting.installerPackageName);
14528                 // If the currently set package isn't valid, then it's always
14529                 // okay to change it.
14530                 if (setting != null) {
14531                     if (compareSignatures(callerSignature,
14532                             setting.signatures.mSigningDetails.signatures)
14533                             != PackageManager.SIGNATURE_MATCH) {
14534                         throw new SecurityException(
14535                                 "Caller does not have same cert as old installer package "
14536                                 + targetPackageSetting.installerPackageName);
14537                     }
14538                 }
14539             }
14540
14541             // Okay!
14542             targetPackageSetting.installerPackageName = installerPackageName;
14543             if (installerPackageName != null) {
14544                 mSettings.mInstallerPackages.add(installerPackageName);
14545             }
14546             scheduleWriteSettingsLocked();
14547         }
14548     }
14549
14550     @Override
14551     public void setApplicationCategoryHint(String packageName, int categoryHint,
14552             String callerPackageName) {
14553         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
14554             throw new SecurityException("Instant applications don't have access to this method");
14555         }
14556         mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(),
14557                 callerPackageName);
14558         synchronized (mPackages) {
14559             PackageSetting ps = mSettings.mPackages.get(packageName);
14560             if (ps == null) {
14561                 throw new IllegalArgumentException("Unknown target package " + packageName);
14562             }
14563             if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
14564                 throw new IllegalArgumentException("Unknown target package " + packageName);
14565             }
14566             if (!Objects.equals(callerPackageName, ps.installerPackageName)) {
14567                 throw new IllegalArgumentException("Calling package " + callerPackageName
14568                         + " is not installer for " + packageName);
14569             }
14570
14571             if (ps.categoryHint != categoryHint) {
14572                 ps.categoryHint = categoryHint;
14573                 scheduleWriteSettingsLocked();
14574             }
14575         }
14576     }
14577
14578     private void processPendingInstall(final InstallArgs args, final int currentStatus) {
14579         if (args.mMultiPackageInstallParams != null) {
14580             args.mMultiPackageInstallParams.tryProcessInstallRequest(args, currentStatus);
14581         } else {
14582             PackageInstalledInfo res = createPackageInstalledInfo(currentStatus);
14583             processInstallRequestsAsync(
14584                     res.returnCode == PackageManager.INSTALL_SUCCEEDED,
14585                     Collections.singletonList(new InstallRequest(args, res)));
14586         }
14587     }
14588
14589     // Queue up an async operation since the package installation may take a little while.
14590     private void processInstallRequestsAsync(boolean success,
14591             List<InstallRequest> installRequests) {
14592         mHandler.post(() -> {
14593             if (success) {
14594                 for (InstallRequest request : installRequests) {
14595                     request.args.doPreInstall(request.installResult.returnCode);
14596                 }
14597                 synchronized (mInstallLock) {
14598                     installPackagesTracedLI(installRequests);
14599                 }
14600                 for (InstallRequest request : installRequests) {
14601                     request.args.doPostInstall(
14602                             request.installResult.returnCode, request.installResult.uid);
14603                 }
14604             }
14605             for (InstallRequest request : installRequests) {
14606                 restoreAndPostInstall(request.args.user.getIdentifier(), request.installResult,
14607                         new PostInstallData(request.args, request.installResult, null));
14608             }
14609         });
14610     }
14611
14612     private PackageInstalledInfo createPackageInstalledInfo(
14613             int currentStatus) {
14614         PackageInstalledInfo res = new PackageInstalledInfo();
14615         res.setReturnCode(currentStatus);
14616         res.uid = -1;
14617         res.pkg = null;
14618         res.removedInfo = null;
14619         return res;
14620     }
14621
14622     /** @param data Post-install is performed only if this is non-null. */
14623     private void restoreAndPostInstall(
14624             int userId, PackageInstalledInfo res, @Nullable PostInstallData data) {
14625         if (DEBUG_INSTALL) {
14626             Log.v(TAG, "restoreAndPostInstall userId=" + userId + " package="
14627                     + res.pkg.packageName);
14628         }
14629
14630         // A restore should be performed at this point if (a) the install
14631         // succeeded, (b) the operation is not an update, and (c) the new
14632         // package has not opted out of backup participation.
14633         final boolean update = res.removedInfo != null
14634                 && res.removedInfo.removedPackage != null;
14635         final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
14636         boolean doRestore = !update
14637                 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
14638
14639         // Set up the post-install work request bookkeeping.  This will be used
14640         // and cleaned up by the post-install event handling regardless of whether
14641         // there's a restore pass performed.  Token values are >= 1.
14642         int token;
14643         if (mNextInstallToken < 0) mNextInstallToken = 1;
14644         token = mNextInstallToken++;
14645         if (data != null) {
14646             mRunningInstalls.put(token, data);
14647         } else if (DEBUG_INSTALL) {
14648             Log.v(TAG, "No post-install required for " + token);
14649         }
14650
14651         if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
14652
14653         if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
14654             // Pass responsibility to the Backup Manager.  It will perform a
14655             // restore if appropriate, then pass responsibility back to the
14656             // Package Manager to run the post-install observer callbacks
14657             // and broadcasts.
14658             IBackupManager bm = IBackupManager.Stub.asInterface(
14659                     ServiceManager.getService(Context.BACKUP_SERVICE));
14660             if (bm != null) {
14661                 // For backwards compatibility as USER_ALL previously routed directly to USER_SYSTEM
14662                 // in the BackupManager. USER_ALL is used in compatibility tests.
14663                 if (userId == UserHandle.USER_ALL) {
14664                     userId = UserHandle.USER_SYSTEM;
14665                 }
14666                 if (DEBUG_INSTALL) {
14667                     Log.v(TAG, "token " + token + " to BM for possible restore for user " + userId);
14668                 }
14669                 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token);
14670                 try {
14671                     if (bm.isBackupServiceActive(userId)) {
14672                         bm.restoreAtInstallForUser(
14673                                 userId, res.pkg.applicationInfo.packageName, token);
14674                     } else {
14675                         doRestore = false;
14676                     }
14677                 } catch (RemoteException e) {
14678                     // can't happen; the backup manager is local
14679                 } catch (Exception e) {
14680                     Slog.e(TAG, "Exception trying to enqueue restore", e);
14681                     doRestore = false;
14682                 }
14683             } else {
14684                 Slog.e(TAG, "Backup Manager not found!");
14685                 doRestore = false;
14686             }
14687         }
14688
14689         // If this is an update to a package that might be potentially downgraded, then we
14690         // need to check with the rollback manager whether there's any userdata that might
14691         // need to be restored for the package.
14692         //
14693         // TODO(narayan): Get this working for cases where userId == UserHandle.USER_ALL.
14694         if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && !doRestore && update) {
14695             IRollbackManager rm = IRollbackManager.Stub.asInterface(
14696                     ServiceManager.getService(Context.ROLLBACK_SERVICE));
14697
14698             final String packageName = res.pkg.applicationInfo.packageName;
14699             final String seInfo = res.pkg.applicationInfo.seInfo;
14700             final int[] allUsers = sUserManager.getUserIds();
14701             final int[] installedUsers;
14702
14703             final PackageSetting ps;
14704             int appId = -1;
14705             long ceDataInode = -1;
14706             synchronized (mSettings) {
14707                 ps = mSettings.getPackageLPr(packageName);
14708                 if (ps != null) {
14709                     appId = ps.appId;
14710                     ceDataInode = ps.getCeDataInode(userId);
14711                 }
14712
14713                 // NOTE: We ignore the user specified in the InstallParam because we know this is
14714                 // an update, and hence need to restore data for all installed users.
14715                 installedUsers = ps.queryInstalledUsers(allUsers, true);
14716             }
14717
14718             if (ps != null) {
14719                 try {
14720                     rm.snapshotAndRestoreUserData(packageName, installedUsers, appId, ceDataInode,
14721                             seInfo, token);
14722                 } catch (RemoteException re) {
14723                     // Cannot happen, the RollbackManager is hosted in the same process.
14724                 }
14725                 doRestore = true;
14726             }
14727         }
14728
14729         if (!doRestore) {
14730             // No restore possible, or the Backup Manager was mysteriously not
14731             // available -- just fire the post-install work request directly.
14732             if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
14733
14734             Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
14735
14736             Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
14737             mHandler.sendMessage(msg);
14738         }
14739     }
14740
14741     /**
14742      * Callback from PackageSettings whenever an app is first transitioned out of the
14743      * 'stopped' state.  Normally we just issue the broadcast, but we can't do that if
14744      * the app was "launched" for a restoreAtInstall operation.  Therefore we check
14745      * here whether the app is the target of an ongoing install, and only send the
14746      * broadcast immediately if it is not in that state.  If it *is* undergoing a restore,
14747      * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL
14748      * handling.
14749      */
14750     void notifyFirstLaunch(final String packageName, final String installerPackage,
14751             final int userId) {
14752         // Serialize this with the rest of the install-process message chain.  In the
14753         // restore-at-install case, this Runnable will necessarily run before the
14754         // POST_INSTALL message is processed, so the contents of mRunningInstalls
14755         // are coherent.  In the non-restore case, the app has already completed install
14756         // and been launched through some other means, so it is not in a problematic
14757         // state for observers to see the FIRST_LAUNCH signal.
14758         mHandler.post(() -> {
14759             for (int i = 0; i < mRunningInstalls.size(); i++) {
14760                 final PostInstallData data = mRunningInstalls.valueAt(i);
14761                 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
14762                     continue;
14763                 }
14764                 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) {
14765                     // right package; but is it for the right user?
14766                     for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) {
14767                         if (userId == data.res.newUsers[uIndex]) {
14768                             if (DEBUG_BACKUP) {
14769                                 Slog.i(TAG, "Package " + packageName
14770                                         + " being restored so deferring FIRST_LAUNCH");
14771                             }
14772                             return;
14773                         }
14774                     }
14775                 }
14776             }
14777             // didn't find it, so not being restored
14778             if (DEBUG_BACKUP) {
14779                 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH");
14780             }
14781             final boolean isInstantApp = isInstantApp(packageName, userId);
14782             final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
14783             final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
14784             sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds);
14785         });
14786     }
14787
14788     private void sendFirstLaunchBroadcast(String pkgName, String installerPkg,
14789             int[] userIds, int[] instantUserIds) {
14790         sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0,
14791                 installerPkg, null, userIds, instantUserIds);
14792     }
14793
14794     private abstract class HandlerParams {
14795         /** User handle for the user requesting the information or installation. */
14796         private final UserHandle mUser;
14797         String traceMethod;
14798         int traceCookie;
14799
14800         HandlerParams(UserHandle user) {
14801             mUser = user;
14802         }
14803
14804         UserHandle getUser() {
14805             return mUser;
14806         }
14807
14808         /**
14809          * Gets the user handle for the user that the rollback agent should
14810          * use to look up information about this installation when enabling
14811          * rollback.
14812          */
14813         UserHandle getRollbackUser() {
14814             // The session for packages installed for "all" users is
14815             // associated with the "system" user.
14816             if (mUser == UserHandle.ALL) {
14817                 return UserHandle.SYSTEM;
14818             }
14819             return mUser;
14820         }
14821
14822         HandlerParams setTraceMethod(String traceMethod) {
14823             this.traceMethod = traceMethod;
14824             return this;
14825         }
14826
14827         HandlerParams setTraceCookie(int traceCookie) {
14828             this.traceCookie = traceCookie;
14829             return this;
14830         }
14831
14832         final void startCopy() {
14833             if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
14834             handleStartCopy();
14835             handleReturnCode();
14836         }
14837
14838         abstract void handleStartCopy();
14839         abstract void handleReturnCode();
14840     }
14841
14842     static class OriginInfo {
14843         /**
14844          * Location where install is coming from, before it has been
14845          * copied/renamed into place. This could be a single monolithic APK
14846          * file, or a cluster directory. This location may be untrusted.
14847          */
14848         final File file;
14849
14850         /**
14851          * Flag indicating that {@link #file} has already been staged, meaning downstream users
14852          * don't need to defensively copy the contents.
14853          */
14854         final boolean staged;
14855
14856         /**
14857          * Flag indicating that {@link #file} is an already installed app that is being moved.
14858          */
14859         final boolean existing;
14860
14861         final String resolvedPath;
14862         final File resolvedFile;
14863
14864         static OriginInfo fromNothing() {
14865             return new OriginInfo(null, false, false);
14866         }
14867
14868         static OriginInfo fromUntrustedFile(File file) {
14869             return new OriginInfo(file, false, false);
14870         }
14871
14872         static OriginInfo fromExistingFile(File file) {
14873             return new OriginInfo(file, false, true);
14874         }
14875
14876         static OriginInfo fromStagedFile(File file) {
14877             return new OriginInfo(file, true, false);
14878         }
14879
14880         private OriginInfo(File file, boolean staged, boolean existing) {
14881             this.file = file;
14882             this.staged = staged;
14883             this.existing = existing;
14884
14885             if (file != null) {
14886                 resolvedPath = file.getAbsolutePath();
14887                 resolvedFile = file;
14888             } else {
14889                 resolvedPath = null;
14890                 resolvedFile = null;
14891             }
14892         }
14893     }
14894
14895     static class MoveInfo {
14896         final int moveId;
14897         final String fromUuid;
14898         final String toUuid;
14899         final String packageName;
14900         final String dataAppName;
14901         final int appId;
14902         final String seinfo;
14903         final int targetSdkVersion;
14904
14905         public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
14906                 String dataAppName, int appId, String seinfo, int targetSdkVersion) {
14907             this.moveId = moveId;
14908             this.fromUuid = fromUuid;
14909             this.toUuid = toUuid;
14910             this.packageName = packageName;
14911             this.dataAppName = dataAppName;
14912             this.appId = appId;
14913             this.seinfo = seinfo;
14914             this.targetSdkVersion = targetSdkVersion;
14915         }
14916     }
14917
14918     static class VerificationInfo {
14919         /** A constant used to indicate that a uid value is not present. */
14920         public static final int NO_UID = -1;
14921
14922         /** URI referencing where the package was downloaded from. */
14923         final Uri originatingUri;
14924
14925         /** HTTP referrer URI associated with the originatingURI. */
14926         final Uri referrer;
14927
14928         /** UID of the application that the install request originated from. */
14929         final int originatingUid;
14930
14931         /** UID of application requesting the install */
14932         final int installerUid;
14933
14934         VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) {
14935             this.originatingUri = originatingUri;
14936             this.referrer = referrer;
14937             this.originatingUid = originatingUid;
14938             this.installerUid = installerUid;
14939         }
14940     }
14941
14942     /**
14943      * Container for a multi-package install which refers to all install sessions and args being
14944      * committed together.
14945      */
14946     class MultiPackageInstallParams extends HandlerParams {
14947
14948         private int mRet = INSTALL_SUCCEEDED;
14949         @NonNull
14950         private final ArrayList<InstallParams> mChildParams;
14951         @NonNull
14952         private final Map<InstallArgs, Integer> mCurrentState;
14953
14954         MultiPackageInstallParams(
14955                 @NonNull UserHandle user,
14956                 @NonNull List<ActiveInstallSession> activeInstallSessions)
14957                 throws PackageManagerException {
14958             super(user);
14959             if (activeInstallSessions.size() == 0) {
14960                 throw new PackageManagerException("No child sessions found!");
14961             }
14962             mChildParams = new ArrayList<>(activeInstallSessions.size());
14963             for (int i = 0; i < activeInstallSessions.size(); i++) {
14964                 final InstallParams childParams = new InstallParams(activeInstallSessions.get(i));
14965                 childParams.mParentInstallParams = this;
14966                 this.mChildParams.add(childParams);
14967             }
14968             this.mCurrentState = new ArrayMap<>(mChildParams.size());
14969         }
14970
14971         @Override
14972         void handleStartCopy() {
14973             for (InstallParams params : mChildParams) {
14974                 params.handleStartCopy();
14975                 if (params.mRet != INSTALL_SUCCEEDED) {
14976                     mRet = params.mRet;
14977                 }
14978             }
14979         }
14980
14981         @Override
14982         void handleReturnCode() {
14983             for (InstallParams params : mChildParams) {
14984                 params.handleReturnCode();
14985                 if (params.mRet != INSTALL_SUCCEEDED) {
14986                     mRet = params.mRet;
14987                 }
14988             }
14989         }
14990
14991         void tryProcessInstallRequest(InstallArgs args, int currentStatus) {
14992             mCurrentState.put(args, currentStatus);
14993             if (mCurrentState.size() != mChildParams.size()) {
14994                 return;
14995             }
14996             int completeStatus = PackageManager.INSTALL_SUCCEEDED;
14997             for (Integer status : mCurrentState.values()) {
14998                 if (status == PackageManager.INSTALL_UNKNOWN) {
14999                     return;
15000                 } else if (status != PackageManager.INSTALL_SUCCEEDED) {
15001                     completeStatus = status;
15002                     break;
15003                 }
15004             }
15005             final List<InstallRequest> installRequests = new ArrayList<>(mCurrentState.size());
15006             for (Map.Entry<InstallArgs, Integer> entry : mCurrentState.entrySet()) {
15007                 installRequests.add(new InstallRequest(entry.getKey(),
15008                         createPackageInstalledInfo(completeStatus)));
15009             }
15010             processInstallRequestsAsync(
15011                     completeStatus == PackageManager.INSTALL_SUCCEEDED,
15012                     installRequests);
15013         }
15014     }
15015
15016     class InstallParams extends HandlerParams {
15017         // TODO: see if we can collapse this into ActiveInstallSession
15018
15019         final OriginInfo origin;
15020         final MoveInfo move;
15021         final IPackageInstallObserver2 observer;
15022         int installFlags;
15023         final String installerPackageName;
15024         final String volumeUuid;
15025         private boolean mVerificationCompleted;
15026         private boolean mEnableRollbackCompleted;
15027         private InstallArgs mArgs;
15028         int mRet;
15029         final String packageAbiOverride;
15030         final String[] grantedRuntimePermissions;
15031         final List<String> whitelistedRestrictedPermissions;
15032         final VerificationInfo verificationInfo;
15033         final PackageParser.SigningDetails signingDetails;
15034         final int installReason;
15035         @Nullable
15036         MultiPackageInstallParams mParentInstallParams;
15037         final long requiredInstalledVersionCode;
15038
15039         InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15040                 int installFlags, String installerPackageName, String volumeUuid,
15041                 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride,
15042                 String[] grantedPermissions, List<String> whitelistedRestrictedPermissions,
15043                 PackageParser.SigningDetails signingDetails, int installReason,
15044                 long requiredInstalledVersionCode) {
15045             super(user);
15046             this.origin = origin;
15047             this.move = move;
15048             this.observer = observer;
15049             this.installFlags = installFlags;
15050             this.installerPackageName = installerPackageName;
15051             this.volumeUuid = volumeUuid;
15052             this.verificationInfo = verificationInfo;
15053             this.packageAbiOverride = packageAbiOverride;
15054             this.grantedRuntimePermissions = grantedPermissions;
15055             this.whitelistedRestrictedPermissions = whitelistedRestrictedPermissions;
15056             this.signingDetails = signingDetails;
15057             this.installReason = installReason;
15058             this.requiredInstalledVersionCode = requiredInstalledVersionCode;
15059         }
15060
15061         InstallParams(ActiveInstallSession activeInstallSession) {
15062             super(activeInstallSession.getUser());
15063             if (DEBUG_INSTANT) {
15064                 if ((activeInstallSession.getSessionParams().installFlags
15065                         & PackageManager.INSTALL_INSTANT_APP) != 0) {
15066                     Slog.d(TAG, "Ephemeral install of " + activeInstallSession.getPackageName());
15067                 }
15068             }
15069             verificationInfo = new VerificationInfo(
15070                     activeInstallSession.getSessionParams().originatingUri,
15071                     activeInstallSession.getSessionParams().referrerUri,
15072                     activeInstallSession.getSessionParams().originatingUid,
15073                     activeInstallSession.getInstallerUid());
15074             origin = OriginInfo.fromStagedFile(activeInstallSession.getStagedDir());
15075             move = null;
15076             installReason = fixUpInstallReason(activeInstallSession.getInstallerPackageName(),
15077                     activeInstallSession.getInstallerUid(),
15078                     activeInstallSession.getSessionParams().installReason);
15079             observer = activeInstallSession.getObserver();
15080             installFlags = activeInstallSession.getSessionParams().installFlags;
15081             installerPackageName = activeInstallSession.getInstallerPackageName();
15082             volumeUuid = activeInstallSession.getSessionParams().volumeUuid;
15083             packageAbiOverride = activeInstallSession.getSessionParams().abiOverride;
15084             grantedRuntimePermissions = activeInstallSession.getSessionParams()
15085                     .grantedRuntimePermissions;
15086             whitelistedRestrictedPermissions = activeInstallSession.getSessionParams()
15087                     .whitelistedRestrictedPermissions;
15088             signingDetails = activeInstallSession.getSigningDetails();
15089             requiredInstalledVersionCode = activeInstallSession.getSessionParams()
15090                     .requiredInstalledVersionCode;
15091         }
15092
15093         @Override
15094         public String toString() {
15095             return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
15096                     + " file=" + origin.file + "}";
15097         }
15098
15099         private int installLocationPolicy(PackageInfoLite pkgLite) {
15100             String packageName = pkgLite.packageName;
15101             int installLocation = pkgLite.installLocation;
15102             // reader
15103             synchronized (mPackages) {
15104                 // Currently installed package which the new package is attempting to replace or
15105                 // null if no such package is installed.
15106                 PackageParser.Package installedPkg = mPackages.get(packageName);
15107                 // Package which currently owns the data which the new package will own if installed.
15108                 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg
15109                 // will be null whereas dataOwnerPkg will contain information about the package
15110                 // which was uninstalled while keeping its data.
15111                 PackageParser.Package dataOwnerPkg = installedPkg;
15112                 if (dataOwnerPkg  == null) {
15113                     PackageSetting ps = mSettings.mPackages.get(packageName);
15114                     if (ps != null) {
15115                         dataOwnerPkg = ps.pkg;
15116                     }
15117                 }
15118
15119                 if (requiredInstalledVersionCode != PackageManager.VERSION_CODE_HIGHEST) {
15120                     if (dataOwnerPkg == null) {
15121                         Slog.w(TAG, "Required installed version code was "
15122                                 + requiredInstalledVersionCode
15123                                 + " but package is not installed");
15124                         return PackageHelper.RECOMMEND_FAILED_WRONG_INSTALLED_VERSION;
15125                     }
15126
15127                     if (dataOwnerPkg.getLongVersionCode() != requiredInstalledVersionCode) {
15128                         Slog.w(TAG, "Required installed version code was "
15129                                 + requiredInstalledVersionCode
15130                                 + " but actual installed version is "
15131                                 + dataOwnerPkg.getLongVersionCode());
15132                         return PackageHelper.RECOMMEND_FAILED_WRONG_INSTALLED_VERSION;
15133                     }
15134                 }
15135
15136                 if (dataOwnerPkg != null) {
15137                     if (!PackageManagerServiceUtils.isDowngradePermitted(installFlags,
15138                             dataOwnerPkg.applicationInfo.flags)) {
15139                         try {
15140                             checkDowngrade(dataOwnerPkg, pkgLite);
15141                         } catch (PackageManagerException e) {
15142                             Slog.w(TAG, "Downgrade detected: " + e.getMessage());
15143                             return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
15144                         }
15145                     }
15146                 }
15147
15148                 if (installedPkg != null) {
15149                     if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
15150                         // Check for updated system application.
15151                         if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
15152                             return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15153                         } else {
15154                             // If current upgrade specifies particular preference
15155                             if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
15156                                 // Application explicitly specified internal.
15157                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15158                             } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
15159                                 // App explictly prefers external. Let policy decide
15160                             } else {
15161                                 // Prefer previous location
15162                                 if (isExternal(installedPkg)) {
15163                                     return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
15164                                 }
15165                                 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
15166                             }
15167                         }
15168                     } else {
15169                         // Invalid install. Return error code
15170                         return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
15171                     }
15172                 }
15173             }
15174             return pkgLite.recommendedInstallLocation;
15175         }
15176
15177         /*
15178          * Invoke remote method to get package information and install
15179          * location values. Override install location based on default
15180          * policy if needed and then create install arguments based
15181          * on the install location.
15182          */
15183         public void handleStartCopy() {
15184             int ret = PackageManager.INSTALL_SUCCEEDED;
15185
15186             // If we're already staged, we've firmly committed to an install location
15187             if (origin.staged) {
15188                 if (origin.file != null) {
15189                     installFlags |= PackageManager.INSTALL_INTERNAL;
15190                 } else {
15191                     throw new IllegalStateException("Invalid stage location");
15192                 }
15193             }
15194
15195             final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
15196             final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15197             PackageInfoLite pkgLite = null;
15198
15199
15200             pkgLite = PackageManagerServiceUtils.getMinimalPackageInfo(mContext,
15201                     origin.resolvedPath, installFlags, packageAbiOverride);
15202
15203             if (DEBUG_INSTANT && ephemeral) {
15204                 Slog.v(TAG, "pkgLite for install: " + pkgLite);
15205             }
15206
15207             /*
15208              * If we have too little free space, try to free cache
15209              * before giving up.
15210              */
15211             if (!origin.staged && pkgLite.recommendedInstallLocation
15212                     == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15213                 // TODO: focus freeing disk space on the target device
15214                 final StorageManager storage = StorageManager.from(mContext);
15215                 final long lowThreshold = storage.getStorageLowBytes(
15216                         Environment.getDataDirectory());
15217
15218                 final long sizeBytes = PackageManagerServiceUtils.calculateInstalledSize(
15219                         origin.resolvedPath, packageAbiOverride);
15220                 if (sizeBytes >= 0) {
15221                     try {
15222                         mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
15223                         pkgLite = PackageManagerServiceUtils.getMinimalPackageInfo(mContext,
15224                                 origin.resolvedPath, installFlags, packageAbiOverride);
15225                     } catch (InstallerException e) {
15226                         Slog.w(TAG, "Failed to free cache", e);
15227                     }
15228                 }
15229
15230                 /*
15231                  * The cache free must have deleted the file we downloaded to install.
15232                  *
15233                  * TODO: fix the "freeCache" call to not delete the file we care about.
15234                  */
15235                 if (pkgLite.recommendedInstallLocation
15236                         == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15237                     pkgLite.recommendedInstallLocation
15238                             = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
15239                 }
15240             }
15241
15242
15243             if (ret == PackageManager.INSTALL_SUCCEEDED) {
15244                 int loc = pkgLite.recommendedInstallLocation;
15245                 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
15246                     ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
15247                 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
15248                     ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
15249                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
15250                     ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15251                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
15252                     ret = PackageManager.INSTALL_FAILED_INVALID_APK;
15253                 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
15254                     ret = PackageManager.INSTALL_FAILED_INVALID_URI;
15255                 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
15256                     ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
15257                 } else {
15258                     // Override with defaults if needed.
15259                     loc = installLocationPolicy(pkgLite);
15260                     if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
15261                         ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
15262                     } else if (loc == PackageHelper.RECOMMEND_FAILED_WRONG_INSTALLED_VERSION) {
15263                         ret = PackageManager.INSTALL_FAILED_WRONG_INSTALLED_VERSION;
15264                     } else if (!onInt) {
15265                         // Override install location with flags
15266                         if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
15267                             // Set the flag to install on external media.
15268                             installFlags &= ~PackageManager.INSTALL_INTERNAL;
15269                         } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
15270                             if (DEBUG_INSTANT) {
15271                                 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
15272                             }
15273                             installFlags |= PackageManager.INSTALL_INSTANT_APP;
15274                             installFlags &= ~PackageManager.INSTALL_INTERNAL;
15275                         } else {
15276                             // Make sure the flag for installing on external
15277                             // media is unset
15278                             installFlags |= PackageManager.INSTALL_INTERNAL;
15279                         }
15280                     }
15281                 }
15282             }
15283
15284             final InstallArgs args = createInstallArgs(this);
15285             mVerificationCompleted = true;
15286             mEnableRollbackCompleted = true;
15287             mArgs = args;
15288
15289             if (ret == PackageManager.INSTALL_SUCCEEDED) {
15290                 // TODO: http://b/22976637
15291                 // Apps installed for "all" users use the device owner to verify the app
15292                 UserHandle verifierUser = getUser();
15293                 if (verifierUser == UserHandle.ALL) {
15294                     verifierUser = UserHandle.SYSTEM;
15295                 }
15296
15297                 /*
15298                  * Determine if we have any installed package verifiers. If we
15299                  * do, then we'll defer to them to verify the packages.
15300                  */
15301                 final int requiredUid = mRequiredVerifierPackage == null ? -1
15302                         : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
15303                                 verifierUser.getIdentifier());
15304                 final int installerUid =
15305                         verificationInfo == null ? -1 : verificationInfo.installerUid;
15306                 if (!origin.existing && requiredUid != -1
15307                         && isVerificationEnabled(
15308                                 verifierUser.getIdentifier(), installFlags, installerUid)) {
15309                     final Intent verification = new Intent(
15310                             Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
15311                     verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
15312                     verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15313                             PACKAGE_MIME_TYPE);
15314                     verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15315
15316                     // Query all live verifiers based on current user state
15317                     final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification,
15318                             PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(),
15319                             false /*allowDynamicSplits*/);
15320
15321                     if (DEBUG_VERIFY) {
15322                         Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
15323                                 + verification.toString() + " with " + pkgLite.verifiers.length
15324                                 + " optional verifiers");
15325                     }
15326
15327                     final int verificationId = mPendingVerificationToken++;
15328
15329                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
15330
15331                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
15332                             installerPackageName);
15333
15334                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
15335                             installFlags);
15336
15337                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
15338                             pkgLite.packageName);
15339
15340                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
15341                             pkgLite.versionCode);
15342
15343                     verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE,
15344                             pkgLite.getLongVersionCode());
15345
15346                     if (verificationInfo != null) {
15347                         if (verificationInfo.originatingUri != null) {
15348                             verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
15349                                     verificationInfo.originatingUri);
15350                         }
15351                         if (verificationInfo.referrer != null) {
15352                             verification.putExtra(Intent.EXTRA_REFERRER,
15353                                     verificationInfo.referrer);
15354                         }
15355                         if (verificationInfo.originatingUid >= 0) {
15356                             verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
15357                                     verificationInfo.originatingUid);
15358                         }
15359                         if (verificationInfo.installerUid >= 0) {
15360                             verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
15361                                     verificationInfo.installerUid);
15362                         }
15363                     }
15364
15365                     final PackageVerificationState verificationState = new PackageVerificationState(
15366                             requiredUid, this);
15367
15368                     mPendingVerification.append(verificationId, verificationState);
15369
15370                     final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
15371                             receivers, verificationState);
15372
15373                     DeviceIdleController.LocalService idleController = getDeviceIdleController();
15374                     final long idleDuration = getVerificationTimeout();
15375
15376                     /*
15377                      * If any sufficient verifiers were listed in the package
15378                      * manifest, attempt to ask them.
15379                      */
15380                     if (sufficientVerifiers != null) {
15381                         final int N = sufficientVerifiers.size();
15382                         if (N == 0) {
15383                             Slog.i(TAG, "Additional verifiers required, but none installed.");
15384                             ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
15385                         } else {
15386                             for (int i = 0; i < N; i++) {
15387                                 final ComponentName verifierComponent = sufficientVerifiers.get(i);
15388                                 idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15389                                         verifierComponent.getPackageName(), idleDuration,
15390                                         verifierUser.getIdentifier(), false, "package verifier");
15391
15392                                 final Intent sufficientIntent = new Intent(verification);
15393                                 sufficientIntent.setComponent(verifierComponent);
15394                                 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser);
15395                             }
15396                         }
15397                     }
15398
15399                     final ComponentName requiredVerifierComponent = matchComponentForVerifier(
15400                             mRequiredVerifierPackage, receivers);
15401                     if (ret == PackageManager.INSTALL_SUCCEEDED
15402                             && mRequiredVerifierPackage != null) {
15403                         Trace.asyncTraceBegin(
15404                                 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId);
15405                         /*
15406                          * Send the intent to the required verification agent,
15407                          * but only start the verification timeout after the
15408                          * target BroadcastReceivers have run.
15409                          */
15410                         verification.setComponent(requiredVerifierComponent);
15411                         idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
15412                                 mRequiredVerifierPackage, idleDuration,
15413                                 verifierUser.getIdentifier(), false, "package verifier");
15414                         mContext.sendOrderedBroadcastAsUser(verification, verifierUser,
15415                                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
15416                                 new BroadcastReceiver() {
15417                                     @Override
15418                                     public void onReceive(Context context, Intent intent) {
15419                                         final Message msg = mHandler
15420                                                 .obtainMessage(CHECK_PENDING_VERIFICATION);
15421                                         msg.arg1 = verificationId;
15422                                         mHandler.sendMessageDelayed(msg, getVerificationTimeout());
15423                                     }
15424                                 }, null, 0, null, null);
15425
15426                         /*
15427                          * We don't want the copy to proceed until verification
15428                          * succeeds.
15429                          */
15430                         mVerificationCompleted = false;
15431                     }
15432                 }
15433
15434                 if ((installFlags & PackageManager.INSTALL_ENABLE_ROLLBACK) != 0) {
15435                     // TODO(ruhler) b/112431924: Don't do this in case of 'move'?
15436                     final int enableRollbackToken = mPendingEnableRollbackToken++;
15437                     Trace.asyncTraceBegin(
15438                             TRACE_TAG_PACKAGE_MANAGER, "enable_rollback", enableRollbackToken);
15439                     mPendingEnableRollback.append(enableRollbackToken, this);
15440
15441                     final int[] installedUsers;
15442                     synchronized (mPackages) {
15443                         PackageSetting ps = mSettings.getPackageLPr(pkgLite.packageName);
15444                         if (ps != null) {
15445                             installedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(),
15446                                     true);
15447                         } else {
15448                             installedUsers = new int[0];
15449                         }
15450                     }
15451
15452                     Intent enableRollbackIntent = new Intent(Intent.ACTION_PACKAGE_ENABLE_ROLLBACK);
15453                     enableRollbackIntent.putExtra(
15454                             PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_TOKEN,
15455                             enableRollbackToken);
15456                     enableRollbackIntent.putExtra(
15457                             PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_INSTALL_FLAGS,
15458                             installFlags);
15459                     enableRollbackIntent.putExtra(
15460                             PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_INSTALLED_USERS,
15461                             installedUsers);
15462                     enableRollbackIntent.putExtra(
15463                             PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_USER,
15464                             getRollbackUser().getIdentifier());
15465                     enableRollbackIntent.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
15466                             PACKAGE_MIME_TYPE);
15467                     enableRollbackIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
15468
15469                     // Allow the broadcast to be sent before boot complete.
15470                     // This is needed when committing the apk part of a staged
15471                     // session in early boot. The rollback manager registers
15472                     // its receiver early enough during the boot process that
15473                     // it will not miss the broadcast.
15474                     enableRollbackIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
15475
15476                     mContext.sendOrderedBroadcastAsUser(enableRollbackIntent, UserHandle.SYSTEM,
15477                             android.Manifest.permission.PACKAGE_ROLLBACK_AGENT,
15478                             new BroadcastReceiver() {
15479                                 @Override
15480                                 public void onReceive(Context context, Intent intent) {
15481                                     // the duration to wait for rollback to be enabled, in millis
15482                                     long rollbackTimeout = DeviceConfig.getLong(
15483                                             DeviceConfig.NAMESPACE_ROLLBACK,
15484                                             PROPERTY_ENABLE_ROLLBACK_TIMEOUT_MILLIS,
15485                                             DEFAULT_ENABLE_ROLLBACK_TIMEOUT_MILLIS);
15486                                     if (rollbackTimeout < 0) {
15487                                         rollbackTimeout = DEFAULT_ENABLE_ROLLBACK_TIMEOUT_MILLIS;
15488                                     }
15489                                     final Message msg = mHandler.obtainMessage(
15490                                             ENABLE_ROLLBACK_TIMEOUT);
15491                                     msg.arg1 = enableRollbackToken;
15492                                     mHandler.sendMessageDelayed(msg, rollbackTimeout);
15493                                 }
15494                             }, null, 0, null, null);
15495
15496                     mEnableRollbackCompleted = false;
15497                 }
15498             }
15499
15500             mRet = ret;
15501         }
15502
15503         void setReturnCode(int ret) {
15504             if (mRet == PackageManager.INSTALL_SUCCEEDED) {
15505                 // Only update mRet if it was previously INSTALL_SUCCEEDED to
15506                 // ensure we do not overwrite any previous failure results.
15507                 mRet = ret;
15508             }
15509         }
15510
15511         void handleVerificationFinished() {
15512             mVerificationCompleted = true;
15513             handleReturnCode();
15514         }
15515
15516         void handleRollbackEnabled() {
15517             // TODO(ruhler) b/112431924: Consider halting the install if we
15518             // couldn't enable rollback.
15519             mEnableRollbackCompleted = true;
15520             handleReturnCode();
15521         }
15522
15523         @Override
15524         void handleReturnCode() {
15525             if (mVerificationCompleted && mEnableRollbackCompleted) {
15526                 if ((installFlags & PackageManager.INSTALL_DRY_RUN) != 0) {
15527                     String packageName = "";
15528                     try {
15529                         PackageLite packageInfo =
15530                                 new PackageParser().parsePackageLite(origin.file, 0);
15531                         packageName = packageInfo.packageName;
15532                     } catch (PackageParserException e) {
15533                         Slog.e(TAG, "Can't parse package at " + origin.file.getAbsolutePath(), e);
15534                     }
15535                     try {
15536                         observer.onPackageInstalled(packageName, mRet, "Dry run", new Bundle());
15537                     } catch (RemoteException e) {
15538                         Slog.i(TAG, "Observer no longer exists.");
15539                     }
15540                     return;
15541                 }
15542                 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
15543                     mRet = mArgs.copyApk();
15544                 }
15545                 processPendingInstall(mArgs, mRet);
15546             }
15547         }
15548     }
15549
15550     private InstallArgs createInstallArgs(InstallParams params) {
15551         if (params.move != null) {
15552             return new MoveInstallArgs(params);
15553         } else {
15554             return new FileInstallArgs(params);
15555         }
15556     }
15557
15558     /**
15559      * Create args that describe an existing installed package. Typically used
15560      * when cleaning up old installs, or used as a move source.
15561      */
15562     private InstallArgs createInstallArgsForExisting(String codePath,
15563             String resourcePath, String[] instructionSets) {
15564         return new FileInstallArgs(codePath, resourcePath, instructionSets);
15565     }
15566
15567     static abstract class InstallArgs {
15568         /** @see InstallParams#origin */
15569         final OriginInfo origin;
15570         /** @see InstallParams#move */
15571         final MoveInfo move;
15572
15573         final IPackageInstallObserver2 observer;
15574         // Always refers to PackageManager flags only
15575         final int installFlags;
15576         final String installerPackageName;
15577         final String volumeUuid;
15578         final UserHandle user;
15579         final String abiOverride;
15580         final String[] installGrantPermissions;
15581         final List<String> whitelistedRestrictedPermissions;
15582         /** If non-null, drop an async trace when the install completes */
15583         final String traceMethod;
15584         final int traceCookie;
15585         final PackageParser.SigningDetails signingDetails;
15586         final int installReason;
15587         @Nullable final MultiPackageInstallParams mMultiPackageInstallParams;
15588
15589         // The list of instruction sets supported by this app. This is currently
15590         // only used during the rmdex() phase to clean up resources. We can get rid of this
15591         // if we move dex files under the common app path.
15592         /* nullable */ String[] instructionSets;
15593
15594         InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
15595                 int installFlags, String installerPackageName, String volumeUuid,
15596                 UserHandle user, String[] instructionSets,
15597                 String abiOverride, String[] installGrantPermissions,
15598                 List<String> whitelistedRestrictedPermissions,
15599                 String traceMethod, int traceCookie, SigningDetails signingDetails,
15600                 int installReason,
15601                 MultiPackageInstallParams multiPackageInstallParams) {
15602             this.origin = origin;
15603             this.move = move;
15604             this.installFlags = installFlags;
15605             this.observer = observer;
15606             this.installerPackageName = installerPackageName;
15607             this.volumeUuid = volumeUuid;
15608             this.user = user;
15609             this.instructionSets = instructionSets;
15610             this.abiOverride = abiOverride;
15611             this.installGrantPermissions = installGrantPermissions;
15612             this.whitelistedRestrictedPermissions = whitelistedRestrictedPermissions;
15613             this.traceMethod = traceMethod;
15614             this.traceCookie = traceCookie;
15615             this.signingDetails = signingDetails;
15616             this.installReason = installReason;
15617             this.mMultiPackageInstallParams = multiPackageInstallParams;
15618         }
15619
15620         abstract int copyApk();
15621         abstract int doPreInstall(int status);
15622
15623         /**
15624          * Rename package into final resting place. All paths on the given
15625          * scanned package should be updated to reflect the rename.
15626          */
15627         abstract boolean doRename(int status, PackageParser.Package pkg);
15628         abstract int doPostInstall(int status, int uid);
15629
15630         /** @see PackageSettingBase#codePathString */
15631         abstract String getCodePath();
15632         /** @see PackageSettingBase#resourcePathString */
15633         abstract String getResourcePath();
15634
15635         // Need installer lock especially for dex file removal.
15636         abstract void cleanUpResourcesLI();
15637         abstract boolean doPostDeleteLI(boolean delete);
15638
15639         /**
15640          * Called before the source arguments are copied. This is used mostly
15641          * for MoveParams when it needs to read the source file to put it in the
15642          * destination.
15643          */
15644         int doPreCopy() {
15645             return PackageManager.INSTALL_SUCCEEDED;
15646         }
15647
15648         /**
15649          * Called after the source arguments are copied. This is used mostly for
15650          * MoveParams when it needs to read the source file to put it in the
15651          * destination.
15652          */
15653         int doPostCopy(int uid) {
15654             return PackageManager.INSTALL_SUCCEEDED;
15655         }
15656
15657         protected boolean isEphemeral() {
15658             return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15659         }
15660
15661         UserHandle getUser() {
15662             return user;
15663         }
15664     }
15665
15666     void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
15667         if (!allCodePaths.isEmpty()) {
15668             if (instructionSets == null) {
15669                 throw new IllegalStateException("instructionSet == null");
15670             }
15671             String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
15672             for (String codePath : allCodePaths) {
15673                 for (String dexCodeInstructionSet : dexCodeInstructionSets) {
15674                     try {
15675                         mInstaller.rmdex(codePath, dexCodeInstructionSet);
15676                     } catch (InstallerException ignored) {
15677                     }
15678                 }
15679             }
15680         }
15681     }
15682
15683     /**
15684      * Logic to handle installation of new applications, including copying
15685      * and renaming logic.
15686      */
15687     class FileInstallArgs extends InstallArgs {
15688         private File codeFile;
15689         private File resourceFile;
15690
15691         // Example topology:
15692         // /data/app/com.example/base.apk
15693         // /data/app/com.example/split_foo.apk
15694         // /data/app/com.example/lib/arm/libfoo.so
15695         // /data/app/com.example/lib/arm64/libfoo.so
15696         // /data/app/com.example/dalvik/arm/base.apk@classes.dex
15697
15698         /** New install */
15699         FileInstallArgs(InstallParams params) {
15700             super(params.origin, params.move, params.observer, params.installFlags,
15701                     params.installerPackageName, params.volumeUuid,
15702                     params.getUser(), null /*instructionSets*/, params.packageAbiOverride,
15703                     params.grantedRuntimePermissions, params.whitelistedRestrictedPermissions,
15704                     params.traceMethod, params.traceCookie, params.signingDetails,
15705                     params.installReason, params.mParentInstallParams);
15706         }
15707
15708         /** Existing install */
15709         FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
15710             super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets,
15711                     null, null, null, null, 0, PackageParser.SigningDetails.UNKNOWN,
15712                     PackageManager.INSTALL_REASON_UNKNOWN, null /* parent */);
15713             this.codeFile = (codePath != null) ? new File(codePath) : null;
15714             this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
15715         }
15716
15717         int copyApk() {
15718             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
15719             try {
15720                 return doCopyApk();
15721             } finally {
15722                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
15723             }
15724         }
15725
15726         private int doCopyApk() {
15727             if (origin.staged) {
15728                 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy");
15729                 codeFile = origin.file;
15730                 resourceFile = origin.file;
15731                 return PackageManager.INSTALL_SUCCEEDED;
15732             }
15733
15734             try {
15735                 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
15736                 final File tempDir =
15737                         mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
15738                 codeFile = tempDir;
15739                 resourceFile = tempDir;
15740             } catch (IOException e) {
15741                 Slog.w(TAG, "Failed to create copy file: " + e);
15742                 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
15743             }
15744
15745             int ret = PackageManagerServiceUtils.copyPackage(
15746                     origin.file.getAbsolutePath(), codeFile);
15747             if (ret != PackageManager.INSTALL_SUCCEEDED) {
15748                 Slog.e(TAG, "Failed to copy package");
15749                 return ret;
15750             }
15751
15752             final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
15753             NativeLibraryHelper.Handle handle = null;
15754             try {
15755                 handle = NativeLibraryHelper.Handle.create(codeFile);
15756                 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
15757                         abiOverride);
15758             } catch (IOException e) {
15759                 Slog.e(TAG, "Copying native libraries failed", e);
15760                 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15761             } finally {
15762                 IoUtils.closeQuietly(handle);
15763             }
15764
15765             return ret;
15766         }
15767
15768         int doPreInstall(int status) {
15769             if (status != PackageManager.INSTALL_SUCCEEDED) {
15770                 cleanUp();
15771             }
15772             return status;
15773         }
15774
15775         boolean doRename(int status, PackageParser.Package pkg) {
15776             if (status != PackageManager.INSTALL_SUCCEEDED) {
15777                 cleanUp();
15778                 return false;
15779             }
15780
15781             final File targetDir = codeFile.getParentFile();
15782             final File beforeCodeFile = codeFile;
15783             final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
15784
15785             if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
15786             try {
15787                 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
15788             } catch (ErrnoException e) {
15789                 Slog.w(TAG, "Failed to rename", e);
15790                 return false;
15791             }
15792
15793             if (!SELinux.restoreconRecursive(afterCodeFile)) {
15794                 Slog.w(TAG, "Failed to restorecon");
15795                 return false;
15796             }
15797
15798             // Reflect the rename internally
15799             codeFile = afterCodeFile;
15800             resourceFile = afterCodeFile;
15801
15802             // Reflect the rename in scanned details
15803             try {
15804                 pkg.setCodePath(afterCodeFile.getCanonicalPath());
15805             } catch (IOException e) {
15806                 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e);
15807                 return false;
15808             }
15809             pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile,
15810                     afterCodeFile, pkg.baseCodePath));
15811             pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile,
15812                     afterCodeFile, pkg.splitCodePaths));
15813
15814             // Reflect the rename in app info
15815             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15816             pkg.setApplicationInfoCodePath(pkg.codePath);
15817             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15818             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15819             pkg.setApplicationInfoResourcePath(pkg.codePath);
15820             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15821             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15822
15823             return true;
15824         }
15825
15826         int doPostInstall(int status, int uid) {
15827             if (status != PackageManager.INSTALL_SUCCEEDED) {
15828                 cleanUp();
15829             }
15830             return status;
15831         }
15832
15833         @Override
15834         String getCodePath() {
15835             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15836         }
15837
15838         @Override
15839         String getResourcePath() {
15840             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15841         }
15842
15843         private boolean cleanUp() {
15844             if (codeFile == null || !codeFile.exists()) {
15845                 return false;
15846             }
15847
15848             removeCodePathLI(codeFile);
15849
15850             if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
15851                 resourceFile.delete();
15852             }
15853
15854             return true;
15855         }
15856
15857         void cleanUpResourcesLI() {
15858             // Try enumerating all code paths before deleting
15859             List<String> allCodePaths = Collections.EMPTY_LIST;
15860             if (codeFile != null && codeFile.exists()) {
15861                 try {
15862                     final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
15863                     allCodePaths = pkg.getAllCodePaths();
15864                 } catch (PackageParserException e) {
15865                     // Ignored; we tried our best
15866                 }
15867             }
15868
15869             cleanUp();
15870             removeDexFiles(allCodePaths, instructionSets);
15871         }
15872
15873         boolean doPostDeleteLI(boolean delete) {
15874             // XXX err, shouldn't we respect the delete flag?
15875             cleanUpResourcesLI();
15876             return true;
15877         }
15878     }
15879
15880     private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
15881             PackageManagerException {
15882         if (copyRet < 0) {
15883             if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
15884                     copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
15885                 throw new PackageManagerException(copyRet, message);
15886             }
15887         }
15888     }
15889
15890     /**
15891      * Logic to handle movement of existing installed applications.
15892      */
15893     class MoveInstallArgs extends InstallArgs {
15894         private File codeFile;
15895         private File resourceFile;
15896
15897         /** New install */
15898         MoveInstallArgs(InstallParams params) {
15899             super(params.origin, params.move, params.observer, params.installFlags,
15900                     params.installerPackageName, params.volumeUuid,
15901                     params.getUser(), null /* instruction sets */, params.packageAbiOverride,
15902                     params.grantedRuntimePermissions, params.whitelistedRestrictedPermissions,
15903                     params.traceMethod, params.traceCookie, params.signingDetails,
15904                     params.installReason, params.mParentInstallParams);
15905         }
15906
15907         int copyApk() {
15908             if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from "
15909                     + move.fromUuid + " to " + move.toUuid);
15910             synchronized (mInstaller) {
15911                 try {
15912                     mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
15913                             move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion);
15914                 } catch (InstallerException e) {
15915                     Slog.w(TAG, "Failed to move app", e);
15916                     return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
15917                 }
15918             }
15919
15920             codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
15921             resourceFile = codeFile;
15922             if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile);
15923
15924             return PackageManager.INSTALL_SUCCEEDED;
15925         }
15926
15927         int doPreInstall(int status) {
15928             if (status != PackageManager.INSTALL_SUCCEEDED) {
15929                 cleanUp(move.toUuid);
15930             }
15931             return status;
15932         }
15933
15934         boolean doRename(int status, PackageParser.Package pkg) {
15935             if (status != PackageManager.INSTALL_SUCCEEDED) {
15936                 cleanUp(move.toUuid);
15937                 return false;
15938             }
15939
15940             // Reflect the move in app info
15941             pkg.setApplicationVolumeUuid(pkg.volumeUuid);
15942             pkg.setApplicationInfoCodePath(pkg.codePath);
15943             pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath);
15944             pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths);
15945             pkg.setApplicationInfoResourcePath(pkg.codePath);
15946             pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath);
15947             pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths);
15948
15949             return true;
15950         }
15951
15952         int doPostInstall(int status, int uid) {
15953             if (status == PackageManager.INSTALL_SUCCEEDED) {
15954                 cleanUp(move.fromUuid);
15955             } else {
15956                 cleanUp(move.toUuid);
15957             }
15958             return status;
15959         }
15960
15961         @Override
15962         String getCodePath() {
15963             return (codeFile != null) ? codeFile.getAbsolutePath() : null;
15964         }
15965
15966         @Override
15967         String getResourcePath() {
15968             return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
15969         }
15970
15971         private boolean cleanUp(String volumeUuid) {
15972             final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid),
15973                     move.dataAppName);
15974             Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid);
15975             final int[] userIds = sUserManager.getUserIds();
15976             synchronized (mInstallLock) {
15977                 // Clean up both app data and code
15978                 // All package moves are frozen until finished
15979
15980                 // We purposefully exclude FLAG_STORAGE_EXTERNAL here, since
15981                 // this task was only focused on moving data on internal storage.
15982                 for (int userId : userIds) {
15983                     try {
15984                         mInstaller.destroyAppData(volumeUuid, move.packageName, userId,
15985                                 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0);
15986                     } catch (InstallerException e) {
15987                         Slog.w(TAG, String.valueOf(e));
15988                     }
15989                 }
15990                 removeCodePathLI(codeFile);
15991             }
15992             return true;
15993         }
15994
15995         void cleanUpResourcesLI() {
15996             throw new UnsupportedOperationException();
15997         }
15998
15999         boolean doPostDeleteLI(boolean delete) {
16000             throw new UnsupportedOperationException();
16001         }
16002     }
16003
16004     private File getNextCodePath(File targetDir, String packageName) {
16005         File result;
16006         SecureRandom random = new SecureRandom();
16007         byte[] bytes = new byte[16];
16008         do {
16009             random.nextBytes(bytes);
16010             String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP);
16011             result = new File(targetDir, packageName + "-" + suffix);
16012         } while (result.exists());
16013         return result;
16014     }
16015
16016     // Utility method that returns the relative package path with respect
16017     // to the installation directory. Like say for /data/data/com.test-1.apk
16018     // string com.test-1 is returned.
16019     static String deriveCodePathName(String codePath) {
16020         if (codePath == null) {
16021             return null;
16022         }
16023         final File codeFile = new File(codePath);
16024         final String name = codeFile.getName();
16025         if (codeFile.isDirectory()) {
16026             return name;
16027         } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
16028             final int lastDot = name.lastIndexOf('.');
16029             return name.substring(0, lastDot);
16030         } else {
16031             Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
16032             return null;
16033         }
16034     }
16035
16036     static class PackageInstalledInfo {
16037         String name;
16038         int uid;
16039         // The set of users that originally had this package installed.
16040         int[] origUsers;
16041         // The set of users that now have this package installed.
16042         int[] newUsers;
16043         PackageParser.Package pkg;
16044         int returnCode;
16045         String returnMsg;
16046         String installerPackageName;
16047         PackageRemovedInfo removedInfo;
16048         ArrayMap<String, PackageInstalledInfo> addedChildPackages;
16049
16050         public void setError(int code, String msg) {
16051             setReturnCode(code);
16052             setReturnMessage(msg);
16053             Slog.w(TAG, msg);
16054         }
16055
16056         public void setError(String msg, PackageParserException e) {
16057             setReturnCode(e.error);
16058             setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16059             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16060             for (int i = 0; i < childCount; i++) {
16061                 addedChildPackages.valueAt(i).setError(msg, e);
16062             }
16063             Slog.w(TAG, msg, e);
16064         }
16065
16066         public void setError(String msg, PackageManagerException e) {
16067             returnCode = e.error;
16068             setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e));
16069             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16070             for (int i = 0; i < childCount; i++) {
16071                 addedChildPackages.valueAt(i).setError(msg, e);
16072             }
16073             Slog.w(TAG, msg, e);
16074         }
16075
16076         public void setReturnCode(int returnCode) {
16077             this.returnCode = returnCode;
16078             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16079             for (int i = 0; i < childCount; i++) {
16080                 addedChildPackages.valueAt(i).returnCode = returnCode;
16081             }
16082         }
16083
16084         private void setReturnMessage(String returnMsg) {
16085             this.returnMsg = returnMsg;
16086             final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0;
16087             for (int i = 0; i < childCount; i++) {
16088                 addedChildPackages.valueAt(i).returnMsg = returnMsg;
16089             }
16090         }
16091
16092         // In some error cases we want to convey more info back to the observer
16093         String origPackage;
16094         String origPermission;
16095     }
16096
16097     private static void updateDigest(MessageDigest digest, File file) throws IOException {
16098         try (DigestInputStream digestStream =
16099                 new DigestInputStream(new FileInputStream(file), digest)) {
16100             while (digestStream.read() != -1) {} // nothing to do; just plow through the file
16101         }
16102     }
16103
16104     /**
16105      * Checks whether the parent or any of the child packages have a change shared
16106      * user. For a package to be a valid update the shred users of the parent and
16107      * the children should match. We may later support changing child shared users.
16108      * @param oldPkg The updated package.
16109      * @param newPkg The update package.
16110      * @return The shared user that change between the versions.
16111      */
16112     private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg,
16113             PackageParser.Package newPkg) {
16114         // Check parent shared user
16115         if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) {
16116             return newPkg.packageName;
16117         }
16118         // Check child shared users
16119         final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16120         final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0;
16121         for (int i = 0; i < newChildCount; i++) {
16122             PackageParser.Package newChildPkg = newPkg.childPackages.get(i);
16123             // If this child was present, did it have the same shared user?
16124             for (int j = 0; j < oldChildCount; j++) {
16125                 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j);
16126                 if (newChildPkg.packageName.equals(oldChildPkg.packageName)
16127                         && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) {
16128                     return newChildPkg.packageName;
16129                 }
16130             }
16131         }
16132         return null;
16133     }
16134
16135     private void removeNativeBinariesLI(PackageSetting ps) {
16136         // Remove the lib path for the parent package
16137         if (ps != null) {
16138             NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString);
16139             // Remove the lib path for the child packages
16140             final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
16141             for (int i = 0; i < childCount; i++) {
16142                 PackageSetting childPs = null;
16143                 synchronized (mPackages) {
16144                     childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
16145                 }
16146                 if (childPs != null) {
16147                     NativeLibraryHelper.removeNativeBinariesLI(childPs
16148                             .legacyNativeLibraryPathString);
16149                 }
16150             }
16151         }
16152     }
16153
16154     @GuardedBy("mPackages")
16155     private void enableSystemPackageLPw(PackageParser.Package pkg) {
16156         // Enable the parent package
16157         mSettings.enableSystemPackageLPw(pkg.packageName);
16158         // Enable the child packages
16159         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16160         for (int i = 0; i < childCount; i++) {
16161             PackageParser.Package childPkg = pkg.childPackages.get(i);
16162             mSettings.enableSystemPackageLPw(childPkg.packageName);
16163         }
16164     }
16165
16166     @GuardedBy("mPackages")
16167     private boolean disableSystemPackageLPw(PackageParser.Package oldPkg,
16168             PackageParser.Package newPkg) {
16169         // Disable the parent package (parent always replaced)
16170         boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true);
16171         // Disable the child packages
16172         final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0;
16173         for (int i = 0; i < childCount; i++) {
16174             PackageParser.Package childPkg = oldPkg.childPackages.get(i);
16175             final boolean replace = newPkg.hasChildPackage(childPkg.packageName);
16176             disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace);
16177         }
16178         return disabled;
16179     }
16180
16181     @GuardedBy("mPackages")
16182     private void setInstallerPackageNameLPw(PackageParser.Package pkg,
16183             String installerPackageName) {
16184         // Enable the parent package
16185         mSettings.setInstallerPackageName(pkg.packageName, installerPackageName);
16186         // Enable the child packages
16187         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16188         for (int i = 0; i < childCount; i++) {
16189             PackageParser.Package childPkg = pkg.childPackages.get(i);
16190             mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName);
16191         }
16192     }
16193
16194     private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
16195             int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) {
16196         // Update the parent package setting
16197         updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers,
16198                 res, user, installReason);
16199         // Update the child packages setting
16200         final int childCount = (newPackage.childPackages != null)
16201                 ? newPackage.childPackages.size() : 0;
16202         for (int i = 0; i < childCount; i++) {
16203             PackageParser.Package childPackage = newPackage.childPackages.get(i);
16204             PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName);
16205             updateSettingsInternalLI(childPackage, installerPackageName, allUsers,
16206                     childRes.origUsers, childRes, user, installReason);
16207         }
16208     }
16209
16210     private void updateSettingsInternalLI(PackageParser.Package pkg,
16211             String installerPackageName, int[] allUsers, int[] installedForUsers,
16212             PackageInstalledInfo res, UserHandle user, int installReason) {
16213         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings");
16214
16215         final String pkgName = pkg.packageName;
16216
16217         if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath);
16218         synchronized (mPackages) {
16219 // NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions
16220             mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
16221                     mPermissionCallback);
16222             // For system-bundled packages, we assume that installing an upgraded version
16223             // of the package implies that the user actually wants to run that new code,
16224             // so we enable the package.
16225             PackageSetting ps = mSettings.mPackages.get(pkgName);
16226             final int userId = user.getIdentifier();
16227             if (ps != null) {
16228                 if (isSystemApp(pkg)) {
16229                     if (DEBUG_INSTALL) {
16230                         Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
16231                     }
16232                     // Enable system package for requested users
16233                     if (res.origUsers != null) {
16234                         for (int origUserId : res.origUsers) {
16235                             if (userId == UserHandle.USER_ALL || userId == origUserId) {
16236                                 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
16237                                         origUserId, installerPackageName);
16238                             }
16239                         }
16240                     }
16241                     // Also convey the prior install/uninstall state
16242                     if (allUsers != null && installedForUsers != null) {
16243                         for (int currentUserId : allUsers) {
16244                             final boolean installed = ArrayUtils.contains(
16245                                     installedForUsers, currentUserId);
16246                             if (DEBUG_INSTALL) {
16247                                 Slog.d(TAG, "    user " + currentUserId + " => " + installed);
16248                             }
16249                             ps.setInstalled(installed, currentUserId);
16250                         }
16251                         // these install state changes will be persisted in the
16252                         // upcoming call to mSettings.writeLPr().
16253                     }
16254                 }
16255                 // It's implied that when a user requests installation, they want the app to be
16256                 // installed and enabled.
16257                 if (userId != UserHandle.USER_ALL) {
16258                     ps.setInstalled(true, userId);
16259                     ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
16260                 }
16261
16262                 // When replacing an existing package, preserve the original install reason for all
16263                 // users that had the package installed before.
16264                 final Set<Integer> previousUserIds = new ArraySet<>();
16265                 if (res.removedInfo != null && res.removedInfo.installReasons != null) {
16266                     final int installReasonCount = res.removedInfo.installReasons.size();
16267                     for (int i = 0; i < installReasonCount; i++) {
16268                         final int previousUserId = res.removedInfo.installReasons.keyAt(i);
16269                         final int previousInstallReason = res.removedInfo.installReasons.valueAt(i);
16270                         ps.setInstallReason(previousInstallReason, previousUserId);
16271                         previousUserIds.add(previousUserId);
16272                     }
16273                 }
16274
16275                 // Set install reason for users that are having the package newly installed.
16276                 if (userId == UserHandle.USER_ALL) {
16277                     for (int currentUserId : sUserManager.getUserIds()) {
16278                         if (!previousUserIds.contains(currentUserId)) {
16279                             ps.setInstallReason(installReason, currentUserId);
16280                         }
16281                     }
16282                 } else if (!previousUserIds.contains(userId)) {
16283                     ps.setInstallReason(installReason, userId);
16284                 }
16285                 mSettings.writeKernelMappingLPr(ps);
16286             }
16287             res.name = pkgName;
16288             res.uid = pkg.applicationInfo.uid;
16289             res.pkg = pkg;
16290             mSettings.setInstallerPackageName(pkgName, installerPackageName);
16291             res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16292             //to update install status
16293             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings");
16294             mSettings.writeLPr();
16295             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16296         }
16297
16298         Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16299     }
16300
16301     private static class InstallRequest {
16302         public final InstallArgs args;
16303         public final PackageInstalledInfo installResult;
16304
16305         private InstallRequest(InstallArgs args, PackageInstalledInfo res) {
16306             this.args = args;
16307             this.installResult = res;
16308         }
16309     }
16310
16311     @GuardedBy({"mInstallLock", "mPackages"})
16312     private void installPackagesTracedLI(List<InstallRequest> requests) {
16313         try {
16314             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackages");
16315             installPackagesLI(requests);
16316         } finally {
16317             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16318         }
16319     }
16320
16321     /**
16322      * Package state to commit to memory and disk after reconciliation has completed.
16323      */
16324     private static class CommitRequest {
16325         final Map<String, ReconciledPackage> reconciledPackages;
16326         final int[] mAllUsers;
16327
16328         private CommitRequest(Map<String, ReconciledPackage> reconciledPackages, int[] allUsers) {
16329             this.reconciledPackages = reconciledPackages;
16330             this.mAllUsers = allUsers;
16331         }
16332     }
16333
16334     /**
16335      * Package scan results and related request details used to reconcile the potential addition of
16336      * one or more packages to the system.
16337      *
16338      * Reconcile will take a set of package details that need to be committed to the system and make
16339      * sure that they are valid in the context of the system and the other installing apps. Any
16340      * invalid state or app will result in a failed reconciliation and thus whatever operation (such
16341      * as install) led to the request.
16342      */
16343     private static class ReconcileRequest {
16344         public final Map<String, ScanResult> scannedPackages;
16345
16346         public final Map<String, PackageParser.Package> allPackages;
16347         public final Map<String, LongSparseArray<SharedLibraryInfo>> sharedLibrarySource;
16348         public final Map<String, InstallArgs> installArgs;
16349         public final Map<String, PackageInstalledInfo> installResults;
16350         public final Map<String, PrepareResult> preparedPackages;
16351         public final Map<String, VersionInfo> versionInfos;
16352         public final Map<String, PackageSetting> lastStaticSharedLibSettings;
16353
16354         private ReconcileRequest(Map<String, ScanResult> scannedPackages,
16355                 Map<String, InstallArgs> installArgs,
16356                 Map<String, PackageInstalledInfo> installResults,
16357                 Map<String, PrepareResult> preparedPackages,
16358                 Map<String, LongSparseArray<SharedLibraryInfo>> sharedLibrarySource,
16359                 Map<String, PackageParser.Package> allPackages,
16360                 Map<String, VersionInfo> versionInfos,
16361                 Map<String, PackageSetting> lastStaticSharedLibSettings) {
16362             this.scannedPackages = scannedPackages;
16363             this.installArgs = installArgs;
16364             this.installResults = installResults;
16365             this.preparedPackages = preparedPackages;
16366             this.sharedLibrarySource = sharedLibrarySource;
16367             this.allPackages = allPackages;
16368             this.versionInfos = versionInfos;
16369             this.lastStaticSharedLibSettings = lastStaticSharedLibSettings;
16370         }
16371
16372         private ReconcileRequest(Map<String, ScanResult> scannedPackages,
16373                 Map<String, LongSparseArray<SharedLibraryInfo>> sharedLibrarySource,
16374                 Map<String, PackageParser.Package> allPackages,
16375                 Map<String, VersionInfo> versionInfos,
16376                 Map<String, PackageSetting> lastStaticSharedLibSettings) {
16377             this(scannedPackages, Collections.emptyMap(), Collections.emptyMap(),
16378                     Collections.emptyMap(), sharedLibrarySource, allPackages, versionInfos,
16379                     lastStaticSharedLibSettings);
16380         }
16381     }
16382     private static class ReconcileFailure extends PackageManagerException {
16383         ReconcileFailure(String message) {
16384             super("Reconcile failed: " + message);
16385         }
16386         ReconcileFailure(int reason, String message) {
16387             super(reason, "Reconcile failed: " + message);
16388         }
16389         ReconcileFailure(PackageManagerException e) {
16390             this(e.error, e.getMessage());
16391         }
16392     }
16393
16394     /**
16395      * A container of all data needed to commit a package to in-memory data structures and to disk.
16396      * TODO: move most of the data contained her into a PackageSetting for commit.
16397      */
16398     private static class ReconciledPackage {
16399         public final ReconcileRequest request;
16400         public final PackageSetting pkgSetting;
16401         public final ScanResult scanResult;
16402         // TODO: Remove install-specific details from the reconcile result
16403         public final PackageInstalledInfo installResult;
16404         @Nullable public final PrepareResult prepareResult;
16405         @Nullable public final InstallArgs installArgs;
16406         public final DeletePackageAction deletePackageAction;
16407         public final List<SharedLibraryInfo> allowedSharedLibraryInfos;
16408         public final SigningDetails signingDetails;
16409         public final boolean sharedUserSignaturesChanged;
16410         public ArrayList<SharedLibraryInfo> collectedSharedLibraryInfos;
16411         public final boolean removeAppKeySetData;
16412
16413         private ReconciledPackage(ReconcileRequest request,
16414                 InstallArgs installArgs,
16415                 PackageSetting pkgSetting,
16416                 PackageInstalledInfo installResult,
16417                 PrepareResult prepareResult,
16418                 ScanResult scanResult,
16419                 DeletePackageAction deletePackageAction,
16420                 List<SharedLibraryInfo> allowedSharedLibraryInfos,
16421                 SigningDetails signingDetails,
16422                 boolean sharedUserSignaturesChanged,
16423                 boolean removeAppKeySetData) {
16424             this.request = request;
16425             this.installArgs = installArgs;
16426             this.pkgSetting = pkgSetting;
16427             this.installResult = installResult;
16428             this.prepareResult = prepareResult;
16429             this.scanResult = scanResult;
16430             this.deletePackageAction = deletePackageAction;
16431             this.allowedSharedLibraryInfos = allowedSharedLibraryInfos;
16432             this.signingDetails = signingDetails;
16433             this.sharedUserSignaturesChanged = sharedUserSignaturesChanged;
16434             this.removeAppKeySetData = removeAppKeySetData;
16435         }
16436
16437         /**
16438          * Returns a combined set of packages containing the packages already installed combined
16439          * with the package(s) currently being installed. The to-be installed packages take
16440          * precedence and may shadow already installed packages.
16441          */
16442         private Map<String, PackageParser.Package> getCombinedPackages() {
16443             final ArrayMap<String, PackageParser.Package> combinedPackages =
16444                     new ArrayMap<>(request.allPackages.size() + request.scannedPackages.size());
16445
16446             combinedPackages.putAll(request.allPackages);
16447             for (ScanResult scanResult : request.scannedPackages.values()) {
16448                 combinedPackages.put(scanResult.pkgSetting.name, scanResult.request.pkg);
16449             }
16450             return combinedPackages;
16451         }
16452     }
16453
16454     @GuardedBy("mPackages")
16455     private static Map<String, ReconciledPackage> reconcilePackagesLocked(
16456             final ReconcileRequest request, KeySetManagerService ksms)
16457             throws ReconcileFailure {
16458         final Map<String, ScanResult> scannedPackages = request.scannedPackages;
16459
16460         final Map<String, ReconciledPackage> result = new ArrayMap<>(scannedPackages.size());
16461
16462         // make a copy of the existing set of packages so we can combine them with incoming packages
16463         final ArrayMap<String, PackageParser.Package> combinedPackages =
16464                 new ArrayMap<>(request.allPackages.size() + scannedPackages.size());
16465         combinedPackages.putAll(request.allPackages);
16466
16467         final Map<String, LongSparseArray<SharedLibraryInfo>> incomingSharedLibraries =
16468                 new ArrayMap<>();
16469
16470         for (String installPackageName : scannedPackages.keySet()) {
16471             final ScanResult scanResult = scannedPackages.get(installPackageName);
16472
16473             // add / replace existing with incoming packages
16474             combinedPackages.put(scanResult.pkgSetting.name, scanResult.request.pkg);
16475
16476             // in the first pass, we'll build up the set of incoming shared libraries
16477             final List<SharedLibraryInfo> allowedSharedLibInfos =
16478                     getAllowedSharedLibInfos(scanResult, request.sharedLibrarySource);
16479             final SharedLibraryInfo staticLib = scanResult.staticSharedLibraryInfo;
16480             if (allowedSharedLibInfos != null) {
16481                 for (SharedLibraryInfo info : allowedSharedLibInfos) {
16482                     if (!addSharedLibraryToPackageVersionMap(incomingSharedLibraries, info)) {
16483                         throw new ReconcileFailure("Static Shared Library " + staticLib.getName()
16484                                 + " is being installed twice in this set!");
16485                     }
16486                 }
16487             }
16488
16489             // the following may be null if we're just reconciling on boot (and not during install)
16490             final InstallArgs installArgs = request.installArgs.get(installPackageName);
16491             final PackageInstalledInfo res = request.installResults.get(installPackageName);
16492             final PrepareResult prepareResult = request.preparedPackages.get(installPackageName);
16493             final boolean isInstall = installArgs != null;
16494             if (isInstall && (res == null || prepareResult == null)) {
16495                 throw new ReconcileFailure("Reconcile arguments are not balanced for "
16496                         + installPackageName + "!");
16497             }
16498
16499             final DeletePackageAction deletePackageAction;
16500             // we only want to try to delete for non system apps
16501             if (isInstall && prepareResult.replace && !prepareResult.system) {
16502                 final boolean killApp = (scanResult.request.scanFlags & SCAN_DONT_KILL_APP) == 0;
16503                 final int deleteFlags = PackageManager.DELETE_KEEP_DATA
16504                         | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP);
16505                 deletePackageAction = mayDeletePackageLocked(res.removedInfo,
16506                         prepareResult.originalPs, prepareResult.disabledPs,
16507                         prepareResult.childPackageSettings, deleteFlags, null /* all users */);
16508                 if (deletePackageAction == null) {
16509                     throw new ReconcileFailure(
16510                             PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE,
16511                             "May not delete " + installPackageName + " to replace");
16512                 }
16513             } else {
16514                 deletePackageAction = null;
16515             }
16516
16517             final int scanFlags = scanResult.request.scanFlags;
16518             final int parseFlags = scanResult.request.parseFlags;
16519             final PackageParser.Package pkg = scanResult.request.pkg;
16520
16521             final PackageSetting disabledPkgSetting = scanResult.request.disabledPkgSetting;
16522             final PackageSetting lastStaticSharedLibSetting =
16523                     request.lastStaticSharedLibSettings.get(installPackageName);
16524             final PackageSetting signatureCheckPs =
16525                     (prepareResult != null && lastStaticSharedLibSetting != null)
16526                             ? lastStaticSharedLibSetting
16527                             : scanResult.pkgSetting;
16528             boolean removeAppKeySetData = false;
16529             boolean sharedUserSignaturesChanged = false;
16530             SigningDetails signingDetails = null;
16531             if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
16532                 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
16533                     // We just determined the app is signed correctly, so bring
16534                     // over the latest parsed certs.
16535                 } else {
16536                     if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
16537                         throw new ReconcileFailure(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
16538                                 "Package " + pkg.packageName + " upgrade keys do not match the "
16539                                         + "previously installed version");
16540                     } else {
16541                         String msg = "System package " + pkg.packageName
16542                                 + " signature changed; retaining data.";
16543                         reportSettingsProblem(Log.WARN, msg);
16544                     }
16545                 }
16546                 signingDetails = pkg.mSigningDetails;
16547             } else {
16548                 try {
16549                     final VersionInfo versionInfo = request.versionInfos.get(installPackageName);
16550                     final boolean compareCompat = isCompatSignatureUpdateNeeded(versionInfo);
16551                     final boolean compareRecover = isRecoverSignatureUpdateNeeded(versionInfo);
16552                     final boolean compatMatch = verifySignatures(signatureCheckPs,
16553                             disabledPkgSetting, pkg.mSigningDetails, compareCompat, compareRecover);
16554                     // The new KeySets will be re-added later in the scanning process.
16555                     if (compatMatch) {
16556                         removeAppKeySetData = true;
16557                     }
16558                     // We just determined the app is signed correctly, so bring
16559                     // over the latest parsed certs.
16560                     signingDetails = pkg.mSigningDetails;
16561
16562
16563                     // if this is is a sharedUser, check to see if the new package is signed by a
16564                     // newer
16565                     // signing certificate than the existing one, and if so, copy over the new
16566                     // details
16567                     if (signatureCheckPs.sharedUser != null) {
16568                         if (pkg.mSigningDetails.hasAncestor(
16569                                 signatureCheckPs.sharedUser.signatures.mSigningDetails)) {
16570                             signatureCheckPs.sharedUser.signatures.mSigningDetails =
16571                                     pkg.mSigningDetails;
16572                         }
16573                         if (signatureCheckPs.sharedUser.signaturesChanged == null) {
16574                             signatureCheckPs.sharedUser.signaturesChanged = Boolean.FALSE;
16575                         }
16576                     }
16577                 } catch (PackageManagerException e) {
16578                     if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
16579                         throw new ReconcileFailure(e);
16580                     }
16581                     signingDetails = pkg.mSigningDetails;
16582
16583                     // If the system app is part of a shared user we allow that shared user to
16584                     // change
16585                     // signatures as well as part of an OTA. We still need to verify that the
16586                     // signatures
16587                     // are consistent within the shared user for a given boot, so only allow
16588                     // updating
16589                     // the signatures on the first package scanned for the shared user (i.e. if the
16590                     // signaturesChanged state hasn't been initialized yet in SharedUserSetting).
16591                     if (signatureCheckPs.sharedUser != null) {
16592                         final Signature[] sharedUserSignatures =
16593                                 signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures;
16594                         if (signatureCheckPs.sharedUser.signaturesChanged != null
16595                                 && compareSignatures(sharedUserSignatures,
16596                                         pkg.mSigningDetails.signatures)
16597                                         != PackageManager.SIGNATURE_MATCH) {
16598                             if (SystemProperties.getInt("ro.product.first_api_level", 0) <= 29) {
16599                                 // Mismatched signatures is an error and silently skipping system
16600                                 // packages will likely break the device in unforeseen ways.
16601                                 // However, we allow the device to boot anyway because, prior to Q,
16602                                 // vendors were not expecting the platform to crash in this
16603                                 // situation.
16604                                 // This WILL be a hard failure on any new API levels after Q.
16605                                 throw new ReconcileFailure(
16606                                         INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
16607                                         "Signature mismatch for shared user: "
16608                                                 + scanResult.pkgSetting.sharedUser);
16609                             } else {
16610                                 // Treat mismatched signatures on system packages using a shared
16611                                 // UID as
16612                                 // fatal for the system overall, rather than just failing to install
16613                                 // whichever package happened to be scanned later.
16614                                 throw new IllegalStateException(
16615                                         "Signature mismatch on system package "
16616                                                 + pkg.packageName + " for shared user "
16617                                                 + scanResult.pkgSetting.sharedUser);
16618                             }
16619                         }
16620
16621                         sharedUserSignaturesChanged = true;
16622                         signatureCheckPs.sharedUser.signatures.mSigningDetails =
16623                                 pkg.mSigningDetails;
16624                         signatureCheckPs.sharedUser.signaturesChanged = Boolean.TRUE;
16625                     }
16626                     // File a report about this.
16627                     String msg = "System package " + pkg.packageName
16628                             + " signature changed; retaining data.";
16629                     reportSettingsProblem(Log.WARN, msg);
16630                 } catch (IllegalArgumentException e) {
16631                     // should never happen: certs matched when checking, but not when comparing
16632                     // old to new for sharedUser
16633                     throw new RuntimeException(
16634                             "Signing certificates comparison made on incomparable signing details"
16635                                     + " but somehow passed verifySignatures!", e);
16636                 }
16637             }
16638
16639             result.put(installPackageName,
16640                     new ReconciledPackage(request, installArgs, scanResult.pkgSetting,
16641                             res, request.preparedPackages.get(installPackageName), scanResult,
16642                             deletePackageAction, allowedSharedLibInfos, signingDetails,
16643                             sharedUserSignaturesChanged, removeAppKeySetData));
16644         }
16645
16646         for (String installPackageName : scannedPackages.keySet()) {
16647             // Check all shared libraries and map to their actual file path.
16648             // We only do this here for apps not on a system dir, because those
16649             // are the only ones that can fail an install due to this.  We
16650             // will take care of the system apps by updating all of their
16651             // library paths after the scan is done. Also during the initial
16652             // scan don't update any libs as we do this wholesale after all
16653             // apps are scanned to avoid dependency based scanning.
16654             final ScanResult scanResult = scannedPackages.get(installPackageName);
16655             if ((scanResult.request.scanFlags & SCAN_BOOTING) != 0
16656                     || (scanResult.request.parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
16657                 continue;
16658             }
16659             try {
16660                 result.get(installPackageName).collectedSharedLibraryInfos =
16661                         collectSharedLibraryInfos(scanResult.request.pkg, combinedPackages,
16662                                 request.sharedLibrarySource, incomingSharedLibraries);
16663
16664             } catch (PackageManagerException e) {
16665                 throw new ReconcileFailure(e.error, e.getMessage());
16666             }
16667         }
16668
16669         return result;
16670     }
16671
16672     /**
16673      * Compare the newly scanned package with current system state to see which of its declared
16674      * shared libraries should be allowed to be added to the system.
16675      */
16676     private static List<SharedLibraryInfo> getAllowedSharedLibInfos(
16677             ScanResult scanResult,
16678             Map<String, LongSparseArray<SharedLibraryInfo>> existingSharedLibraries) {
16679         // Let's used the parsed package as scanResult.pkgSetting may be null
16680         final PackageParser.Package pkg = scanResult.request.pkg;
16681         if (scanResult.staticSharedLibraryInfo == null
16682                 && scanResult.dynamicSharedLibraryInfos == null) {
16683             return null;
16684         }
16685
16686         // Any app can add new static shared libraries
16687         if (scanResult.staticSharedLibraryInfo != null) {
16688             return Collections.singletonList(scanResult.staticSharedLibraryInfo);
16689         }
16690         final boolean hasDynamicLibraries =
16691                 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0
16692                         && scanResult.dynamicSharedLibraryInfos != null;
16693         if (!hasDynamicLibraries) {
16694             return null;
16695         }
16696         final boolean isUpdatedSystemApp = pkg.isUpdatedSystemApp();
16697         // We may not yet have disabled the updated package yet, so be sure to grab the
16698         // current setting if that's the case.
16699         final PackageSetting updatedSystemPs = isUpdatedSystemApp
16700                 ? scanResult.request.disabledPkgSetting == null
16701                         ? scanResult.request.oldPkgSetting
16702                         : scanResult.request.disabledPkgSetting
16703                 : null;
16704         if (isUpdatedSystemApp && (updatedSystemPs.pkg == null
16705                 || updatedSystemPs.pkg.libraryNames == null)) {
16706             Slog.w(TAG, "Package " + pkg.packageName + " declares libraries that are not "
16707                     + "declared on the system image; skipping");
16708             return null;
16709         }
16710         final ArrayList<SharedLibraryInfo> infos =
16711                 new ArrayList<>(scanResult.dynamicSharedLibraryInfos.size());
16712         for (SharedLibraryInfo info : scanResult.dynamicSharedLibraryInfos) {
16713             final String name = info.getName();
16714             if (isUpdatedSystemApp) {
16715                 // New library entries can only be added through the
16716                 // system image.  This is important to get rid of a lot
16717                 // of nasty edge cases: for example if we allowed a non-
16718                 // system update of the app to add a library, then uninstalling
16719                 // the update would make the library go away, and assumptions
16720                 // we made such as through app install filtering would now
16721                 // have allowed apps on the device which aren't compatible
16722                 // with it.  Better to just have the restriction here, be
16723                 // conservative, and create many fewer cases that can negatively
16724                 // impact the user experience.
16725                 if (!updatedSystemPs.pkg.libraryNames.contains(name)) {
16726                     Slog.w(TAG, "Package " + pkg.packageName + " declares library " + name
16727                             + " that is not declared on system image; skipping");
16728                     continue;
16729                 }
16730             }
16731             if (sharedLibExists(
16732                     name, SharedLibraryInfo.VERSION_UNDEFINED, existingSharedLibraries)) {
16733                 Slog.w(TAG, "Package " + pkg.packageName + " declares library " + name
16734                         + " that already exists; skipping");
16735                 continue;
16736             }
16737             infos.add(info);
16738         }
16739         return infos;
16740     }
16741
16742     /**
16743      * Returns false if the adding shared library already exists in the map and so could not be
16744      * added.
16745      */
16746     private static boolean addSharedLibraryToPackageVersionMap(
16747             Map<String, LongSparseArray<SharedLibraryInfo>> target,
16748             SharedLibraryInfo library) {
16749         final String name = library.getName();
16750         if (target.containsKey(name)) {
16751             if (library.getType() != SharedLibraryInfo.TYPE_STATIC) {
16752                 // We've already added this non-version-specific library to the map.
16753                 return false;
16754             } else if (target.get(name).indexOfKey(library.getLongVersion()) >= 0) {
16755                 // We've already added this version of a version-specific library to the map.
16756                 return false;
16757             }
16758         } else {
16759             target.put(name, new LongSparseArray<>());
16760         }
16761         target.get(name).put(library.getLongVersion(), library);
16762         return true;
16763     }
16764
16765     @GuardedBy("mPackages")
16766     private void commitPackagesLocked(final CommitRequest request) {
16767         // TODO: remove any expected failures from this method; this should only be able to fail due
16768         //       to unavoidable errors (I/O, etc.)
16769         for (ReconciledPackage reconciledPkg : request.reconciledPackages.values()) {
16770             final ScanResult scanResult = reconciledPkg.scanResult;
16771             final ScanRequest scanRequest = scanResult.request;
16772             final PackageParser.Package pkg = scanRequest.pkg;
16773             final String packageName = pkg.packageName;
16774             final PackageInstalledInfo res = reconciledPkg.installResult;
16775
16776             if (reconciledPkg.prepareResult.replace) {
16777                 PackageParser.Package oldPackage = mPackages.get(packageName);
16778
16779                 // Set the update and install times
16780                 PackageSetting deletedPkgSetting = (PackageSetting) oldPackage.mExtras;
16781                 setInstallAndUpdateTime(pkg, deletedPkgSetting.firstInstallTime,
16782                         System.currentTimeMillis());
16783
16784                 if (reconciledPkg.prepareResult.system) {
16785                     // Remove existing system package
16786                     removePackageLI(oldPackage, true);
16787                     if (!disableSystemPackageLPw(oldPackage, pkg)) {
16788                         // We didn't need to disable the .apk as a current system package,
16789                         // which means we are replacing another update that is already
16790                         // installed.  We need to make sure to delete the older one's .apk.
16791                         res.removedInfo.args = createInstallArgsForExisting(
16792                                 oldPackage.applicationInfo.getCodePath(),
16793                                 oldPackage.applicationInfo.getResourcePath(),
16794                                 getAppDexInstructionSets(oldPackage.applicationInfo));
16795                     } else {
16796                         res.removedInfo.args = null;
16797                     }
16798
16799                     // Update the package dynamic state if succeeded
16800                     // Now that the install succeeded make sure we remove data
16801                     // directories for any child package the update removed.
16802                     final int deletedChildCount = (oldPackage.childPackages != null)
16803                             ? oldPackage.childPackages.size() : 0;
16804                     final int newChildCount = (pkg.childPackages != null)
16805                             ? pkg.childPackages.size() : 0;
16806                     for (int i = 0; i < deletedChildCount; i++) {
16807                         PackageParser.Package deletedChildPkg = oldPackage.childPackages.get(i);
16808                         boolean childPackageDeleted = true;
16809                         for (int j = 0; j < newChildCount; j++) {
16810                             PackageParser.Package newChildPkg = pkg.childPackages.get(j);
16811                             if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) {
16812                                 childPackageDeleted = false;
16813                                 break;
16814                             }
16815                         }
16816                         if (childPackageDeleted) {
16817                             PackageSetting ps1 = mSettings.getDisabledSystemPkgLPr(
16818                                     deletedChildPkg.packageName);
16819                             if (ps1 != null && res.removedInfo.removedChildPackages != null) {
16820                                 PackageRemovedInfo removedChildRes = res.removedInfo
16821                                         .removedChildPackages.get(deletedChildPkg.packageName);
16822                                 removePackageDataLIF(ps1, request.mAllUsers, removedChildRes, 0,
16823                                         false);
16824                                 removedChildRes.removedForAllUsers = mPackages.get(ps1.name)
16825                                         == null;
16826                             }
16827                         }
16828                     }
16829                 } else {
16830                     try {
16831                         executeDeletePackageLIF(reconciledPkg.deletePackageAction, packageName,
16832                                 true, request.mAllUsers, true, pkg);
16833                     } catch (SystemDeleteException e) {
16834                         if (Build.IS_ENG) {
16835                             throw new RuntimeException("Unexpected failure", e);
16836                             // ignore; not possible for non-system app
16837                         }
16838                     }
16839                     // Successfully deleted the old package; proceed with replace.
16840
16841                     // If deleted package lived in a container, give users a chance to
16842                     // relinquish resources before killing.
16843                     if (oldPackage.isForwardLocked() || isExternal(oldPackage)) {
16844                         if (DEBUG_INSTALL) {
16845                             Slog.i(TAG, "upgrading pkg " + oldPackage
16846                                     + " is ASEC-hosted -> UNAVAILABLE");
16847                         }
16848                         final int[] uidArray = new int[]{oldPackage.applicationInfo.uid};
16849                         final ArrayList<String> pkgList = new ArrayList<>(1);
16850                         pkgList.add(oldPackage.applicationInfo.packageName);
16851                         sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
16852                     }
16853
16854                     // Update the in-memory copy of the previous code paths.
16855                     PackageSetting ps1 = mSettings.mPackages.get(
16856                             reconciledPkg.prepareResult.existingPackage.packageName);
16857                     if ((reconciledPkg.installArgs.installFlags & PackageManager.DONT_KILL_APP)
16858                             == 0) {
16859                         if (ps1.mOldCodePaths == null) {
16860                             ps1.mOldCodePaths = new ArraySet<>();
16861                         }
16862                         Collections.addAll(ps1.mOldCodePaths, oldPackage.baseCodePath);
16863                         if (oldPackage.splitCodePaths != null) {
16864                             Collections.addAll(ps1.mOldCodePaths, oldPackage.splitCodePaths);
16865                         }
16866                     } else {
16867                         ps1.mOldCodePaths = null;
16868                     }
16869                     if (ps1.childPackageNames != null) {
16870                         for (int i = ps1.childPackageNames.size() - 1; i >= 0; --i) {
16871                             final String childPkgName = ps1.childPackageNames.get(i);
16872                             final PackageSetting childPs = mSettings.mPackages.get(childPkgName);
16873                             childPs.mOldCodePaths = ps1.mOldCodePaths;
16874                         }
16875                     }
16876
16877                     if (reconciledPkg.installResult.returnCode
16878                             == PackageManager.INSTALL_SUCCEEDED) {
16879                         PackageSetting ps2 = mSettings.getPackageLPr(pkg.packageName);
16880                         if (ps2 != null) {
16881                             res.removedInfo.removedForAllUsers = mPackages.get(ps2.name) == null;
16882                             if (res.removedInfo.removedChildPackages != null) {
16883                                 final int childCount1 = res.removedInfo.removedChildPackages.size();
16884                                 // Iterate in reverse as we may modify the collection
16885                                 for (int i = childCount1 - 1; i >= 0; i--) {
16886                                     String childPackageName =
16887                                             res.removedInfo.removedChildPackages.keyAt(i);
16888                                     if (res.addedChildPackages.containsKey(childPackageName)) {
16889                                         res.removedInfo.removedChildPackages.removeAt(i);
16890                                     } else {
16891                                         PackageRemovedInfo childInfo = res.removedInfo
16892                                                 .removedChildPackages.valueAt(i);
16893                                         childInfo.removedForAllUsers = mPackages.get(
16894                                                 childInfo.removedPackage) == null;
16895                                     }
16896                                 }
16897                             }
16898                         }
16899                     }
16900                 }
16901             }
16902
16903             commitReconciledScanResultLocked(reconciledPkg);
16904             updateSettingsLI(pkg, reconciledPkg.installArgs.installerPackageName, request.mAllUsers,
16905                     res, reconciledPkg.installArgs.user, reconciledPkg.installArgs.installReason);
16906
16907             final PackageSetting ps = mSettings.mPackages.get(packageName);
16908             if (ps != null) {
16909                 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
16910                 ps.setUpdateAvailable(false /*updateAvailable*/);
16911             }
16912             final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
16913             for (int i = 0; i < childCount; i++) {
16914                 PackageParser.Package childPkg = pkg.childPackages.get(i);
16915                 PackageInstalledInfo childRes = res.addedChildPackages.get(
16916                         childPkg.packageName);
16917                 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
16918                 if (childPs != null) {
16919                     childRes.newUsers = childPs.queryInstalledUsers(
16920                             sUserManager.getUserIds(), true);
16921                 }
16922             }
16923             if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
16924                 updateSequenceNumberLP(ps, res.newUsers);
16925                 updateInstantAppInstallerLocked(packageName);
16926             }
16927         }
16928     }
16929
16930     /**
16931      * Installs one or more packages atomically. This operation is broken up into four phases:
16932      * <ul>
16933      *     <li><b>Prepare</b>
16934      *         <br/>Analyzes any current install state, parses the package and does initial
16935      *         validation on it.</li>
16936      *     <li><b>Scan</b>
16937      *         <br/>Interrogates the parsed packages given the context collected in prepare.</li>
16938      *     <li><b>Reconcile</b>
16939      *         <br/>Validates scanned packages in the context of each other and the current system
16940      *         state to ensure that the install will be successful.
16941      *     <li><b>Commit</b>
16942      *         <br/>Commits all scanned packages and updates system state. This is the only place
16943      *         that system state may be modified in the install flow and all predictable errors
16944      *         must be determined before this phase.</li>
16945      * </ul>
16946      *
16947      * Failure at any phase will result in a full failure to install all packages.
16948      */
16949     @GuardedBy("mInstallLock")
16950     private void installPackagesLI(List<InstallRequest> requests) {
16951         final Map<String, ScanResult> preparedScans = new ArrayMap<>(requests.size());
16952         final Map<String, InstallArgs> installArgs = new ArrayMap<>(requests.size());
16953         final Map<String, PackageInstalledInfo> installResults = new ArrayMap<>(requests.size());
16954         final Map<String, PrepareResult> prepareResults = new ArrayMap<>(requests.size());
16955         final Map<String, VersionInfo> versionInfos = new ArrayMap<>(requests.size());
16956         final Map<String, PackageSetting> lastStaticSharedLibSettings =
16957                 new ArrayMap<>(requests.size());
16958         final Map<String, Boolean> createdAppId = new ArrayMap<>(requests.size());
16959         boolean success = false;
16960         try {
16961             Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackagesLI");
16962             for (InstallRequest request : requests) {
16963                 // TODO(b/109941548): remove this once we've pulled everything from it and into
16964                 //                    scan, reconcile or commit.
16965                 final PrepareResult prepareResult;
16966                 try {
16967                     Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "preparePackage");
16968                     prepareResult = preparePackageLI(request.args, request.installResult);
16969                 } catch (PrepareFailure prepareFailure) {
16970                     request.installResult.setError(prepareFailure.error,
16971                             prepareFailure.getMessage());
16972                     request.installResult.origPackage = prepareFailure.conflictingPackage;
16973                     request.installResult.origPermission = prepareFailure.conflictingPermission;
16974                     return;
16975                 } finally {
16976                     Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
16977                 }
16978                 request.installResult.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
16979                 request.installResult.installerPackageName = request.args.installerPackageName;
16980
16981                 final String packageName = prepareResult.packageToScan.packageName;
16982                 prepareResults.put(packageName, prepareResult);
16983                 installResults.put(packageName, request.installResult);
16984                 installArgs.put(packageName, request.args);
16985                 try {
16986                     final List<ScanResult> scanResults = scanPackageTracedLI(
16987                             prepareResult.packageToScan, prepareResult.parseFlags,
16988                             prepareResult.scanFlags, System.currentTimeMillis(),
16989                             request.args.user);
16990                     for (ScanResult result : scanResults) {
16991                         if (null != preparedScans.put(result.pkgSetting.pkg.packageName, result)) {
16992                             request.installResult.setError(
16993                                     PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE,
16994                                     "Duplicate package " + result.pkgSetting.pkg.packageName
16995                                             + " in multi-package install request.");
16996                             return;
16997                         }
16998                         createdAppId.put(packageName, optimisticallyRegisterAppId(result));
16999                         versionInfos.put(result.pkgSetting.pkg.packageName,
17000                                 getSettingsVersionForPackage(result.pkgSetting.pkg));
17001                         if (result.staticSharedLibraryInfo != null) {
17002                             final PackageSetting sharedLibLatestVersionSetting =
17003                                     getSharedLibLatestVersionSetting(result);
17004                             if (sharedLibLatestVersionSetting != null) {
17005                                 lastStaticSharedLibSettings.put(result.pkgSetting.pkg.packageName,
17006                                         sharedLibLatestVersionSetting);
17007                             }
17008                         }
17009                     }
17010                 } catch (PackageManagerException e) {
17011                     request.installResult.setError("Scanning Failed.", e);
17012                     return;
17013                 }
17014             }
17015             ReconcileRequest reconcileRequest = new ReconcileRequest(preparedScans, installArgs,
17016                     installResults,
17017                     prepareResults,
17018                     mSharedLibraries,
17019                     Collections.unmodifiableMap(mPackages), versionInfos,
17020                     lastStaticSharedLibSettings);
17021             CommitRequest commitRequest = null;
17022             synchronized (mPackages) {
17023                 Map<String, ReconciledPackage> reconciledPackages;
17024                 try {
17025                     Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "reconcilePackages");
17026                     reconciledPackages = reconcilePackagesLocked(
17027                             reconcileRequest, mSettings.mKeySetManagerService);
17028                 } catch (ReconcileFailure e) {
17029                     for (InstallRequest request : requests) {
17030                         request.installResult.setError("Reconciliation failed...", e);
17031                     }
17032                     return;
17033                 } finally {
17034                     Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17035                 }
17036                 try {
17037                     Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "commitPackages");
17038                     commitRequest = new CommitRequest(reconciledPackages,
17039                             sUserManager.getUserIds());
17040                     commitPackagesLocked(commitRequest);
17041                     success = true;
17042                 } finally {
17043                     for (PrepareResult result : prepareResults.values()) {
17044                         if (result.freezer != null) {
17045                             result.freezer.close();
17046                         }
17047                     }
17048                     Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17049                 }
17050             }
17051             executePostCommitSteps(commitRequest);
17052         } finally {
17053             if (!success) {
17054                 for (ScanResult result : preparedScans.values()) {
17055                     if (createdAppId.getOrDefault(result.request.pkg.packageName, false)) {
17056                         cleanUpAppIdCreation(result);
17057                     }
17058                 }
17059                 // TODO(patb): create a more descriptive reason than unknown in future release
17060                 // mark all non-failure installs as UNKNOWN so we do not treat them as success
17061                 for (InstallRequest request : requests) {
17062                     if (request.installResult.returnCode == PackageManager.INSTALL_SUCCEEDED) {
17063                         request.installResult.returnCode = PackageManager.INSTALL_UNKNOWN;
17064                     }
17065                 }
17066             }
17067             for (PrepareResult result : prepareResults.values()) {
17068                 if (result.freezer != null) {
17069                     result.freezer.close();
17070                 }
17071             }
17072             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17073         }
17074     }
17075
17076     /**
17077      * On successful install, executes remaining steps after commit completes and the package lock
17078      * is released. These are typically more expensive or require calls to installd, which often
17079      * locks on {@link #mPackages}.
17080      */
17081     private void executePostCommitSteps(CommitRequest commitRequest) {
17082         for (ReconciledPackage reconciledPkg : commitRequest.reconciledPackages.values()) {
17083             final boolean instantApp = ((reconciledPkg.scanResult.request.scanFlags
17084                             & PackageManagerService.SCAN_AS_INSTANT_APP) != 0);
17085             final PackageParser.Package pkg = reconciledPkg.pkgSetting.pkg;
17086             final String packageName = pkg.packageName;
17087             prepareAppDataAfterInstallLIF(pkg);
17088             if (reconciledPkg.prepareResult.clearCodeCache) {
17089                 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE | FLAG_STORAGE_CE
17090                         | FLAG_STORAGE_EXTERNAL | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
17091             }
17092             if (reconciledPkg.prepareResult.replace) {
17093                 mDexManager.notifyPackageUpdated(pkg.packageName,
17094                         pkg.baseCodePath, pkg.splitCodePaths);
17095             }
17096
17097             // Prepare the application profiles for the new code paths.
17098             // This needs to be done before invoking dexopt so that any install-time profile
17099             // can be used for optimizations.
17100             mArtManagerService.prepareAppProfiles(
17101                     pkg,
17102                     resolveUserIds(reconciledPkg.installArgs.user.getIdentifier()),
17103                     /* updateReferenceProfileContent= */ true);
17104
17105             // Check whether we need to dexopt the app.
17106             //
17107             // NOTE: it is IMPORTANT to call dexopt:
17108             //   - after doRename which will sync the package data from PackageParser.Package and
17109             //     its corresponding ApplicationInfo.
17110             //   - after installNewPackageLIF or replacePackageLIF which will update result with the
17111             //     uid of the application (pkg.applicationInfo.uid).
17112             //     This update happens in place!
17113             //
17114             // We only need to dexopt if the package meets ALL of the following conditions:
17115             //   1) it is not an instant app or if it is then dexopt is enabled via gservices.
17116             //   2) it is not debuggable.
17117             //
17118             // Note that we do not dexopt instant apps by default. dexopt can take some time to
17119             // complete, so we skip this step during installation. Instead, we'll take extra time
17120             // the first time the instant app starts. It's preferred to do it this way to provide
17121             // continuous progress to the useur instead of mysteriously blocking somewhere in the
17122             // middle of running an instant app. The default behaviour can be overridden
17123             // via gservices.
17124             final boolean performDexopt =
17125                     (!instantApp || Global.getInt(mContext.getContentResolver(),
17126                     Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0)
17127                     && ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0);
17128
17129             if (performDexopt) {
17130                 // Compile the layout resources.
17131                 if (SystemProperties.getBoolean(PRECOMPILE_LAYOUTS, false)) {
17132                     Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "compileLayouts");
17133                     mViewCompiler.compileLayouts(pkg);
17134                     Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17135                 }
17136
17137                 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt");
17138                 // Do not run PackageDexOptimizer through the local performDexOpt
17139                 // method because `pkg` may not be in `mPackages` yet.
17140                 //
17141                 // Also, don't fail application installs if the dexopt step fails.
17142                 DexoptOptions dexoptOptions = new DexoptOptions(packageName,
17143                         REASON_INSTALL,
17144                         DexoptOptions.DEXOPT_BOOT_COMPLETE
17145                                 | DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE);
17146                 mPackageDexOptimizer.performDexOpt(pkg,
17147                         null /* instructionSets */,
17148                         getOrCreateCompilerPackageStats(pkg),
17149                         mDexManager.getPackageUseInfoOrDefault(packageName),
17150                         dexoptOptions);
17151                 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17152             }
17153
17154             // Notify BackgroundDexOptService that the package has been changed.
17155             // If this is an update of a package which used to fail to compile,
17156             // BackgroundDexOptService will remove it from its blacklist.
17157             // TODO: Layering violation
17158             BackgroundDexOptService.notifyPackageChanged(packageName);
17159         }
17160     }
17161
17162     /**
17163      * The set of data needed to successfully install the prepared package. This includes data that
17164      * will be used to scan and reconcile the package.
17165      */
17166     private static class PrepareResult {
17167         public final int installReason;
17168         public final String volumeUuid;
17169         public final String installerPackageName;
17170         public final UserHandle user;
17171         public final boolean replace;
17172         public final int scanFlags;
17173         public final int parseFlags;
17174         @Nullable /* The original Package if it is being replaced, otherwise {@code null} */
17175         public final PackageParser.Package existingPackage;
17176         public final PackageParser.Package packageToScan;
17177         public final boolean clearCodeCache;
17178         public final boolean system;
17179         /* The original package name if it was changed during an update, otherwise {@code null}. */
17180         @Nullable
17181         public final String renamedPackage;
17182         public final PackageFreezer freezer;
17183         public final PackageSetting originalPs;
17184         public final PackageSetting disabledPs;
17185         public final PackageSetting[] childPackageSettings;
17186
17187         private PrepareResult(int installReason, String volumeUuid,
17188                 String installerPackageName, UserHandle user, boolean replace, int scanFlags,
17189                 int parseFlags, PackageParser.Package existingPackage,
17190                 PackageParser.Package packageToScan, boolean clearCodeCache, boolean system,
17191                 String renamedPackage, PackageFreezer freezer, PackageSetting originalPs,
17192                 PackageSetting disabledPs, PackageSetting[] childPackageSettings) {
17193             this.installReason = installReason;
17194             this.volumeUuid = volumeUuid;
17195             this.installerPackageName = installerPackageName;
17196             this.user = user;
17197             this.replace = replace;
17198             this.scanFlags = scanFlags;
17199             this.parseFlags = parseFlags;
17200             this.existingPackage = existingPackage;
17201             this.packageToScan = packageToScan;
17202             this.clearCodeCache = clearCodeCache;
17203             this.system = system;
17204             this.renamedPackage = renamedPackage;
17205             this.freezer = freezer;
17206             this.originalPs = originalPs;
17207             this.disabledPs = disabledPs;
17208             this.childPackageSettings = childPackageSettings;
17209         }
17210     }
17211
17212     private static class PrepareFailure extends PackageManagerException {
17213
17214         public String conflictingPackage;
17215         public String conflictingPermission;
17216
17217         PrepareFailure(int error) {
17218             super(error, "Failed to prepare for install.");
17219         }
17220
17221         PrepareFailure(int error, String detailMessage) {
17222             super(error, detailMessage);
17223         }
17224
17225         PrepareFailure(String message, Exception e) {
17226             super(e instanceof PackageParserException
17227                     ? ((PackageParserException) e).error
17228                     : ((PackageManagerException) e).error,
17229                     ExceptionUtils.getCompleteMessage(message, e));
17230         }
17231
17232         PrepareFailure conflictsWithExistingPermission(String conflictingPermission,
17233                 String conflictingPackage) {
17234             this.conflictingPermission = conflictingPermission;
17235             this.conflictingPackage = conflictingPackage;
17236             return this;
17237         }
17238     }
17239
17240     @GuardedBy("mInstallLock")
17241     private PrepareResult preparePackageLI(InstallArgs args, PackageInstalledInfo res)
17242             throws PrepareFailure {
17243         final int installFlags = args.installFlags;
17244         final String installerPackageName = args.installerPackageName;
17245         final String volumeUuid = args.volumeUuid;
17246         final File tmpPackageFile = new File(args.getCodePath());
17247         final boolean onExternal = args.volumeUuid != null;
17248         final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0);
17249         final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0);
17250         final boolean virtualPreload =
17251                 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0);
17252         @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
17253         if (args.move != null) {
17254             // moving a complete application; perform an initial scan on the new install location
17255             scanFlags |= SCAN_INITIAL;
17256         }
17257         if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
17258             scanFlags |= SCAN_DONT_KILL_APP;
17259         }
17260         if (instantApp) {
17261             scanFlags |= SCAN_AS_INSTANT_APP;
17262         }
17263         if (fullApp) {
17264             scanFlags |= SCAN_AS_FULL_APP;
17265         }
17266         if (virtualPreload) {
17267             scanFlags |= SCAN_AS_VIRTUAL_PRELOAD;
17268         }
17269
17270         if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
17271
17272         // Sanity check
17273         if (instantApp && onExternal) {
17274             Slog.i(TAG, "Incompatible ephemeral install; external=" + onExternal);
17275             throw new PrepareFailure(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17276         }
17277
17278         // Retrieve PackageSettings and parse package
17279         @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
17280                 | PackageParser.PARSE_ENFORCE_CODE
17281                 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
17282
17283         PackageParser pp = new PackageParser();
17284         pp.setSeparateProcesses(mSeparateProcesses);
17285         pp.setDisplayMetrics(mMetrics);
17286         pp.setCallback(mPackageParserCallback);
17287
17288         Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage");
17289         final PackageParser.Package pkg;
17290         try {
17291             pkg = pp.parsePackage(tmpPackageFile, parseFlags);
17292             DexMetadataHelper.validatePackageDexMetadata(pkg);
17293         } catch (PackageParserException e) {
17294             throw new PrepareFailure("Failed parse during installPackageLI", e);
17295         } finally {
17296             Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
17297         }
17298
17299         // Instant apps have several additional install-time checks.
17300         if (instantApp) {
17301             if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) {
17302                 Slog.w(TAG,
17303                         "Instant app package " + pkg.packageName + " does not target at least O");
17304                 throw new PrepareFailure(INSTALL_FAILED_INSTANT_APP_INVALID,
17305                         "Instant app package must target at least O");
17306             }
17307             if (pkg.mSharedUserId != null) {
17308                 Slog.w(TAG, "Instant app package " + pkg.packageName
17309                         + " may not declare sharedUserId.");
17310                 throw new PrepareFailure(INSTALL_FAILED_INSTANT_APP_INVALID,
17311                         "Instant app package may not declare a sharedUserId");
17312             }
17313         }
17314
17315         if (pkg.applicationInfo.isStaticSharedLibrary()) {
17316             // Static shared libraries have synthetic package names
17317             renameStaticSharedLibraryPackage(pkg);
17318
17319             // No static shared libs on external storage
17320             if (onExternal) {
17321                 Slog.i(TAG, "Static shared libs can only be installed on internal storage.");
17322                 throw new PrepareFailure(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17323                         "Packages declaring static-shared libs cannot be updated");
17324             }
17325         }
17326
17327         // If we are installing a clustered package add results for the children
17328         if (pkg.childPackages != null) {
17329             synchronized (mPackages) {
17330                 final int childCount = pkg.childPackages.size();
17331                 for (int i = 0; i < childCount; i++) {
17332                     PackageParser.Package childPkg = pkg.childPackages.get(i);
17333                     PackageInstalledInfo childRes = new PackageInstalledInfo();
17334                     childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17335                     childRes.pkg = childPkg;
17336                     childRes.name = childPkg.packageName;
17337                     PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName);
17338                     if (childPs != null) {
17339                         childRes.origUsers = childPs.queryInstalledUsers(
17340                                 sUserManager.getUserIds(), true);
17341                     }
17342                     if ((mPackages.containsKey(childPkg.packageName))) {
17343                         childRes.removedInfo = new PackageRemovedInfo(this);
17344                         childRes.removedInfo.removedPackage = childPkg.packageName;
17345                         childRes.removedInfo.installerPackageName = childPs.installerPackageName;
17346                     }
17347                     if (res.addedChildPackages == null) {
17348                         res.addedChildPackages = new ArrayMap<>();
17349                     }
17350                     res.addedChildPackages.put(childPkg.packageName, childRes);
17351                 }
17352             }
17353         }
17354
17355         // If package doesn't declare API override, mark that we have an install
17356         // time CPU ABI override.
17357         if (TextUtils.isEmpty(pkg.cpuAbiOverride)) {
17358             pkg.cpuAbiOverride = args.abiOverride;
17359         }
17360
17361         String pkgName = res.name = pkg.packageName;
17362         if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0) {
17363             if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
17364                 throw new PrepareFailure(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
17365             }
17366         }
17367
17368         try {
17369             // either use what we've been given or parse directly from the APK
17370             if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) {
17371                 pkg.setSigningDetails(args.signingDetails);
17372             } else {
17373                 PackageParser.collectCertificates(pkg, false /* skipVerify */);
17374             }
17375         } catch (PackageParserException e) {
17376             throw new PrepareFailure("Failed collect during installPackageLI", e);
17377         }
17378
17379         if (instantApp && pkg.mSigningDetails.signatureSchemeVersion
17380                 < SignatureSchemeVersion.SIGNING_BLOCK_V2) {
17381             Slog.w(TAG, "Instant app package " + pkg.packageName
17382                     + " is not signed with at least APK Signature Scheme v2");
17383             throw new PrepareFailure(INSTALL_FAILED_INSTANT_APP_INVALID,
17384                     "Instant app package must be signed with APK Signature Scheme v2 or greater");
17385         }
17386
17387         // Get rid of all references to package scan path via parser.
17388         pp = null;
17389         boolean systemApp = false;
17390         boolean replace = false;
17391         synchronized (mPackages) {
17392             // Check if installing already existing package
17393             if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
17394                 String oldName = mSettings.getRenamedPackageLPr(pkgName);
17395                 if (pkg.mOriginalPackages != null
17396                         && pkg.mOriginalPackages.contains(oldName)
17397                         && mPackages.containsKey(oldName)) {
17398                     // This package is derived from an original package,
17399                     // and this device has been updating from that original
17400                     // name.  We must continue using the original name, so
17401                     // rename the new package here.
17402                     pkg.setPackageName(oldName);
17403                     pkgName = pkg.packageName;
17404                     replace = true;
17405                     if (DEBUG_INSTALL) {
17406                         Slog.d(TAG, "Replacing existing renamed package: oldName="
17407                                 + oldName + " pkgName=" + pkgName);
17408                     }
17409                 } else if (mPackages.containsKey(pkgName)) {
17410                     // This package, under its official name, already exists
17411                     // on the device; we should replace it.
17412                     replace = true;
17413                     if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
17414                 }
17415
17416                 // Child packages are installed through the parent package
17417                 if (pkg.parentPackage != null) {
17418                     throw new PrepareFailure(
17419                             PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17420                             "Package " + pkg.packageName + " is child of package "
17421                                     + pkg.parentPackage.parentPackage + ". Child packages "
17422                                     + "can be updated only through the parent package.");
17423                 }
17424
17425                 if (replace) {
17426                     // Prevent apps opting out from runtime permissions
17427                     PackageParser.Package oldPackage = mPackages.get(pkgName);
17428                     final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion;
17429                     final int newTargetSdk = pkg.applicationInfo.targetSdkVersion;
17430                     if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
17431                             && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
17432                         throw new PrepareFailure(
17433                                 PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
17434                                 "Package " + pkg.packageName + " new target SDK " + newTargetSdk
17435                                         + " doesn't support runtime permissions but the old"
17436                                         + " target SDK " + oldTargetSdk + " does.");
17437                     }
17438                     // Prevent persistent apps from being updated
17439                     if (((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0)
17440                             && ((installFlags & PackageManager.INSTALL_STAGED) == 0)) {
17441                         throw new PrepareFailure(PackageManager.INSTALL_FAILED_INVALID_APK,
17442                                 "Package " + oldPackage.packageName + " is a persistent app. "
17443                                         + "Persistent apps are not updateable.");
17444                     }
17445                     // Prevent installing of child packages
17446                     if (oldPackage.parentPackage != null) {
17447                         throw new PrepareFailure(
17448                                 PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME,
17449                                 "Package " + pkg.packageName + " is child of package "
17450                                         + oldPackage.parentPackage + ". Child packages "
17451                                         + "can be updated only through the parent package.");
17452                     }
17453                 }
17454             }
17455
17456             PackageSetting ps = mSettings.mPackages.get(pkgName);
17457             if (ps != null) {
17458                 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
17459
17460                 // Static shared libs have same package with different versions where
17461                 // we internally use a synthetic package name to allow multiple versions
17462                 // of the same package, therefore we need to compare signatures against
17463                 // the package setting for the latest library version.
17464                 PackageSetting signatureCheckPs = ps;
17465                 if (pkg.applicationInfo.isStaticSharedLibrary()) {
17466                     SharedLibraryInfo libraryInfo = getLatestSharedLibraVersionLPr(pkg);
17467                     if (libraryInfo != null) {
17468                         signatureCheckPs = mSettings.getPackageLPr(libraryInfo.getPackageName());
17469                     }
17470                 }
17471
17472                 // Quick sanity check that we're signed correctly if updating;
17473                 // we'll check this again later when scanning, but we want to
17474                 // bail early here before tripping over redefined permissions.
17475                 final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17476                 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) {
17477                     if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) {
17478                         throw new PrepareFailure(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
17479                                 + pkg.packageName + " upgrade keys do not match the "
17480                                 + "previously installed version");
17481                     }
17482                 } else {
17483                     try {
17484                         final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg);
17485                         final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg);
17486                         // We don't care about disabledPkgSetting on install for now.
17487                         final boolean compatMatch = verifySignatures(
17488                                 signatureCheckPs, null, pkg.mSigningDetails, compareCompat,
17489                                 compareRecover);
17490                         // The new KeySets will be re-added later in the scanning process.
17491                         if (compatMatch) {
17492                             synchronized (mPackages) {
17493                                 ksms.removeAppKeySetDataLPw(pkg.packageName);
17494                             }
17495                         }
17496                     } catch (PackageManagerException e) {
17497                         throw new PrepareFailure(e.error, e.getMessage());
17498                     }
17499                 }
17500
17501                 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
17502                     systemApp = (ps.pkg.applicationInfo.flags &
17503                             ApplicationInfo.FLAG_SYSTEM) != 0;
17504                 }
17505                 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
17506             }
17507
17508
17509             int N = pkg.permissions.size();
17510             for (int i = N - 1; i >= 0; i--) {
17511                 final PackageParser.Permission perm = pkg.permissions.get(i);
17512                 final BasePermission bp =
17513                         (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name);
17514
17515                 // Don't allow anyone but the system to define ephemeral permissions.
17516                 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0
17517                         && !systemApp) {
17518                     Slog.w(TAG, "Non-System package " + pkg.packageName
17519                             + " attempting to delcare ephemeral permission "
17520                             + perm.info.name + "; Removing ephemeral.");
17521                     perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT;
17522                 }
17523
17524                 // Check whether the newly-scanned package wants to define an already-defined perm
17525                 if (bp != null) {
17526                     // If the defining package is signed with our cert, it's okay.  This
17527                     // also includes the "updating the same package" case, of course.
17528                     // "updating same package" could also involve key-rotation.
17529                     final boolean sigsOk;
17530                     final String sourcePackageName = bp.getSourcePackageName();
17531                     final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting();
17532                     final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17533                     if (sourcePackageName.equals(pkg.packageName)
17534                             && (ksms.shouldCheckUpgradeKeySetLocked(
17535                             sourcePackageSetting, scanFlags))) {
17536                         sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg);
17537                     } else {
17538
17539                         // in the event of signing certificate rotation, we need to see if the
17540                         // package's certificate has rotated from the current one, or if it is an
17541                         // older certificate with which the current is ok with sharing permissions
17542                         if (sourcePackageSetting.signatures.mSigningDetails.checkCapability(
17543                                 pkg.mSigningDetails,
17544                                 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17545                             sigsOk = true;
17546                         } else if (pkg.mSigningDetails.checkCapability(
17547                                 sourcePackageSetting.signatures.mSigningDetails,
17548                                 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) {
17549
17550                             // the scanned package checks out, has signing certificate rotation
17551                             // history, and is newer; bring it over
17552                             sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails;
17553                             sigsOk = true;
17554                         } else {
17555                             sigsOk = false;
17556                         }
17557                     }
17558                     if (!sigsOk) {
17559                         // If the owning package is the system itself, we log but allow
17560                         // install to proceed; we fail the install on all other permission
17561                         // redefinitions.
17562                         if (!sourcePackageName.equals("android")) {
17563                             throw new PrepareFailure(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
17564                                     + pkg.packageName
17565                                     + " attempting to redeclare permission "
17566                                     + perm.info.name + " already owned by "
17567                                     + sourcePackageName)
17568                                     .conflictsWithExistingPermission(perm.info.name,
17569                                             sourcePackageName);
17570                         } else {
17571                             Slog.w(TAG, "Package " + pkg.packageName
17572                                     + " attempting to redeclare system permission "
17573                                     + perm.info.name + "; ignoring new declaration");
17574                             pkg.permissions.remove(i);
17575                         }
17576                     } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) {
17577                         // Prevent apps to change protection level to dangerous from any other
17578                         // type as this would allow a privilege escalation where an app adds a
17579                         // normal/signature permission in other app's group and later redefines
17580                         // it as dangerous leading to the group auto-grant.
17581                         if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE)
17582                                 == PermissionInfo.PROTECTION_DANGEROUS) {
17583                             if (bp != null && !bp.isRuntime()) {
17584                                 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a "
17585                                         + "non-runtime permission " + perm.info.name
17586                                         + " to runtime; keeping old protection level");
17587                                 perm.info.protectionLevel = bp.getProtectionLevel();
17588                             }
17589                         }
17590                     }
17591                 }
17592             }
17593         }
17594
17595         if (systemApp) {
17596             if (onExternal) {
17597                 // Abort update; system app can't be replaced with app on sdcard
17598                 throw new PrepareFailure(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
17599                         "Cannot install updates to system apps on sdcard");
17600             } else if (instantApp) {
17601                 // Abort update; system app can't be replaced with an instant app
17602                 throw new PrepareFailure(INSTALL_FAILED_INSTANT_APP_INVALID,
17603                         "Cannot update a system app with an instant app");
17604             }
17605         }
17606
17607         if (args.move != null) {
17608             // We did an in-place move, so dex is ready to roll
17609             scanFlags |= SCAN_NO_DEX;
17610             scanFlags |= SCAN_MOVE;
17611
17612             synchronized (mPackages) {
17613                 final PackageSetting ps = mSettings.mPackages.get(pkgName);
17614                 if (ps == null) {
17615                     res.setError(INSTALL_FAILED_INTERNAL_ERROR,
17616                             "Missing settings for moved package " + pkgName);
17617                 }
17618
17619                 // We moved the entire application as-is, so bring over the
17620                 // previously derived ABI information.
17621                 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
17622                 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
17623             }
17624
17625         } else {
17626             // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
17627             scanFlags |= SCAN_NO_DEX;
17628
17629             try {
17630                 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ?
17631                         args.abiOverride : pkg.cpuAbiOverride);
17632                 final boolean extractNativeLibs = !pkg.isLibrary();
17633                 derivePackageAbi(pkg, abiOverride, extractNativeLibs);
17634             } catch (PackageManagerException pme) {
17635                 Slog.e(TAG, "Error deriving application ABI", pme);
17636                 throw new PrepareFailure(INSTALL_FAILED_INTERNAL_ERROR,
17637                         "Error deriving application ABI");
17638             }
17639         }
17640
17641         if (!args.doRename(res.returnCode, pkg)) {
17642             throw new PrepareFailure(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
17643         }
17644
17645         try {
17646             setUpFsVerityIfPossible(pkg);
17647         } catch (InstallerException | IOException | DigestException | NoSuchAlgorithmException e) {
17648             throw new PrepareFailure(INSTALL_FAILED_INTERNAL_ERROR,
17649                     "Failed to set up verity: " + e);
17650         }
17651
17652         if (!instantApp) {
17653             startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg);
17654         } else {
17655             if (DEBUG_DOMAIN_VERIFICATION) {
17656                 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName);
17657             }
17658         }
17659         final PackageFreezer freezer =
17660                 freezePackageForInstall(pkgName, installFlags, "installPackageLI");
17661         boolean shouldCloseFreezerBeforeReturn = true;
17662         try {
17663             final PackageParser.Package existingPackage;
17664             String renamedPackage = null;
17665             boolean sysPkg = false;
17666             String targetVolumeUuid = volumeUuid;
17667             int targetScanFlags = scanFlags;
17668             int targetParseFlags = parseFlags;
17669             final PackageSetting ps;
17670             final PackageSetting disabledPs;
17671             final PackageSetting[] childPackages;
17672             if (replace) {
17673                 targetVolumeUuid = null;
17674                 if (pkg.applicationInfo.isStaticSharedLibrary()) {
17675                     // Static libs have a synthetic package name containing the version
17676                     // and cannot be updated as an update would get a new package name,
17677                     // unless this is the exact same version code which is useful for
17678                     // development.
17679                     PackageParser.Package existingPkg = mPackages.get(pkg.packageName);
17680                     if (existingPkg != null
17681                             && existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) {
17682                         throw new PrepareFailure(INSTALL_FAILED_DUPLICATE_PACKAGE,
17683                                 "Packages declaring "
17684                                         + "static-shared libs cannot be updated");
17685                     }
17686                 }
17687
17688                 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0;
17689
17690                 final PackageParser.Package oldPackage;
17691                 final String pkgName11 = pkg.packageName;
17692                 final int[] allUsers;
17693                 final int[] installedUsers;
17694
17695                 synchronized (mPackages) {
17696                     oldPackage = mPackages.get(pkgName11);
17697                     existingPackage = oldPackage;
17698                     if (DEBUG_INSTALL) {
17699                         Slog.d(TAG,
17700                                 "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
17701                     }
17702
17703                     ps = mSettings.mPackages.get(pkgName11);
17704                     disabledPs = mSettings.getDisabledSystemPkgLPr(ps);
17705
17706                     // verify signatures are valid
17707                     final KeySetManagerService ksms = mSettings.mKeySetManagerService;
17708                     if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) {
17709                         if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) {
17710                             throw new PrepareFailure(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17711                                     "New package not signed by keys specified by upgrade-keysets: "
17712                                             + pkgName11);
17713                         }
17714                     } else {
17715                         // default to original signature matching
17716                         if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails,
17717                                 SigningDetails.CertCapabilities.INSTALLED_DATA)
17718                                 && !oldPackage.mSigningDetails.checkCapability(
17719                                 pkg.mSigningDetails,
17720                                 SigningDetails.CertCapabilities.ROLLBACK)) {
17721                             throw new PrepareFailure(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
17722                                     "New package has a different signature: " + pkgName11);
17723                         }
17724                     }
17725
17726                     // don't allow a system upgrade unless the upgrade hash matches
17727                     if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) {
17728                         final byte[] digestBytes;
17729                         try {
17730                             final MessageDigest digest = MessageDigest.getInstance("SHA-512");
17731                             updateDigest(digest, new File(pkg.baseCodePath));
17732                             if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) {
17733                                 for (String path : pkg.splitCodePaths) {
17734                                     updateDigest(digest, new File(path));
17735                                 }
17736                             }
17737                             digestBytes = digest.digest();
17738                         } catch (NoSuchAlgorithmException | IOException e) {
17739                             throw new PrepareFailure(INSTALL_FAILED_INVALID_APK,
17740                                     "Could not compute hash: " + pkgName11);
17741                         }
17742                         if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) {
17743                             throw new PrepareFailure(INSTALL_FAILED_INVALID_APK,
17744                                     "New package fails restrict-update check: " + pkgName11);
17745                         }
17746                         // retain upgrade restriction
17747                         pkg.restrictUpdateHash = oldPackage.restrictUpdateHash;
17748                     }
17749
17750                     // Check for shared user id changes
17751                     String invalidPackageName =
17752                             getParentOrChildPackageChangedSharedUser(oldPackage, pkg);
17753                     if (invalidPackageName != null) {
17754                         throw new PrepareFailure(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
17755                                 "Package " + invalidPackageName + " tried to change user "
17756                                         + oldPackage.mSharedUserId);
17757                     }
17758
17759                     // In case of rollback, remember per-user/profile install state
17760                     allUsers = sUserManager.getUserIds();
17761                     installedUsers = ps.queryInstalledUsers(allUsers, true);
17762
17763
17764                     // don't allow an upgrade from full to ephemeral
17765                     if (isInstantApp) {
17766                         if (args.user == null || args.user.getIdentifier() == UserHandle.USER_ALL) {
17767                             for (int currentUser : allUsers) {
17768                                 if (!ps.getInstantApp(currentUser)) {
17769                                     // can't downgrade from full to instant
17770                                     Slog.w(TAG,
17771                                             "Can't replace full app with instant app: " + pkgName11
17772                                                     + " for user: " + currentUser);
17773                                     throw new PrepareFailure(
17774                                             PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17775                                 }
17776                             }
17777                         } else if (!ps.getInstantApp(args.user.getIdentifier())) {
17778                             // can't downgrade from full to instant
17779                             Slog.w(TAG, "Can't replace full app with instant app: " + pkgName11
17780                                     + " for user: " + args.user.getIdentifier());
17781                             throw new PrepareFailure(
17782                                     PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID);
17783                         }
17784                     }
17785                 }
17786
17787                 // Update what is removed
17788                 res.removedInfo = new PackageRemovedInfo(this);
17789                 res.removedInfo.uid = oldPackage.applicationInfo.uid;
17790                 res.removedInfo.removedPackage = oldPackage.packageName;
17791                 res.removedInfo.installerPackageName = ps.installerPackageName;
17792                 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null;
17793                 res.removedInfo.isUpdate = true;
17794                 res.removedInfo.origUsers = installedUsers;
17795                 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length);
17796                 for (int i = 0; i < installedUsers.length; i++) {
17797                     final int userId = installedUsers[i];
17798                     res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId));
17799                 }
17800
17801                 childPackages = mSettings.getChildSettingsLPr(ps);
17802                 if (childPackages != null) {
17803                     for (PackageSetting childPs : childPackages) {
17804                         boolean childPackageUpdated = false;
17805                         PackageParser.Package childPkg = (childPs == null) ? null : childPs.pkg;
17806                         if (res.addedChildPackages != null) {
17807                             PackageInstalledInfo childRes = res.addedChildPackages.get(
17808                                     childPkg.packageName);
17809                             if (childRes != null) {
17810                                 childRes.removedInfo.uid = childPkg.applicationInfo.uid;
17811                                 childRes.removedInfo.removedPackage = childPkg.packageName;
17812                                 if (childPs != null) {
17813                                     childRes.removedInfo.installerPackageName =
17814                                             childPs.installerPackageName;
17815                                 }
17816                                 childRes.removedInfo.isUpdate = true;
17817                                 childRes.removedInfo.installReasons =
17818                                         res.removedInfo.installReasons;
17819                                 childPackageUpdated = true;
17820                             }
17821                         }
17822                         if (!childPackageUpdated) {
17823                             PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this);
17824                             childRemovedRes.removedPackage = childPkg.packageName;
17825                             if (childPs != null) {
17826                                 childRemovedRes.installerPackageName = childPs.installerPackageName;
17827                             }
17828                             childRemovedRes.isUpdate = false;
17829                             childRemovedRes.dataRemoved = true;
17830                             synchronized (mPackages) {
17831                                 if (childPs != null) {
17832                                     childRemovedRes.origUsers = childPs.queryInstalledUsers(
17833                                             allUsers,
17834                                             true);
17835                                 }
17836                             }
17837                             if (res.removedInfo.removedChildPackages == null) {
17838                                 res.removedInfo.removedChildPackages = new ArrayMap<>();
17839                             }
17840                             res.removedInfo.removedChildPackages.put(childPkg.packageName,
17841                                     childRemovedRes);
17842                         }
17843                     }
17844                 }
17845
17846
17847                 sysPkg = (isSystemApp(oldPackage));
17848                 if (sysPkg) {
17849                     // Set the system/privileged/oem/vendor/product flags as needed
17850                     final boolean privileged = isPrivilegedApp(oldPackage);
17851                     final boolean oem = isOemApp(oldPackage);
17852                     final boolean vendor = isVendorApp(oldPackage);
17853                     final boolean product = isProductApp(oldPackage);
17854                     final boolean odm = isOdmApp(oldPackage);
17855                     final @ParseFlags int systemParseFlags = parseFlags;
17856                     final @ScanFlags int systemScanFlags = scanFlags
17857                             | SCAN_AS_SYSTEM
17858                             | (privileged ? SCAN_AS_PRIVILEGED : 0)
17859                             | (oem ? SCAN_AS_OEM : 0)
17860                             | (vendor ? SCAN_AS_VENDOR : 0)
17861                             | (product ? SCAN_AS_PRODUCT : 0)
17862                             | (odm ? SCAN_AS_ODM : 0);
17863
17864                     if (DEBUG_INSTALL) {
17865                         Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
17866                                 + ", old=" + oldPackage);
17867                     }
17868                     res.setReturnCode(PackageManager.INSTALL_SUCCEEDED);
17869                     pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP,
17870                             ApplicationInfo.FLAG_UPDATED_SYSTEM_APP);
17871                     targetParseFlags = systemParseFlags;
17872                     targetScanFlags = systemScanFlags;
17873                 } else { // non system replace
17874                     replace = true;
17875                     if (DEBUG_INSTALL) {
17876                         Slog.d(TAG,
17877                                 "replaceNonSystemPackageLI: new=" + pkg + ", old="
17878                                         + oldPackage);
17879                     }
17880
17881                     String pkgName1 = oldPackage.packageName;
17882                     boolean deletedPkg = true;
17883                     boolean addedPkg = false;
17884                     boolean updatedSettings = false;
17885
17886                     final long origUpdateTime = (pkg.mExtras != null)
17887                             ? ((PackageSetting) pkg.mExtras).lastUpdateTime : 0;
17888
17889                 }
17890             } else { // new package install
17891                 ps = null;
17892                 childPackages = null;
17893                 disabledPs = null;
17894                 replace = false;
17895                 existingPackage = null;
17896                 // Remember this for later, in case we need to rollback this install
17897                 String pkgName1 = pkg.packageName;
17898
17899                 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
17900
17901                 // TODO(patb): MOVE TO RECONCILE
17902                 synchronized (mPackages) {
17903                     renamedPackage = mSettings.getRenamedPackageLPr(pkgName1);
17904                     if (renamedPackage != null) {
17905                         // A package with the same name is already installed, though
17906                         // it has been renamed to an older name.  The package we
17907                         // are trying to install should be installed as an update to
17908                         // the existing one, but that has not been requested, so bail.
17909                         throw new PrepareFailure(INSTALL_FAILED_ALREADY_EXISTS,
17910                                 "Attempt to re-install " + pkgName1
17911                                         + " without first uninstalling package running as "
17912                                         + renamedPackage);
17913                     }
17914                     if (mPackages.containsKey(pkgName1)) {
17915                         // Don't allow installation over an existing package with the same name.
17916                         throw new PrepareFailure(INSTALL_FAILED_ALREADY_EXISTS,
17917                                 "Attempt to re-install " + pkgName1
17918                                         + " without first uninstalling.");
17919                     }
17920                 }
17921             }
17922             // we're passing the freezer back to be closed in a later phase of install
17923             shouldCloseFreezerBeforeReturn = false;
17924
17925             return new PrepareResult(args.installReason, targetVolumeUuid, installerPackageName,
17926                     args.user, replace, targetScanFlags, targetParseFlags, existingPackage, pkg,
17927                     replace /* clearCodeCache */, sysPkg, renamedPackage, freezer,
17928                     ps, disabledPs, childPackages);
17929         } finally {
17930             if (shouldCloseFreezerBeforeReturn) {
17931                 freezer.close();
17932             }
17933         }
17934     }
17935
17936     /**
17937      * Set up fs-verity for the given package if possible.  This requires a feature flag of system
17938      * property to be enabled only if the kernel supports fs-verity.
17939      *
17940      * <p>When the feature flag is set to legacy mode, only APK is supported (with some experimental
17941      * kernel patches). In normal mode, all file format can be supported.
17942      */
17943     private void setUpFsVerityIfPossible(PackageParser.Package pkg) throws InstallerException,
17944             PrepareFailure, IOException, DigestException, NoSuchAlgorithmException {
17945         final boolean standardMode = PackageManagerServiceUtils.isApkVerityEnabled();
17946         final boolean legacyMode = PackageManagerServiceUtils.isLegacyApkVerityEnabled();
17947         if (!standardMode && !legacyMode) {
17948             return;
17949         }
17950
17951         // Collect files we care for fs-verity setup.
17952         ArrayMap<String, String> fsverityCandidates = new ArrayMap<>();
17953         if (legacyMode) {
17954             synchronized (mPackages) {
17955                 final PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
17956                 if (ps != null && ps.isPrivileged()) {
17957                     fsverityCandidates.put(pkg.baseCodePath, null);
17958                     if (pkg.splitCodePaths != null) {
17959                         for (String splitPath : pkg.splitCodePaths) {
17960                             fsverityCandidates.put(splitPath, null);
17961                         }
17962                     }
17963                 }
17964             }
17965         } else {
17966             // NB: These files will become only accessible if the signing key is loaded in kernel's
17967             // .fs-verity keyring.
17968             fsverityCandidates.put(pkg.baseCodePath,
17969                     VerityUtils.getFsveritySignatureFilePath(pkg.baseCodePath));
17970
17971             final String dmPath = DexMetadataHelper.buildDexMetadataPathForApk(pkg.baseCodePath);
17972             if (new File(dmPath).exists()) {
17973                 fsverityCandidates.put(dmPath, VerityUtils.getFsveritySignatureFilePath(dmPath));
17974             }
17975
17976             if (pkg.splitCodePaths != null) {
17977                 for (String path : pkg.splitCodePaths) {
17978                     fsverityCandidates.put(path, VerityUtils.getFsveritySignatureFilePath(path));
17979
17980                     final String splitDmPath = DexMetadataHelper.buildDexMetadataPathForApk(path);
17981                     if (new File(splitDmPath).exists()) {
17982                         fsverityCandidates.put(splitDmPath,
17983                                 VerityUtils.getFsveritySignatureFilePath(splitDmPath));
17984                     }
17985                 }
17986             }
17987         }
17988
17989         for (Map.Entry<String, String> entry : fsverityCandidates.entrySet()) {
17990             final String filePath = entry.getKey();
17991             final String signaturePath = entry.getValue();
17992
17993             if (!legacyMode) {
17994                 // fs-verity is optional for now.  Only set up if signature is provided.
17995                 if (new File(signaturePath).exists() && !VerityUtils.hasFsverity(filePath)) {
17996                     try {
17997                         VerityUtils.setUpFsverity(filePath, signaturePath);
17998                     } catch (IOException | DigestException | NoSuchAlgorithmException
17999                             | SecurityException e) {
18000                         throw new PrepareFailure(PackageManager.INSTALL_FAILED_BAD_SIGNATURE,
18001                                 "Failed to enable fs-verity: " + e);
18002                     }
18003                 }
18004                 continue;
18005             }
18006
18007             // In legacy mode, fs-verity can only be enabled by process with CAP_SYS_ADMIN.
18008             final VerityUtils.SetupResult result = VerityUtils.generateApkVeritySetupData(filePath);
18009             if (result.isOk()) {
18010                 if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling verity to " + filePath);
18011                 final FileDescriptor fd = result.getUnownedFileDescriptor();
18012                 try {
18013                     final byte[] rootHash = VerityUtils.generateApkVerityRootHash(filePath);
18014                     try {
18015                         // A file may already have fs-verity, e.g. when reused during a split
18016                         // install. If the measurement succeeds, no need to attempt to set up.
18017                         mInstaller.assertFsverityRootHashMatches(filePath, rootHash);
18018                     } catch (InstallerException e) {
18019                         mInstaller.installApkVerity(filePath, fd, result.getContentSize());
18020                         mInstaller.assertFsverityRootHashMatches(filePath, rootHash);
18021                     }
18022                 } finally {
18023                     IoUtils.closeQuietly(fd);
18024                 }
18025             } else if (result.isFailed()) {
18026                 throw new PrepareFailure(PackageManager.INSTALL_FAILED_BAD_SIGNATURE,
18027                         "Failed to generate verity");
18028             }
18029         }
18030     }
18031
18032     private void startIntentFilterVerifications(int userId, boolean replacing,
18033             PackageParser.Package pkg) {
18034         if (mIntentFilterVerifierComponent == null) {
18035             Slog.w(TAG, "No IntentFilter verification will not be done as "
18036                     + "there is no IntentFilterVerifier available!");
18037             return;
18038         }
18039
18040         final int verifierUid = getPackageUid(
18041                 mIntentFilterVerifierComponent.getPackageName(),
18042                 MATCH_DEBUG_TRIAGED_MISSING,
18043                 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId);
18044
18045         Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18046         msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid);
18047         mHandler.sendMessage(msg);
18048
18049         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
18050         for (int i = 0; i < childCount; i++) {
18051             PackageParser.Package childPkg = pkg.childPackages.get(i);
18052             msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
18053             msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid);
18054             mHandler.sendMessage(msg);
18055         }
18056     }
18057
18058     private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing,
18059             PackageParser.Package pkg) {
18060         int size = pkg.activities.size();
18061         if (size == 0) {
18062             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18063                     "No activity, so no need to verify any IntentFilter!");
18064             return;
18065         }
18066
18067         final boolean hasDomainURLs = hasDomainURLs(pkg);
18068         if (!hasDomainURLs) {
18069             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18070                     "No domain URLs, so no need to verify any IntentFilter!");
18071             return;
18072         }
18073
18074         if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId
18075                 + " if any IntentFilter from the " + size
18076                 + " Activities needs verification ...");
18077
18078         int count = 0;
18079         final String packageName = pkg.packageName;
18080
18081         synchronized (mPackages) {
18082             // If this is a new install and we see that we've already run verification for this
18083             // package, we have nothing to do: it means the state was restored from backup.
18084             if (!replacing) {
18085                 IntentFilterVerificationInfo ivi =
18086                         mSettings.getIntentFilterVerificationLPr(packageName);
18087                 if (ivi != null) {
18088                     if (DEBUG_DOMAIN_VERIFICATION) {
18089                         Slog.i(TAG, "Package " + packageName+ " already verified: status="
18090                                 + ivi.getStatusString());
18091                     }
18092                     return;
18093                 }
18094             }
18095
18096             // If any filters need to be verified, then all need to be.
18097             boolean needToVerify = false;
18098             for (PackageParser.Activity a : pkg.activities) {
18099                 for (ActivityIntentInfo filter : a.intents) {
18100                     if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) {
18101                         if (DEBUG_DOMAIN_VERIFICATION) {
18102                             Slog.d(TAG,
18103                                     "Intent filter needs verification, so processing all filters");
18104                         }
18105                         needToVerify = true;
18106                         break;
18107                     }
18108                 }
18109             }
18110
18111             if (needToVerify) {
18112                 final int verificationId = mIntentFilterVerificationToken++;
18113                 for (PackageParser.Activity a : pkg.activities) {
18114                     for (ActivityIntentInfo filter : a.intents) {
18115                         if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) {
18116                             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG,
18117                                     "Verification needed for IntentFilter:" + filter.toString());
18118                             mIntentFilterVerifier.addOneIntentFilterVerification(
18119                                     verifierUid, userId, verificationId, filter, packageName);
18120                             count++;
18121                         }
18122                     }
18123                 }
18124             }
18125         }
18126
18127         if (count > 0) {
18128             if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count
18129                     + " IntentFilter verification" + (count > 1 ? "s" : "")
18130                     +  " for userId:" + userId);
18131             mIntentFilterVerifier.startVerifications(userId);
18132         } else {
18133             if (DEBUG_DOMAIN_VERIFICATION) {
18134                 Slog.d(TAG, "No filters or not all autoVerify for " + packageName);
18135             }
18136         }
18137     }
18138
18139     @GuardedBy("mPackages")
18140     private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
18141         final ComponentName cn  = filter.activity.getComponentName();
18142         final String packageName = cn.getPackageName();
18143
18144         IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
18145                 packageName);
18146         if (ivi == null) {
18147             return true;
18148         }
18149         int status = ivi.getStatus();
18150         switch (status) {
18151             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
18152             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS:
18153             case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
18154                 return true;
18155
18156             default:
18157                 // Nothing to do
18158                 return false;
18159         }
18160     }
18161
18162     private static boolean isMultiArch(ApplicationInfo info) {
18163         return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
18164     }
18165
18166     private static boolean isExternal(PackageParser.Package pkg) {
18167         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18168     }
18169
18170     private static boolean isExternal(PackageSetting ps) {
18171         return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
18172     }
18173
18174     private static boolean isSystemApp(PackageParser.Package pkg) {
18175         return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
18176     }
18177
18178     private static boolean isPrivilegedApp(PackageParser.Package pkg) {
18179         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
18180     }
18181
18182     private static boolean isOemApp(PackageParser.Package pkg) {
18183         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0;
18184     }
18185
18186     private static boolean isVendorApp(PackageParser.Package pkg) {
18187         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0;
18188     }
18189
18190     private static boolean isProductApp(PackageParser.Package pkg) {
18191         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0;
18192     }
18193
18194     private static boolean isProductServicesApp(PackageParser.Package pkg) {
18195         return (pkg.applicationInfo.privateFlags
18196                 & ApplicationInfo.PRIVATE_FLAG_PRODUCT_SERVICES) != 0;
18197     }
18198
18199     private static boolean isOdmApp(PackageParser.Package pkg) {
18200         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_ODM) != 0;
18201     }
18202
18203     private static boolean hasDomainURLs(PackageParser.Package pkg) {
18204         return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
18205     }
18206
18207     private static boolean isSystemApp(PackageSetting ps) {
18208         return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
18209     }
18210
18211     private static boolean isUpdatedSystemApp(PackageSetting ps) {
18212         return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
18213     }
18214
18215     private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) {
18216         if (isExternal(pkg)) {
18217             if (TextUtils.isEmpty(pkg.volumeUuid)) {
18218                 return mSettings.getExternalVersion();
18219             } else {
18220                 return mSettings.findOrCreateVersion(pkg.volumeUuid);
18221             }
18222         } else {
18223             return mSettings.getInternalVersion();
18224         }
18225     }
18226
18227     private void deleteTempPackageFiles() {
18228         final FilenameFilter filter =
18229                 (dir, name) -> name.startsWith("vmdl") && name.endsWith(".tmp");
18230     }
18231
18232     @Override
18233     public void deletePackageAsUser(String packageName, int versionCode,
18234             IPackageDeleteObserver observer, int userId, int flags) {
18235         deletePackageVersioned(new VersionedPackage(packageName, versionCode),
18236                 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags);
18237     }
18238
18239     @Override
18240     public void deletePackageVersioned(VersionedPackage versionedPackage,
18241             final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) {
18242         final int callingUid = Binder.getCallingUid();
18243         mContext.enforceCallingOrSelfPermission(
18244                 android.Manifest.permission.DELETE_PACKAGES, null);
18245         final boolean canViewInstantApps = canViewInstantApps(callingUid, userId);
18246         Preconditions.checkNotNull(versionedPackage);
18247         Preconditions.checkNotNull(observer);
18248         Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(),
18249                 PackageManager.VERSION_CODE_HIGHEST,
18250                 Long.MAX_VALUE, "versionCode must be >= -1");
18251
18252         final String packageName = versionedPackage.getPackageName();
18253         final long versionCode = versionedPackage.getLongVersionCode();
18254         final String internalPackageName;
18255         synchronized (mPackages) {
18256             // Normalize package name to handle renamed packages and static libs
18257             internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode);
18258         }
18259
18260         final int uid = Binder.getCallingUid();
18261         if (!isOrphaned(internalPackageName)
18262                 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) {
18263             mHandler.post(() -> {
18264                 try {
18265                     final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
18266                     intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null));
18267                     intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder());
18268                     observer.onUserActionRequired(intent);
18269                 } catch (RemoteException re) {
18270                 }
18271             });
18272             return;
18273         }
18274         final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0;
18275         final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{userId};
18276         if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) {
18277             mContext.enforceCallingOrSelfPermission(
18278                     android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
18279                     "deletePackage for user " + userId);
18280         }
18281
18282         if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
18283             mHandler.post(() -> {
18284                 try {
18285                     observer.onPackageDeleted(packageName,
18286                             PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
18287                 } catch (RemoteException re) {
18288                 }
18289             });
18290             return;
18291         }
18292
18293         if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) {
18294             mHandler.post(() -> {
18295                 try {
18296                     observer.onPackageDeleted(packageName,
18297                             PackageManager.DELETE_FAILED_OWNER_BLOCKED, null);
18298                 } catch (RemoteException re) {
18299                 }
18300             });
18301             return;
18302         }
18303
18304         if (DEBUG_REMOVE) {
18305             Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId
18306                     + " deleteAllUsers: " + deleteAllUsers + " version="
18307                     + (versionCode == PackageManager.VERSION_CODE_HIGHEST
18308                     ? "VERSION_CODE_HIGHEST" : versionCode));
18309         }
18310         // Queue up an async operation since the package deletion may take a little while.
18311         mHandler.post(() -> {
18312             int returnCode;
18313             final PackageSetting ps = mSettings.mPackages.get(internalPackageName);
18314             boolean doDeletePackage = true;
18315             if (ps != null) {
18316                 final boolean targetIsInstantApp =
18317                         ps.getInstantApp(UserHandle.getUserId(callingUid));
18318                 doDeletePackage = !targetIsInstantApp
18319                         || canViewInstantApps;
18320             }
18321             if (doDeletePackage) {
18322                 if (!deleteAllUsers) {
18323                     returnCode = deletePackageX(internalPackageName, versionCode,
18324                             userId, deleteFlags);
18325                 } else {
18326                     int[] blockUninstallUserIds = getBlockUninstallForUsers(
18327                             internalPackageName, users);
18328                     // If nobody is blocking uninstall, proceed with delete for all users
18329                     if (ArrayUtils.isEmpty(blockUninstallUserIds)) {
18330                         returnCode = deletePackageX(internalPackageName, versionCode,
18331                                 userId, deleteFlags);
18332                     } else {
18333                         // Otherwise uninstall individually for users with blockUninstalls=false
18334                         final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS;
18335                         for (int userId1 : users) {
18336                             if (!ArrayUtils.contains(blockUninstallUserIds, userId1)) {
18337                                 returnCode = deletePackageX(internalPackageName, versionCode,
18338                                         userId1, userFlags);
18339                                 if (returnCode != PackageManager.DELETE_SUCCEEDED) {
18340                                     Slog.w(TAG, "Package delete failed for user " + userId1
18341                                             + ", returnCode " + returnCode);
18342                                 }
18343                             }
18344                         }
18345                         // The app has only been marked uninstalled for certain users.
18346                         // We still need to report that delete was blocked
18347                         returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED;
18348                     }
18349                 }
18350             } else {
18351                 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18352             }
18353             try {
18354                 observer.onPackageDeleted(packageName, returnCode, null);
18355             } catch (RemoteException e) {
18356                 Log.i(TAG, "Observer no longer exists.");
18357             } //end catch
18358         });
18359     }
18360
18361     private String resolveExternalPackageNameLPr(PackageParser.Package pkg) {
18362         if (pkg.staticSharedLibName != null) {
18363             return pkg.manifestPackageName;
18364         }
18365         return pkg.packageName;
18366     }
18367
18368     @GuardedBy("mPackages")
18369     private String resolveInternalPackageNameLPr(String packageName, long versionCode) {
18370         // Handle renamed packages
18371         String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName);
18372         packageName = normalizedPackageName != null ? normalizedPackageName : packageName;
18373
18374         // Is this a static library?
18375         LongSparseArray<SharedLibraryInfo> versionedLib =
18376                 mStaticLibsByDeclaringPackage.get(packageName);
18377         if (versionedLib == null || versionedLib.size() <= 0) {
18378             return packageName;
18379         }
18380
18381         // Figure out which lib versions the caller can see
18382         LongSparseLongArray versionsCallerCanSee = null;
18383         final int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
18384         if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID
18385                 && callingAppId != Process.ROOT_UID) {
18386             versionsCallerCanSee = new LongSparseLongArray();
18387             String libName = versionedLib.valueAt(0).getName();
18388             String[] uidPackages = getPackagesForUid(Binder.getCallingUid());
18389             if (uidPackages != null) {
18390                 for (String uidPackage : uidPackages) {
18391                     PackageSetting ps = mSettings.getPackageLPr(uidPackage);
18392                     final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName);
18393                     if (libIdx >= 0) {
18394                         final long libVersion = ps.usesStaticLibrariesVersions[libIdx];
18395                         versionsCallerCanSee.append(libVersion, libVersion);
18396                     }
18397                 }
18398             }
18399         }
18400
18401         // Caller can see nothing - done
18402         if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) {
18403             return packageName;
18404         }
18405
18406         // Find the version the caller can see and the app version code
18407         SharedLibraryInfo highestVersion = null;
18408         final int versionCount = versionedLib.size();
18409         for (int i = 0; i < versionCount; i++) {
18410             SharedLibraryInfo libraryInfo = versionedLib.valueAt(i);
18411             if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey(
18412                     libraryInfo.getLongVersion()) < 0) {
18413                 continue;
18414             }
18415             final long libVersionCode = libraryInfo.getDeclaringPackage().getLongVersionCode();
18416             if (versionCode != PackageManager.VERSION_CODE_HIGHEST) {
18417                 if (libVersionCode == versionCode) {
18418                     return libraryInfo.getPackageName();
18419                 }
18420             } else if (highestVersion == null) {
18421                 highestVersion = libraryInfo;
18422             } else if (libVersionCode  > highestVersion
18423                     .getDeclaringPackage().getLongVersionCode()) {
18424                 highestVersion = libraryInfo;
18425             }
18426         }
18427
18428         if (highestVersion != null) {
18429             return highestVersion.getPackageName();
18430         }
18431
18432         return packageName;
18433     }
18434
18435     boolean isCallerVerifier(int callingUid) {
18436         final int callingUserId = UserHandle.getUserId(callingUid);
18437         return mRequiredVerifierPackage != null &&
18438                 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId);
18439     }
18440
18441     private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) {
18442         if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID
18443               || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
18444             return true;
18445         }
18446         final int callingUserId = UserHandle.getUserId(callingUid);
18447         // If the caller installed the pkgName, then allow it to silently uninstall.
18448         if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) {
18449             return true;
18450         }
18451
18452         // Allow package verifier to silently uninstall.
18453         if (mRequiredVerifierPackage != null &&
18454                 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) {
18455             return true;
18456         }
18457
18458         // Allow package uninstaller to silently uninstall.
18459         if (mRequiredUninstallerPackage != null &&
18460                 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) {
18461             return true;
18462         }
18463
18464         // Allow storage manager to silently uninstall.
18465         if (mStorageManagerPackage != null &&
18466                 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) {
18467             return true;
18468         }
18469
18470         // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently
18471         // uninstall for device owner provisioning.
18472         if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid)
18473                 == PERMISSION_GRANTED) {
18474             return true;
18475         }
18476
18477         return false;
18478     }
18479
18480     private int[] getBlockUninstallForUsers(String packageName, int[] userIds) {
18481         int[] result = EMPTY_INT_ARRAY;
18482         for (int userId : userIds) {
18483             if (getBlockUninstallForUser(packageName, userId)) {
18484                 result = ArrayUtils.appendInt(result, userId);
18485             }
18486         }
18487         return result;
18488     }
18489
18490     @Override
18491     public boolean isPackageDeviceAdminOnAnyUser(String packageName) {
18492         final int callingUid = Binder.getCallingUid();
18493         if (checkUidPermission(android.Manifest.permission.MANAGE_USERS, callingUid)
18494                 != PERMISSION_GRANTED) {
18495             EventLog.writeEvent(0x534e4554, "128599183", -1, "");
18496             throw new SecurityException(android.Manifest.permission.MANAGE_USERS
18497                     + " permission is required to call this API");
18498         }
18499         if (getInstantAppPackageName(callingUid) != null
18500                 && !isCallerSameApp(packageName, callingUid)) {
18501             return false;
18502         }
18503         return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL);
18504     }
18505
18506     private boolean isPackageDeviceAdmin(String packageName, int userId) {
18507         IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
18508                 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
18509         try {
18510             if (dpm != null) {
18511                 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent(
18512                         /* callingUserOnly =*/ false);
18513                 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null
18514                         : deviceOwnerComponentName.getPackageName();
18515                 // Does the package contains the device owner?
18516                 // TODO Do we have to do it even if userId != UserHandle.USER_ALL?  Otherwise,
18517                 // this check is probably not needed, since DO should be registered as a device
18518                 // admin on some user too. (Original bug for this: b/17657954)
18519                 if (packageName.equals(deviceOwnerPackageName)) {
18520                     return true;
18521                 }
18522                 // Does it contain a device admin for any user?
18523                 int[] users;
18524                 if (userId == UserHandle.USER_ALL) {
18525                     users = sUserManager.getUserIds();
18526                 } else {
18527                     users = new int[]{userId};
18528                 }
18529                 for (int i = 0; i < users.length; ++i) {
18530                     if (dpm.packageHasActiveAdmins(packageName, users[i])) {
18531                         return true;
18532                     }
18533                 }
18534             }
18535         } catch (RemoteException e) {
18536         }
18537         return false;
18538     }
18539
18540     private boolean shouldKeepUninstalledPackageLPr(String packageName) {
18541         return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName);
18542     }
18543
18544     /**
18545      *  This method is an internal method that could be get invoked either
18546      *  to delete an installed package or to clean up a failed installation.
18547      *  After deleting an installed package, a broadcast is sent to notify any
18548      *  listeners that the package has been removed. For cleaning up a failed
18549      *  installation, the broadcast is not necessary since the package's
18550      *  installation wouldn't have sent the initial broadcast either
18551      *  The key steps in deleting a package are
18552      *  deleting the package information in internal structures like mPackages,
18553      *  deleting the packages base directories through installd
18554      *  updating mSettings to reflect current status
18555      *  persisting settings for later use
18556      *  sending a broadcast if necessary
18557      */
18558     int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) {
18559         final PackageRemovedInfo info = new PackageRemovedInfo(this);
18560         final boolean res;
18561
18562         final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0
18563                 ? UserHandle.USER_ALL : userId;
18564
18565         if (isPackageDeviceAdmin(packageName, removeUser)) {
18566             Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
18567             return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
18568         }
18569
18570         final PackageSetting uninstalledPs;
18571         final PackageSetting disabledSystemPs;
18572         final PackageParser.Package pkg;
18573
18574         // for the uninstall-updates case and restricted profiles, remember the per-
18575         // user handle installed state
18576         int[] allUsers;
18577         /** enabled state of the uninstalled application */
18578         final int origEnabledState;
18579         synchronized (mPackages) {
18580             uninstalledPs = mSettings.mPackages.get(packageName);
18581             if (uninstalledPs == null) {
18582                 Slog.w(TAG, "Not removing non-existent package " + packageName);
18583                 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18584             }
18585
18586             if (versionCode != PackageManager.VERSION_CODE_HIGHEST
18587                     && uninstalledPs.versionCode != versionCode) {
18588                 Slog.w(TAG, "Not removing package " + packageName + " with versionCode "
18589                         + uninstalledPs.versionCode + " != " + versionCode);
18590                 return PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18591             }
18592
18593             disabledSystemPs = mSettings.getDisabledSystemPkgLPr(packageName);
18594             // Save the enabled state before we delete the package. When deleting a stub
18595             // application we always set the enabled state to 'disabled'.
18596             origEnabledState = uninstalledPs == null
18597                     ? COMPONENT_ENABLED_STATE_DEFAULT : uninstalledPs.getEnabled(userId);
18598             // Static shared libs can be declared by any package, so let us not
18599             // allow removing a package if it provides a lib others depend on.
18600             pkg = mPackages.get(packageName);
18601
18602             allUsers = sUserManager.getUserIds();
18603
18604             if (pkg != null && pkg.staticSharedLibName != null) {
18605                 SharedLibraryInfo libraryInfo = getSharedLibraryInfoLPr(pkg.staticSharedLibName,
18606                         pkg.staticSharedLibVersion);
18607                 if (libraryInfo != null) {
18608                     for (int currUserId : allUsers) {
18609                         if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) {
18610                             continue;
18611                         }
18612                         List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr(
18613                                 libraryInfo, 0, currUserId);
18614                         if (!ArrayUtils.isEmpty(libClientPackages)) {
18615                             Slog.w(TAG, "Not removing package " + pkg.manifestPackageName
18616                                     + " hosting lib " + libraryInfo.getName() + " version "
18617                                     + libraryInfo.getLongVersion() + " used by " + libClientPackages
18618                                     + " for user " + currUserId);
18619                             return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY;
18620                         }
18621                     }
18622                 }
18623             }
18624
18625             info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true);
18626         }
18627
18628         final int freezeUser;
18629         if (isUpdatedSystemApp(uninstalledPs)
18630                 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) {
18631             // We're downgrading a system app, which will apply to all users, so
18632             // freeze them all during the downgrade
18633             freezeUser = UserHandle.USER_ALL;
18634         } else {
18635             freezeUser = removeUser;
18636         }
18637
18638         synchronized (mInstallLock) {
18639             if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
18640             try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser,
18641                     deleteFlags, "deletePackageX")) {
18642                 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers,
18643                         deleteFlags | PackageManager.DELETE_CHATTY, info, true, null);
18644             }
18645             synchronized (mPackages) {
18646                 if (res) {
18647                     if (pkg != null) {
18648                         mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers);
18649                     }
18650                     updateSequenceNumberLP(uninstalledPs, info.removedUsers);
18651                     updateInstantAppInstallerLocked(packageName);
18652                 }
18653             }
18654         }
18655
18656         if (res) {
18657             final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0;
18658             info.sendPackageRemovedBroadcasts(killApp);
18659             info.sendSystemPackageUpdatedBroadcasts();
18660             info.sendSystemPackageAppearedBroadcasts();
18661         }
18662         // Force a gc here.
18663         Runtime.getRuntime().gc();
18664         // Delete the resources here after sending the broadcast to let
18665         // other processes clean up before deleting resources.
18666         synchronized (mInstallLock) {
18667             if (info.args != null) {
18668                 info.args.doPostDeleteLI(true);
18669             }
18670             final PackageParser.Package stubPkg =
18671                     (disabledSystemPs == null) ? null : disabledSystemPs.pkg;
18672             if (stubPkg != null && stubPkg.isStub) {
18673                 synchronized (mPackages) {
18674                     // restore the enabled state of the stub; the state is overwritten when
18675                     // the stub is uninstalled
18676                     final PackageSetting stubPs = mSettings.mPackages.get(stubPkg.packageName);
18677                     if (stubPs != null) {
18678                         stubPs.setEnabled(origEnabledState, userId, "android");
18679                     }
18680                 }
18681                 if (origEnabledState == COMPONENT_ENABLED_STATE_DEFAULT
18682                         || origEnabledState == COMPONENT_ENABLED_STATE_ENABLED) {
18683                     if (DEBUG_COMPRESSION) {
18684                         Slog.i(TAG, "Enabling system stub after removal; pkg: "
18685                                 + stubPkg.packageName);
18686                     }
18687                     enableCompressedPackage(stubPkg);
18688                 }
18689             }
18690         }
18691
18692         return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
18693     }
18694
18695     static class PackageRemovedInfo {
18696         final PackageSender packageSender;
18697         String removedPackage;
18698         String installerPackageName;
18699         int uid = -1;
18700         int removedAppId = -1;
18701         int[] origUsers;
18702         int[] removedUsers = null;
18703         int[] broadcastUsers = null;
18704         int[] instantUserIds = null;
18705         SparseArray<Integer> installReasons;
18706         boolean isRemovedPackageSystemUpdate = false;
18707         boolean isUpdate;
18708         boolean dataRemoved;
18709         boolean removedForAllUsers;
18710         boolean isStaticSharedLib;
18711         // Clean up resources deleted packages.
18712         InstallArgs args = null;
18713         ArrayMap<String, PackageRemovedInfo> removedChildPackages;
18714         ArrayMap<String, PackageInstalledInfo> appearedChildPackages;
18715
18716         PackageRemovedInfo(PackageSender packageSender) {
18717             this.packageSender = packageSender;
18718         }
18719
18720         void sendPackageRemovedBroadcasts(boolean killApp) {
18721             sendPackageRemovedBroadcastInternal(killApp);
18722             final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0;
18723             for (int i = 0; i < childCount; i++) {
18724                 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18725                 childInfo.sendPackageRemovedBroadcastInternal(killApp);
18726             }
18727         }
18728
18729         void sendSystemPackageUpdatedBroadcasts() {
18730             if (isRemovedPackageSystemUpdate) {
18731                 sendSystemPackageUpdatedBroadcastsInternal();
18732                 final int childCount = (removedChildPackages != null)
18733                         ? removedChildPackages.size() : 0;
18734                 for (int i = 0; i < childCount; i++) {
18735                     PackageRemovedInfo childInfo = removedChildPackages.valueAt(i);
18736                     if (childInfo.isRemovedPackageSystemUpdate) {
18737                         childInfo.sendSystemPackageUpdatedBroadcastsInternal();
18738                     }
18739                 }
18740             }
18741         }
18742
18743         void sendSystemPackageAppearedBroadcasts() {
18744             final int packageCount = (appearedChildPackages != null)
18745                     ? appearedChildPackages.size() : 0;
18746             for (int i = 0; i < packageCount; i++) {
18747                 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i);
18748                 packageSender.sendPackageAddedForNewUsers(installedInfo.name,
18749                     true /*sendBootCompleted*/, false /*startReceiver*/,
18750                     UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null);
18751             }
18752         }
18753
18754         private void sendSystemPackageUpdatedBroadcastsInternal() {
18755             Bundle extras = new Bundle(2);
18756             extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
18757             extras.putBoolean(Intent.EXTRA_REPLACING, true);
18758             packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18759                 removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18760             packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18761                 removedPackage, extras, 0, null /*targetPackage*/, null, null, null);
18762             packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
18763                 null, null, 0, removedPackage, null, null, null);
18764             if (installerPackageName != null) {
18765                 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
18766                         removedPackage, extras, 0 /*flags*/,
18767                         installerPackageName, null, null, null);
18768                 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
18769                         removedPackage, extras, 0 /*flags*/,
18770                         installerPackageName, null, null, null);
18771             }
18772         }
18773
18774         private void sendPackageRemovedBroadcastInternal(boolean killApp) {
18775             // Don't send static shared library removal broadcasts as these
18776             // libs are visible only the the apps that depend on them an one
18777             // cannot remove the library if it has a dependency.
18778             if (isStaticSharedLib) {
18779                 return;
18780             }
18781             Bundle extras = new Bundle(2);
18782             final int removedUid = removedAppId >= 0  ? removedAppId : uid;
18783             extras.putInt(Intent.EXTRA_UID, removedUid);
18784             extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved);
18785             extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp);
18786             if (isUpdate || isRemovedPackageSystemUpdate) {
18787                 extras.putBoolean(Intent.EXTRA_REPLACING, true);
18788             }
18789             extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
18790             if (removedPackage != null) {
18791                 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18792                     removedPackage, extras, 0, null /*targetPackage*/, null,
18793                     broadcastUsers, instantUserIds);
18794                 if (installerPackageName != null) {
18795                     packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED,
18796                             removedPackage, extras, 0 /*flags*/,
18797                             installerPackageName, null, broadcastUsers, instantUserIds);
18798                 }
18799                 if (dataRemoved && !isRemovedPackageSystemUpdate) {
18800                     packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED,
18801                         removedPackage, extras,
18802                         Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18803                         null, null, broadcastUsers, instantUserIds);
18804                     packageSender.notifyPackageRemoved(removedPackage, removedUid);
18805                 }
18806             }
18807             if (removedAppId >= 0) {
18808                 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED,
18809                     null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND,
18810                     null, null, broadcastUsers, instantUserIds);
18811             }
18812         }
18813
18814         void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) {
18815             removedUsers = userIds;
18816             if (removedUsers == null) {
18817                 broadcastUsers = null;
18818                 return;
18819             }
18820
18821             broadcastUsers = EMPTY_INT_ARRAY;
18822             instantUserIds = EMPTY_INT_ARRAY;
18823             for (int i = userIds.length - 1; i >= 0; --i) {
18824                 final int userId = userIds[i];
18825                 if (deletedPackageSetting.getInstantApp(userId)) {
18826                     instantUserIds = ArrayUtils.appendInt(instantUserIds, userId);
18827                 } else {
18828                     broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId);
18829                 }
18830             }
18831         }
18832     }
18833
18834     /*
18835      * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
18836      * flag is not set, the data directory is removed as well.
18837      * make sure this flag is set for partially installed apps. If not its meaningless to
18838      * delete a partially installed application.
18839      */
18840     private void removePackageDataLIF(final PackageSetting deletedPs, int[] allUserHandles,
18841             PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
18842         String packageName = deletedPs.name;
18843         if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + deletedPs);
18844         // Retrieve object to delete permissions for shared user later on
18845         final PackageParser.Package deletedPkg = deletedPs.pkg;
18846         if (outInfo != null) {
18847             outInfo.removedPackage = packageName;
18848             outInfo.installerPackageName = deletedPs.installerPackageName;
18849             outInfo.isStaticSharedLib = deletedPkg != null
18850                     && deletedPkg.staticSharedLibName != null;
18851             outInfo.populateUsers(deletedPs == null ? null
18852                     : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs);
18853         }
18854
18855         removePackageLI(deletedPs.name, (flags & PackageManager.DELETE_CHATTY) != 0);
18856
18857         if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18858             final PackageParser.Package resolvedPkg;
18859             if (deletedPkg != null) {
18860                 resolvedPkg = deletedPkg;
18861             } else {
18862                 // We don't have a parsed package when it lives on an ejected
18863                 // adopted storage device, so fake something together
18864                 resolvedPkg = new PackageParser.Package(deletedPs.name);
18865                 resolvedPkg.setVolumeUuid(deletedPs.volumeUuid);
18866             }
18867             destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL,
18868                     FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL);
18869             destroyAppProfilesLIF(resolvedPkg);
18870             if (outInfo != null) {
18871                 outInfo.dataRemoved = true;
18872             }
18873         }
18874
18875         int removedAppId = -1;
18876
18877         // writer
18878         boolean installedStateChanged = false;
18879         if (deletedPs != null) {
18880             if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) {
18881                 final SparseBooleanArray changedUsers = new SparseBooleanArray();
18882                 synchronized (mPackages) {
18883                     clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
18884                     clearDefaultBrowserIfNeeded(packageName);
18885                     mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
18886                     removedAppId = mSettings.removePackageLPw(packageName);
18887                     if (outInfo != null) {
18888                         outInfo.removedAppId = removedAppId;
18889                     }
18890                     mPermissionManager.updatePermissions(
18891                             deletedPs.name, null, false, mPackages.values(), mPermissionCallback);
18892                     if (deletedPs.sharedUser != null) {
18893                         // Remove permissions associated with package. Since runtime
18894                         // permissions are per user we have to kill the removed package
18895                         // or packages running under the shared user of the removed
18896                         // package if revoking the permissions requested only by the removed
18897                         // package is successful and this causes a change in gids.
18898                         for (int userId : UserManagerService.getInstance().getUserIds()) {
18899                             final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
18900                                     userId);
18901                             if (userIdToKill == UserHandle.USER_ALL
18902                                     || userIdToKill >= UserHandle.USER_SYSTEM) {
18903                                 // If gids changed for this user, kill all affected packages.
18904                                 mHandler.post(() -> {
18905                                     // This has to happen with no lock held.
18906                                     killApplication(deletedPs.name, deletedPs.appId,
18907                                             KILL_APP_REASON_GIDS_CHANGED);
18908                                 });
18909                                 break;
18910                             }
18911                         }
18912                     }
18913                     clearPackagePreferredActivitiesLPw(
18914                             deletedPs.name, changedUsers, UserHandle.USER_ALL);
18915                 }
18916                 if (changedUsers.size() > 0) {
18917                     updateDefaultHomeNotLocked(changedUsers);
18918                     postPreferredActivityChangedBroadcast(UserHandle.USER_ALL);
18919                 }
18920             }
18921             // make sure to preserve per-user disabled state if this removal was just
18922             // a downgrade of a system app to the factory package
18923             if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) {
18924                 if (DEBUG_REMOVE) {
18925                     Slog.d(TAG, "Propagating install state across downgrade");
18926                 }
18927                 for (int userId : allUserHandles) {
18928                     final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId);
18929                     if (DEBUG_REMOVE) {
18930                         Slog.d(TAG, "    user " + userId + " => " + installed);
18931                     }
18932                     if (installed != deletedPs.getInstalled(userId)) {
18933                         installedStateChanged = true;
18934                     }
18935                     deletedPs.setInstalled(installed, userId);
18936                 }
18937             }
18938         }
18939         synchronized (mPackages) {
18940             // can downgrade to reader
18941             if (writeSettings) {
18942                 // Save settings now
18943                 mSettings.writeLPr();
18944             }
18945             if (installedStateChanged) {
18946                 mSettings.writeKernelMappingLPr(deletedPs);
18947             }
18948         }
18949         if (removedAppId != -1) {
18950             // A user ID was deleted here. Go through all users and remove it
18951             // from KeyStore.
18952             removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId);
18953         }
18954     }
18955
18956     static boolean locationIsPrivileged(String path) {
18957         try {
18958             final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
18959             final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app");
18960             final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app");
18961             final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app");
18962             final File privilegedProductServicesAppDir =
18963                     new File(Environment.getProductServicesDirectory(), "priv-app");
18964             return path.startsWith(privilegedAppDir.getCanonicalPath() + "/")
18965                     || path.startsWith(privilegedVendorAppDir.getCanonicalPath() + "/")
18966                     || path.startsWith(privilegedOdmAppDir.getCanonicalPath() + "/")
18967                     || path.startsWith(privilegedProductAppDir.getCanonicalPath() + "/")
18968                     || path.startsWith(privilegedProductServicesAppDir.getCanonicalPath() + "/");
18969         } catch (IOException e) {
18970             Slog.e(TAG, "Unable to access code path " + path);
18971         }
18972         return false;
18973     }
18974
18975     static boolean locationIsOem(String path) {
18976         try {
18977             return path.startsWith(Environment.getOemDirectory().getCanonicalPath() + "/");
18978         } catch (IOException e) {
18979             Slog.e(TAG, "Unable to access code path " + path);
18980         }
18981         return false;
18982     }
18983
18984     static boolean locationIsVendor(String path) {
18985         try {
18986             return path.startsWith(Environment.getVendorDirectory().getCanonicalPath() + "/")
18987                     || path.startsWith(Environment.getOdmDirectory().getCanonicalPath() + "/");
18988         } catch (IOException e) {
18989             Slog.e(TAG, "Unable to access code path " + path);
18990         }
18991         return false;
18992     }
18993
18994     static boolean locationIsProduct(String path) {
18995         try {
18996             return path.startsWith(Environment.getProductDirectory().getCanonicalPath() + "/");
18997         } catch (IOException e) {
18998             Slog.e(TAG, "Unable to access code path " + path);
18999         }
19000         return false;
19001     }
19002
19003     static boolean locationIsProductServices(String path) {
19004         try {
19005             return path.startsWith(
19006               Environment.getProductServicesDirectory().getCanonicalPath() + "/");
19007         } catch (IOException e) {
19008             Slog.e(TAG, "Unable to access code path " + path);
19009         }
19010         return false;
19011     }
19012
19013     static boolean locationIsOdm(String path) {
19014         try {
19015             return path.startsWith(Environment.getOdmDirectory().getCanonicalPath() + "/");
19016         } catch (IOException e) {
19017             Slog.e(TAG, "Unable to access code path " + path);
19018         }
19019         return false;
19020     }
19021
19022     /*
19023      * Tries to delete system package.
19024      */
19025     private void deleteSystemPackageLIF(DeletePackageAction action, PackageSetting deletedPs,
19026             int[] allUserHandles, int flags, PackageRemovedInfo outInfo, boolean writeSettings)
19027             throws SystemDeleteException {
19028         final boolean applyUserRestrictions
19029                 = (allUserHandles != null) && (outInfo.origUsers != null);
19030         final PackageParser.Package deletedPkg = deletedPs.pkg;
19031         // Confirm if the system package has been updated
19032         // An updated system app can be deleted. This will also have to restore
19033         // the system pkg from system partition
19034         // reader
19035         final PackageSetting disabledPs = action.disabledPs;
19036         if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName
19037                 + " disabledPs=" + disabledPs);
19038         Slog.d(TAG, "Deleting system pkg from data partition");
19039
19040         if (DEBUG_REMOVE) {
19041             if (applyUserRestrictions) {
19042                 Slog.d(TAG, "Remembering install states:");
19043                 for (int userId : allUserHandles) {
19044                     final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId);
19045                     Slog.d(TAG, "   u=" + userId + " inst=" + finstalled);
19046                 }
19047             }
19048         }
19049
19050         // Delete the updated package
19051         outInfo.isRemovedPackageSystemUpdate = true;
19052         if (outInfo.removedChildPackages != null) {
19053             final int childCount = (deletedPs.childPackageNames != null)
19054                     ? deletedPs.childPackageNames.size() : 0;
19055             for (int i = 0; i < childCount; i++) {
19056                 String childPackageName = deletedPs.childPackageNames.get(i);
19057                 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames
19058                         .contains(childPackageName)) {
19059                     PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19060                             childPackageName);
19061                     if (childInfo != null) {
19062                         childInfo.isRemovedPackageSystemUpdate = true;
19063                     }
19064                 }
19065             }
19066         }
19067
19068         if (disabledPs.versionCode < deletedPs.versionCode) {
19069             // Delete data for downgrades
19070             flags &= ~PackageManager.DELETE_KEEP_DATA;
19071         } else {
19072             // Preserve data by setting flag
19073             flags |= PackageManager.DELETE_KEEP_DATA;
19074         }
19075
19076         deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles,
19077                 outInfo, writeSettings, disabledPs.pkg);
19078
19079         // writer
19080         synchronized (mPackages) {
19081             // NOTE: The system package always needs to be enabled; even if it's for
19082             // a compressed stub. If we don't, installing the system package fails
19083             // during scan [scanning checks the disabled packages]. We will reverse
19084             // this later, after we've "installed" the stub.
19085             // Reinstate the old system package
19086             enableSystemPackageLPw(disabledPs.pkg);
19087             // Remove any native libraries from the upgraded package.
19088             removeNativeBinariesLI(deletedPs);
19089         }
19090
19091         // Install the system package
19092         if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
19093         try {
19094             installPackageFromSystemLIF(disabledPs.codePathString, allUserHandles,
19095                     outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings);
19096         } catch (PackageManagerException e) {
19097             Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": "
19098                     + e.getMessage());
19099             // TODO(patb): can we avoid this; throw would come from scan...
19100             throw new SystemDeleteException(e);
19101         } finally {
19102             if (disabledPs.pkg.isStub) {
19103                 // We've re-installed the stub; make sure it's disabled here. If package was
19104                 // originally enabled, we'll install the compressed version of the application
19105                 // and re-enable it afterward.
19106                 final PackageSetting stubPs = mSettings.mPackages.get(deletedPkg.packageName);
19107                 if (stubPs != null) {
19108                     stubPs.setEnabled(
19109                             COMPONENT_ENABLED_STATE_DISABLED, UserHandle.USER_SYSTEM, "android");
19110                 }
19111             }
19112         }
19113     }
19114
19115     /**
19116      * Installs a package that's already on the system partition.
19117      */
19118     private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString,
19119             @Nullable int[] allUserHandles, @Nullable int[] origUserHandles,
19120             @Nullable PermissionsState origPermissionState, boolean writeSettings)
19121                     throws PackageManagerException {
19122         @ParseFlags int parseFlags =
19123                 mDefParseFlags
19124                 | PackageParser.PARSE_MUST_BE_APK
19125                 | PackageParser.PARSE_IS_SYSTEM_DIR;
19126         @ScanFlags int scanFlags = SCAN_AS_SYSTEM;
19127         if (locationIsPrivileged(codePathString)) {
19128             scanFlags |= SCAN_AS_PRIVILEGED;
19129         }
19130         if (locationIsOem(codePathString)) {
19131             scanFlags |= SCAN_AS_OEM;
19132         }
19133         if (locationIsVendor(codePathString)) {
19134             scanFlags |= SCAN_AS_VENDOR;
19135         }
19136         if (locationIsProduct(codePathString)) {
19137             scanFlags |= SCAN_AS_PRODUCT;
19138         }
19139         if (locationIsProductServices(codePathString)) {
19140             scanFlags |= SCAN_AS_PRODUCT_SERVICES;
19141         }
19142         if (locationIsOdm(codePathString)) {
19143             scanFlags |= SCAN_AS_ODM;
19144         }
19145
19146         final File codePath = new File(codePathString);
19147         final PackageParser.Package pkg =
19148                 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null);
19149
19150         try {
19151             // update shared libraries for the newly re-installed system package
19152             updateSharedLibrariesLocked(pkg, null, Collections.unmodifiableMap(mPackages));
19153         } catch (PackageManagerException e) {
19154             Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
19155         }
19156
19157         prepareAppDataAfterInstallLIF(pkg);
19158
19159         // writer
19160         synchronized (mPackages) {
19161             PackageSetting ps = mSettings.mPackages.get(pkg.packageName);
19162
19163             // Propagate the permissions state as we do not want to drop on the floor
19164             // runtime permissions. The update permissions method below will take
19165             // care of removing obsolete permissions and grant install permissions.
19166             if (origPermissionState != null) {
19167                 ps.getPermissionsState().copyFrom(origPermissionState);
19168             }
19169             mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(),
19170                     mPermissionCallback);
19171
19172             final boolean applyUserRestrictions
19173                     = (allUserHandles != null) && (origUserHandles != null);
19174             if (applyUserRestrictions) {
19175                 boolean installedStateChanged = false;
19176                 if (DEBUG_REMOVE) {
19177                     Slog.d(TAG, "Propagating install state across reinstall");
19178                 }
19179                 for (int userId : allUserHandles) {
19180                     final boolean installed = ArrayUtils.contains(origUserHandles, userId);
19181                     if (DEBUG_REMOVE) {
19182                         Slog.d(TAG, "    user " + userId + " => " + installed);
19183                     }
19184                     if (installed != ps.getInstalled(userId)) {
19185                         installedStateChanged = true;
19186                     }
19187                     ps.setInstalled(installed, userId);
19188
19189                     mSettings.writeRuntimePermissionsForUserLPr(userId, false);
19190                 }
19191                 // Regardless of writeSettings we need to ensure that this restriction
19192                 // state propagation is persisted
19193                 mSettings.writeAllUsersPackageRestrictionsLPr();
19194                 if (installedStateChanged) {
19195                     mSettings.writeKernelMappingLPr(ps);
19196                 }
19197             }
19198             // can downgrade to reader here
19199             if (writeSettings) {
19200                 mSettings.writeLPr();
19201             }
19202         }
19203         return pkg;
19204     }
19205
19206     private void deleteInstalledPackageLIF(PackageSetting ps,
19207             boolean deleteCodeAndResources, int flags, int[] allUserHandles,
19208             PackageRemovedInfo outInfo, boolean writeSettings,
19209             PackageParser.Package replacingPackage) {
19210         synchronized (mPackages) {
19211             if (outInfo != null) {
19212                 outInfo.uid = ps.appId;
19213             }
19214
19215             if (outInfo != null && outInfo.removedChildPackages != null) {
19216                 final int childCount = (ps.childPackageNames != null)
19217                         ? ps.childPackageNames.size() : 0;
19218                 for (int i = 0; i < childCount; i++) {
19219                     String childPackageName = ps.childPackageNames.get(i);
19220                     PackageSetting childPs = mSettings.mPackages.get(childPackageName);
19221                     PackageRemovedInfo childInfo = outInfo.removedChildPackages.get(
19222                             childPackageName);
19223                     if (childInfo != null) {
19224                         childInfo.uid = childPs.appId;
19225                     }
19226                 }
19227             }
19228         }
19229
19230         // Delete package data from internal structures and also remove data if flag is set
19231         removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings);
19232
19233         // Delete the child packages data
19234         final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19235         for (int i = 0; i < childCount; i++) {
19236             PackageSetting childPs;
19237             synchronized (mPackages) {
19238                 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i));
19239             }
19240             if (childPs != null) {
19241                 PackageRemovedInfo childOutInfo = (outInfo != null
19242                         && outInfo.removedChildPackages != null)
19243                         ? outInfo.removedChildPackages.get(childPs.name) : null;
19244                 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0
19245                         && (replacingPackage != null
19246                         && !replacingPackage.hasChildPackage(childPs.name))
19247                         ? flags & ~DELETE_KEEP_DATA : flags;
19248                 removePackageDataLIF(childPs, allUserHandles, childOutInfo,
19249                         deleteFlags, writeSettings);
19250             }
19251         }
19252
19253         // Delete application code and resources only for parent packages
19254         if (ps.parentPackageName == null) {
19255             if (deleteCodeAndResources && (outInfo != null)) {
19256                 outInfo.args = createInstallArgsForExisting(
19257                         ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
19258                 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
19259             }
19260         }
19261     }
19262
19263     @Override
19264     public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
19265             int userId) {
19266         mContext.enforceCallingOrSelfPermission(
19267                 android.Manifest.permission.DELETE_PACKAGES, null);
19268         synchronized (mPackages) {
19269             // Cannot block uninstall of static shared libs as they are
19270             // considered a part of the using app (emulating static linking).
19271             // Also static libs are installed always on internal storage.
19272             PackageParser.Package pkg = mPackages.get(packageName);
19273             if (pkg != null && pkg.staticSharedLibName != null) {
19274                 Slog.w(TAG, "Cannot block uninstall of package: " + packageName
19275                         + " providing static shared library: " + pkg.staticSharedLibName);
19276                 return false;
19277             }
19278             mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall);
19279             mSettings.writePackageRestrictionsLPr(userId);
19280         }
19281         return true;
19282     }
19283
19284     @Override
19285     public boolean getBlockUninstallForUser(String packageName, int userId) {
19286         synchronized (mPackages) {
19287             final PackageSetting ps = mSettings.mPackages.get(packageName);
19288             if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) {
19289                 return false;
19290             }
19291             return mSettings.getBlockUninstallLPr(userId, packageName);
19292         }
19293     }
19294
19295     @Override
19296     public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) {
19297         enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root");
19298         synchronized (mPackages) {
19299             PackageSetting ps = mSettings.mPackages.get(packageName);
19300             if (ps == null) {
19301                 Log.w(TAG, "Package doesn't exist: " + packageName);
19302                 return false;
19303             }
19304             if (systemUserApp) {
19305                 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19306             } else {
19307                 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER;
19308             }
19309             mSettings.writeLPr();
19310         }
19311         return true;
19312     }
19313
19314     private static class DeletePackageAction {
19315         public final PackageSetting deletingPs;
19316         public final PackageSetting disabledPs;
19317         public final PackageRemovedInfo outInfo;
19318         public final int flags;
19319         public final UserHandle user;
19320
19321         private DeletePackageAction(PackageSetting deletingPs, PackageSetting disabledPs,
19322                 PackageRemovedInfo outInfo, int flags, UserHandle user) {
19323             this.deletingPs = deletingPs;
19324             this.disabledPs = disabledPs;
19325             this.outInfo = outInfo;
19326             this.flags = flags;
19327             this.user = user;
19328         }
19329     }
19330
19331     /**
19332      * @return a {@link DeletePackageAction} if the provided package and related state may be
19333      * deleted, {@code null} otherwise.
19334      */
19335     @Nullable
19336     @GuardedBy("mPackages")
19337     private static DeletePackageAction mayDeletePackageLocked(
19338             PackageRemovedInfo outInfo, PackageSetting ps, @Nullable PackageSetting disabledPs,
19339             @Nullable PackageSetting[] children, int flags, UserHandle user) {
19340         if (ps == null) {
19341             return null;
19342         }
19343         if (isSystemApp(ps)) {
19344             if (ps.parentPackageName != null) {
19345                 Slog.w(TAG, "Attempt to delete child system package " + ps.pkg.packageName);
19346                 return null;
19347             }
19348
19349             final boolean deleteSystem = (flags & PackageManager.DELETE_SYSTEM_APP) != 0;
19350             final boolean deleteAllUsers =
19351                     user == null || user.getIdentifier() == UserHandle.USER_ALL;
19352             if ((!deleteSystem || deleteAllUsers) && disabledPs == null) {
19353                 Slog.w(TAG, "Attempt to delete unknown system package " + ps.pkg.packageName);
19354                 return null;
19355             }
19356             // Confirmed if the system package has been updated
19357             // An updated system app can be deleted. This will also have to restore
19358             // the system pkg from system partition reader
19359         }
19360         final int parentReferenceCount =
19361                 (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0;
19362         final int childCount = children != null ? children.length : 0;
19363         if (childCount != parentReferenceCount) {
19364             return null;
19365         }
19366         if (childCount != 0 && outInfo != null && outInfo.removedChildPackages != null) {
19367             for (PackageSetting child : children) {
19368                 if (child == null || !ps.childPackageNames.contains(child.name)) {
19369                     return null;
19370                 }
19371             }
19372         }
19373         return new DeletePackageAction(ps, disabledPs, outInfo, flags, user);
19374     }
19375
19376     /*
19377      * This method handles package deletion in general
19378      */
19379     private boolean deletePackageLIF(@NonNull String packageName, UserHandle user,
19380             boolean deleteCodeAndResources, int[] allUserHandles, int flags,
19381             PackageRemovedInfo outInfo, boolean writeSettings,
19382             PackageParser.Package replacingPackage) {
19383         final DeletePackageAction action;
19384         synchronized (mPackages) {
19385             final PackageSetting ps = mSettings.mPackages.get(packageName);
19386             final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps);
19387             PackageSetting[] children = mSettings.getChildSettingsLPr(ps);
19388             action = mayDeletePackageLocked(outInfo, ps, disabledPs, children, flags, user);
19389         }
19390         if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
19391         if (null == action) {
19392             if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: action was null");
19393             return false;
19394         }
19395
19396
19397         try {
19398             executeDeletePackageLIF(action, packageName, deleteCodeAndResources,
19399                     allUserHandles, writeSettings, replacingPackage);
19400         } catch (SystemDeleteException e) {
19401             if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: system deletion failure", e);
19402             return false;
19403         }
19404         return true;
19405     }
19406
19407     private static class SystemDeleteException extends Exception {
19408         public final PackageManagerException reason;
19409
19410         private SystemDeleteException(PackageManagerException reason) {
19411             this.reason = reason;
19412         }
19413     }
19414
19415     /** Deletes a package. Only throws when install of a disabled package fails. */
19416     private void executeDeletePackageLIF(DeletePackageAction action,
19417             String packageName, boolean deleteCodeAndResources,
19418             int[] allUserHandles, boolean writeSettings,
19419             PackageParser.Package replacingPackage) throws SystemDeleteException {
19420         final PackageSetting ps = action.deletingPs;
19421         final PackageRemovedInfo outInfo = action.outInfo;
19422         final UserHandle user = action.user;
19423         final int flags = action.flags;
19424         final boolean systemApp = isSystemApp(ps);
19425
19426         if (ps.parentPackageName != null
19427                 && (!systemApp || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) {
19428             if (DEBUG_REMOVE) {
19429                 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:"
19430                         + ((user == null) ? UserHandle.USER_ALL : user));
19431             }
19432             final int removedUserId = (user != null) ? user.getIdentifier()
19433                     : UserHandle.USER_ALL;
19434
19435             clearPackageStateForUserLIF(ps, removedUserId, outInfo, flags);
19436             synchronized (mPackages) {
19437                 markPackageUninstalledForUserLPw(ps, user);
19438                 scheduleWritePackageRestrictionsLocked(user);
19439             }
19440             return;
19441         }
19442
19443         final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier();
19444         if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) {
19445             unsuspendForSuspendingPackage(packageName, userId);
19446         }
19447         if ((!systemApp || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)
19448                 && userId != UserHandle.USER_ALL) {
19449             // The caller is asking that the package only be deleted for a single
19450             // user.  To do this, we just mark its uninstalled state and delete
19451             // its data. If this is a system app, we only allow this to happen if
19452             // they have set the special DELETE_SYSTEM_APP which requests different
19453             // semantics than normal for uninstalling system apps.
19454             final boolean clearPackageStateAndReturn;
19455             synchronized (mPackages) {
19456                 markPackageUninstalledForUserLPw(ps, user);
19457                 if (!systemApp) {
19458                     // Do not uninstall the APK if an app should be cached
19459                     boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName);
19460                     if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) {
19461                         // Other users still have this package installed, so all
19462                         // we need to do is clear this user's data and save that
19463                         // it is uninstalled.
19464                         if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
19465                         clearPackageStateAndReturn = true;
19466                     } else {
19467                         // We need to set it back to 'installed' so the uninstall
19468                         // broadcasts will be sent correctly.
19469                         if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
19470                         ps.setInstalled(true, userId);
19471                         mSettings.writeKernelMappingLPr(ps);
19472                         clearPackageStateAndReturn = false;
19473                     }
19474                 } else {
19475                     // This is a system app, so we assume that the
19476                     // other users still have this package installed, so all
19477                     // we need to do is clear this user's data and save that
19478                     // it is uninstalled.
19479                     if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
19480                     clearPackageStateAndReturn = true;
19481                 }
19482             }
19483             if (clearPackageStateAndReturn) {
19484                 clearPackageStateForUserLIF(ps, userId, outInfo, flags);
19485                 synchronized (mPackages) {
19486                     scheduleWritePackageRestrictionsLocked(user);
19487                 }
19488                 return;
19489             }
19490         }
19491
19492         // If we are deleting a composite package for all users, keep track
19493         // of result for each child.
19494         if (ps.childPackageNames != null && outInfo != null) {
19495             synchronized (mPackages) {
19496                 final int childCount = ps.childPackageNames.size();
19497                 outInfo.removedChildPackages = new ArrayMap<>(childCount);
19498                 for (int i = 0; i < childCount; i++) {
19499                     String childPackageName = ps.childPackageNames.get(i);
19500                     PackageRemovedInfo childInfo = new PackageRemovedInfo(this);
19501                     childInfo.removedPackage = childPackageName;
19502                     childInfo.installerPackageName = ps.installerPackageName;
19503                     outInfo.removedChildPackages.put(childPackageName, childInfo);
19504                     PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19505                     if (childPs != null) {
19506                         childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true);
19507                     }
19508                 }
19509             }
19510         }
19511
19512         // TODO(b/109941548): break reasons for ret = false out into mayDelete method
19513         if (systemApp) {
19514             if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name);
19515             // When an updated system application is deleted we delete the existing resources
19516             // as well and fall back to existing code in system partition
19517             deleteSystemPackageLIF(action, ps, allUserHandles, flags, outInfo, writeSettings);
19518         } else {
19519             if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name);
19520             deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles,
19521                     outInfo, writeSettings, replacingPackage);
19522         }
19523
19524         // Take a note whether we deleted the package for all users
19525         if (outInfo != null) {
19526             outInfo.removedForAllUsers = mPackages.get(ps.name) == null;
19527             if (outInfo.removedChildPackages != null) {
19528                 synchronized (mPackages) {
19529                     final int childCount = outInfo.removedChildPackages.size();
19530                     for (int i = 0; i < childCount; i++) {
19531                         PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i);
19532                         if (childInfo != null) {
19533                             childInfo.removedForAllUsers = mPackages.get(
19534                                     childInfo.removedPackage) == null;
19535                         }
19536                     }
19537                 }
19538             }
19539             // If we uninstalled an update to a system app there may be some
19540             // child packages that appeared as they are declared in the system
19541             // app but were not declared in the update.
19542             if (systemApp) {
19543                 synchronized (mPackages) {
19544                     PackageSetting updatedPs = mSettings.getPackageLPr(ps.name);
19545                     final int childCount = (updatedPs.childPackageNames != null)
19546                             ? updatedPs.childPackageNames.size() : 0;
19547                     for (int i = 0; i < childCount; i++) {
19548                         String childPackageName = updatedPs.childPackageNames.get(i);
19549                         if (outInfo.removedChildPackages == null
19550                                 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) {
19551                             PackageSetting childPs = mSettings.getPackageLPr(childPackageName);
19552                             if (childPs == null) {
19553                                 continue;
19554                             }
19555                             PackageInstalledInfo installRes = new PackageInstalledInfo();
19556                             installRes.name = childPackageName;
19557                             installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true);
19558                             installRes.pkg = mPackages.get(childPackageName);
19559                             installRes.uid = childPs.pkg.applicationInfo.uid;
19560                             if (outInfo.appearedChildPackages == null) {
19561                                 outInfo.appearedChildPackages = new ArrayMap<>();
19562                             }
19563                             outInfo.appearedChildPackages.put(childPackageName, installRes);
19564                         }
19565                     }
19566                 }
19567             }
19568         }
19569     }
19570
19571     @GuardedBy("mPackages")
19572     private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) {
19573         final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL)
19574                 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()};
19575         for (int nextUserId : userIds) {
19576             if (DEBUG_REMOVE) {
19577                 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId);
19578             }
19579             ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT,
19580                     false /*installed*/,
19581                     true /*stopped*/,
19582                     true /*notLaunched*/,
19583                     false /*hidden*/,
19584                     0 /*distractionFlags*/,
19585                     false /*suspended*/,
19586                     null /*suspendingPackage*/,
19587                     null /*dialogInfo*/,
19588                     null /*suspendedAppExtras*/,
19589                     null /*suspendedLauncherExtras*/,
19590                     false /*instantApp*/,
19591                     false /*virtualPreload*/,
19592                     null /*lastDisableAppCaller*/,
19593                     null /*enabledComponents*/,
19594                     null /*disabledComponents*/,
19595                     ps.readUserState(nextUserId).domainVerificationStatus,
19596                     0, PackageManager.INSTALL_REASON_UNKNOWN,
19597                     null /*harmfulAppWarning*/);
19598         }
19599         mSettings.writeKernelMappingLPr(ps);
19600     }
19601
19602     private void clearPackageStateForUserLIF(PackageSetting ps, int userId,
19603             PackageRemovedInfo outInfo, int flags) {
19604         final PackageParser.Package pkg;
19605         synchronized (mPackages) {
19606             pkg = mPackages.get(ps.name);
19607         }
19608
19609         destroyAppProfilesLIF(pkg);
19610
19611         final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds()
19612                 : new int[] {userId};
19613         for (int nextUserId : userIds) {
19614             if (DEBUG_REMOVE) {
19615                 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:"
19616                         + nextUserId);
19617             }
19618
19619             destroyAppDataLIF(pkg, nextUserId,
19620                     FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL);
19621             clearDefaultBrowserIfNeededForUser(ps.name, nextUserId);
19622             removeKeystoreDataIfNeeded(nextUserId, ps.appId);
19623             final SparseBooleanArray changedUsers = new SparseBooleanArray();
19624             clearPackagePreferredActivitiesLPw(ps.name, changedUsers, nextUserId);
19625             if (changedUsers.size() > 0) {
19626                 updateDefaultHomeNotLocked(changedUsers);
19627                 postPreferredActivityChangedBroadcast(nextUserId);
19628                 synchronized (mPackages) {
19629                     scheduleWritePackageRestrictionsLocked(nextUserId);
19630                 }
19631             }
19632             synchronized (mPackages) {
19633                 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId);
19634             }
19635             // Also delete contributed media, when requested
19636             if ((flags & PackageManager.DELETE_CONTRIBUTED_MEDIA) != 0) {
19637                 try {
19638                     MediaStore.deleteContributedMedia(mContext, ps.name, UserHandle.of(nextUserId));
19639                 } catch (IOException e) {
19640                     Slog.w(TAG, "Failed to delete contributed media for " + ps.name, e);
19641                 }
19642             }
19643         }
19644
19645         if (outInfo != null) {
19646             outInfo.removedPackage = ps.name;
19647             outInfo.installerPackageName = ps.installerPackageName;
19648             outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null;
19649             outInfo.removedAppId = ps.appId;
19650             outInfo.removedUsers = userIds;
19651             outInfo.broadcastUsers = userIds;
19652         }
19653     }
19654
19655     @Override
19656     public void clearApplicationProfileData(String packageName) {
19657         enforceSystemOrRoot("Only the system can clear all profile data");
19658
19659         final PackageParser.Package pkg;
19660         synchronized (mPackages) {
19661             pkg = mPackages.get(packageName);
19662         }
19663
19664         try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) {
19665             synchronized (mInstallLock) {
19666                 clearAppProfilesLIF(pkg, UserHandle.USER_ALL);
19667             }
19668         }
19669     }
19670
19671     @Override
19672     public void clearApplicationUserData(final String packageName,
19673             final IPackageDataObserver observer, final int userId) {
19674         mContext.enforceCallingOrSelfPermission(
19675                 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
19676
19677         final int callingUid = Binder.getCallingUid();
19678         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
19679                 true /* requireFullPermission */, false /* checkShell */, "clear application data");
19680
19681         final PackageSetting ps = mSettings.getPackageLPr(packageName);
19682         final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId));
19683         if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) {
19684             throw new SecurityException("Cannot clear data for a protected package: "
19685                     + packageName);
19686         }
19687         // Queue up an async operation since the package deletion may take a little while.
19688         mHandler.post(new Runnable() {
19689             public void run() {
19690                 mHandler.removeCallbacks(this);
19691                 final boolean succeeded;
19692                 if (!filterApp) {
19693                     try (PackageFreezer freezer = freezePackage(packageName,
19694                             "clearApplicationUserData")) {
19695                         synchronized (mInstallLock) {
19696                             succeeded = clearApplicationUserDataLIF(packageName, userId);
19697                         }
19698                         synchronized (mPackages) {
19699                             mInstantAppRegistry.deleteInstantApplicationMetadataLPw(
19700                                     packageName, userId);
19701                         }
19702                     }
19703                     if (succeeded) {
19704                         // invoke DeviceStorageMonitor's update method to clear any notifications
19705                         DeviceStorageMonitorInternal dsm = LocalServices
19706                                 .getService(DeviceStorageMonitorInternal.class);
19707                         if (dsm != null) {
19708                             dsm.checkMemory();
19709                         }
19710                         if (checkPermission(Manifest.permission.SUSPEND_APPS, packageName, userId)
19711                                 == PERMISSION_GRANTED) {
19712                             unsuspendForSuspendingPackage(packageName, userId);
19713                         }
19714                     }
19715                 } else {
19716                     succeeded = false;
19717                 }
19718                 if (observer != null) {
19719                     try {
19720                         observer.onRemoveCompleted(packageName, succeeded);
19721                     } catch (RemoteException e) {
19722                         Log.i(TAG, "Observer no longer exists.");
19723                     }
19724                 } //end if observer
19725             } //end run
19726         });
19727     }
19728
19729     private boolean clearApplicationUserDataLIF(String packageName, int userId) {
19730         if (packageName == null) {
19731             Slog.w(TAG, "Attempt to delete null packageName.");
19732             return false;
19733         }
19734
19735         // Try finding details about the requested package
19736         PackageParser.Package pkg;
19737         synchronized (mPackages) {
19738             pkg = mPackages.get(packageName);
19739             if (pkg == null) {
19740                 final PackageSetting ps = mSettings.mPackages.get(packageName);
19741                 if (ps != null) {
19742                     pkg = ps.pkg;
19743                 }
19744             }
19745
19746             if (pkg == null) {
19747                 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
19748                 return false;
19749             }
19750
19751             PackageSetting ps = (PackageSetting) pkg.mExtras;
19752             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19753         }
19754
19755         clearAppDataLIF(pkg, userId,
19756                 FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL);
19757
19758         final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
19759         removeKeystoreDataIfNeeded(userId, appId);
19760
19761         UserManagerInternal umInternal = getUserManagerInternal();
19762         final int flags;
19763         if (umInternal.isUserUnlockingOrUnlocked(userId)) {
19764             flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
19765         } else if (umInternal.isUserRunning(userId)) {
19766             flags = StorageManager.FLAG_STORAGE_DE;
19767         } else {
19768             flags = 0;
19769         }
19770         prepareAppDataContentsLIF(pkg, userId, flags);
19771
19772         return true;
19773     }
19774
19775     /**
19776      * Reverts user permission state changes (permissions and flags) in
19777      * all packages for a given user.
19778      *
19779      * @param userId The device user for which to do a reset.
19780      */
19781     @GuardedBy("mPackages")
19782     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) {
19783         final int packageCount = mPackages.size();
19784         for (int i = 0; i < packageCount; i++) {
19785             PackageParser.Package pkg = mPackages.valueAt(i);
19786             PackageSetting ps = (PackageSetting) pkg.mExtras;
19787             resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId);
19788         }
19789     }
19790
19791     private void resetNetworkPolicies(int userId) {
19792         LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId);
19793     }
19794
19795     /**
19796      * Reverts user permission state changes (permissions and flags).
19797      *
19798      * @param ps The package for which to reset.
19799      * @param userId The device user for which to do a reset.
19800      */
19801     @GuardedBy("mPackages")
19802     private void resetUserChangesToRuntimePermissionsAndFlagsLPw(
19803             final PackageSetting ps, final int userId) {
19804         if (ps.pkg == null) {
19805             return;
19806         }
19807
19808         final String packageName = ps.pkg.packageName;
19809
19810         // These are flags that can change base on user actions.
19811         final int userSettableMask = FLAG_PERMISSION_USER_SET
19812                 | FLAG_PERMISSION_USER_FIXED
19813                 | FLAG_PERMISSION_REVOKE_ON_UPGRADE
19814                 | FLAG_PERMISSION_REVIEW_REQUIRED;
19815
19816         final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED
19817                 | FLAG_PERMISSION_POLICY_FIXED;
19818
19819         // Delay and combine non-async permission callbacks
19820         final boolean[] permissionRemoved = new boolean[1];
19821         final ArraySet<Long> revokedPermissions = new ArraySet<>();
19822         final SparseBooleanArray updatedUsers = new SparseBooleanArray();
19823
19824         PermissionCallback delayingPermCallback = new PermissionCallback() {
19825             public void onGidsChanged(int appId, int userId) {
19826                 mPermissionCallback.onGidsChanged(appId, userId);
19827             }
19828
19829             public void onPermissionChanged() {
19830                 mPermissionCallback.onPermissionChanged();
19831             }
19832
19833             public void onPermissionGranted(int uid, int userId) {
19834                 mPermissionCallback.onPermissionGranted(uid, userId);
19835             }
19836
19837             public void onInstallPermissionGranted() {
19838                 mPermissionCallback.onInstallPermissionGranted();
19839             }
19840
19841             public void onPermissionRevoked(int uid, int userId) {
19842                 revokedPermissions.add(IntPair.of(uid, userId));
19843
19844                 updatedUsers.put(userId, true);
19845             }
19846
19847             public void onInstallPermissionRevoked() {
19848                 mPermissionCallback.onInstallPermissionRevoked();
19849             }
19850
19851             public void onPermissionUpdated(int[] updatedUserIds, boolean sync) {
19852                 for (int userId : updatedUserIds) {
19853                     if (sync) {
19854                         updatedUsers.put(userId, true);
19855                     } else {
19856                         // Don't override sync=true by sync=false
19857                         if (!updatedUsers.get(userId)) {
19858                             updatedUsers.put(userId, false);
19859                         }
19860                     }
19861                 }
19862             }
19863
19864             public void onPermissionRemoved() {
19865                 permissionRemoved[0] = true;
19866             }
19867
19868             public void onInstallPermissionUpdated() {
19869                 mPermissionCallback.onInstallPermissionUpdated();
19870             }
19871         };
19872
19873         final int permissionCount = ps.pkg.requestedPermissions.size();
19874         for (int i = 0; i < permissionCount; i++) {
19875             final String permName = ps.pkg.requestedPermissions.get(i);
19876             final BasePermission bp =
19877                     (BasePermission) mPermissionManager.getPermissionTEMP(permName);
19878             if (bp == null) {
19879                 continue;
19880             }
19881
19882             if (bp.isRemoved()) {
19883                 continue;
19884             }
19885
19886             // If shared user we just reset the state to which only this app contributed.
19887             if (ps.sharedUser != null) {
19888                 boolean used = false;
19889                 final int packageCount = ps.sharedUser.packages.size();
19890                 for (int j = 0; j < packageCount; j++) {
19891                     PackageSetting pkg = ps.sharedUser.packages.valueAt(j);
19892                     if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName)
19893                             && pkg.pkg.requestedPermissions.contains(permName)) {
19894                         used = true;
19895                         break;
19896                     }
19897                 }
19898                 if (used) {
19899                     continue;
19900                 }
19901             }
19902
19903             final int oldFlags = mPermissionManager.getPermissionFlags(permName, packageName,
19904                     Process.SYSTEM_UID, userId);
19905
19906             // Always clear the user settable flags.
19907             // If permission review is enabled and this is a legacy app, mark the
19908             // permission as requiring a review as this is the initial state.
19909             int flags = 0;
19910             if (ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M && bp.isRuntime()) {
19911                 flags |= FLAG_PERMISSION_REVIEW_REQUIRED | FLAG_PERMISSION_REVOKE_ON_UPGRADE;
19912             }
19913
19914             mPermissionManager.updatePermissionFlags(permName, packageName,
19915                     userSettableMask, flags, Process.SYSTEM_UID, userId, false,
19916                     delayingPermCallback);
19917
19918             // Below is only runtime permission handling.
19919             if (!bp.isRuntime()) {
19920                 continue;
19921             }
19922
19923             // Never clobber system or policy.
19924             if ((oldFlags & policyOrSystemFlags) != 0) {
19925                 continue;
19926             }
19927
19928             // If this permission was granted by default, make sure it is.
19929             if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) {
19930                 mPermissionManager.grantRuntimePermission(permName, packageName, false,
19931                         Process.SYSTEM_UID, userId, delayingPermCallback);
19932             // If permission review is enabled the permissions for a legacy apps
19933             // are represented as constantly granted runtime ones, so don't revoke.
19934             } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) {
19935                 // Otherwise, reset the permission.
19936                 mPermissionManager.revokeRuntimePermission(permName, packageName, false, userId,
19937                         delayingPermCallback);
19938             }
19939         }
19940
19941         // Execute delayed callbacks
19942         if (permissionRemoved[0]) {
19943             mPermissionCallback.onPermissionRemoved();
19944         }
19945
19946         // Slight variation on the code in mPermissionCallback.onPermissionRevoked() as we cannot
19947         // kill uid while holding mPackages-lock
19948         if (!revokedPermissions.isEmpty()) {
19949             int numRevokedPermissions = revokedPermissions.size();
19950             for (int i = 0; i < numRevokedPermissions; i++) {
19951                 int revocationUID = IntPair.first(revokedPermissions.valueAt(i));
19952                 int revocationUserId = IntPair.second(revokedPermissions.valueAt(i));
19953
19954                 mOnPermissionChangeListeners.onPermissionsChanged(revocationUID);
19955
19956                 // Kill app later as we are holding mPackages
19957                 mHandler.post(() -> killUid(UserHandle.getAppId(revocationUID), revocationUserId,
19958                         KILL_APP_REASON_PERMISSIONS_REVOKED));
19959             }
19960         }
19961
19962         int numUpdatedUsers = updatedUsers.size();
19963         for (int i = 0; i < numUpdatedUsers; i++) {
19964             mSettings.writeRuntimePermissionsForUserLPr(updatedUsers.keyAt(i),
19965                     updatedUsers.valueAt(i));
19966         }
19967     }
19968
19969     /**
19970      * Remove entries from the keystore daemon. Will only remove it if the
19971      * {@code appId} is valid.
19972      */
19973     private static void removeKeystoreDataIfNeeded(int userId, int appId) {
19974         if (appId < 0) {
19975             return;
19976         }
19977
19978         final KeyStore keyStore = KeyStore.getInstance();
19979         if (keyStore != null) {
19980             if (userId == UserHandle.USER_ALL) {
19981                 for (final int individual : sUserManager.getUserIds()) {
19982                     keyStore.clearUid(UserHandle.getUid(individual, appId));
19983                 }
19984             } else {
19985                 keyStore.clearUid(UserHandle.getUid(userId, appId));
19986             }
19987         } else {
19988             Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
19989         }
19990     }
19991
19992     @Override
19993     public void deleteApplicationCacheFiles(final String packageName,
19994             final IPackageDataObserver observer) {
19995         final int userId = UserHandle.getCallingUserId();
19996         deleteApplicationCacheFilesAsUser(packageName, userId, observer);
19997     }
19998
19999     @Override
20000     public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId,
20001             final IPackageDataObserver observer) {
20002         final int callingUid = Binder.getCallingUid();
20003         if (mContext.checkCallingOrSelfPermission(
20004                 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES)
20005                 != PackageManager.PERMISSION_GRANTED) {
20006             // If the caller has the old delete cache permission, silently ignore.  Else throw.
20007             if (mContext.checkCallingOrSelfPermission(
20008                     android.Manifest.permission.DELETE_CACHE_FILES)
20009                     == PackageManager.PERMISSION_GRANTED) {
20010                 Slog.w(TAG, "Calling uid " + callingUid + " does not have " +
20011                         android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES +
20012                         ", silently ignoring");
20013                 return;
20014             }
20015             mContext.enforceCallingOrSelfPermission(
20016                     android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null);
20017         }
20018         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20019                 /* requireFullPermission= */ true, /* checkShell= */ false,
20020                 "delete application cache files");
20021         final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission(
20022                 android.Manifest.permission.ACCESS_INSTANT_APPS);
20023
20024         final PackageParser.Package pkg;
20025         synchronized (mPackages) {
20026             pkg = mPackages.get(packageName);
20027         }
20028
20029         // Queue up an async operation since the package deletion may take a little while.
20030         mHandler.post(() -> {
20031             final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras;
20032             boolean doClearData = true;
20033             if (ps != null) {
20034                 final boolean targetIsInstantApp =
20035                         ps.getInstantApp(UserHandle.getUserId(callingUid));
20036                 doClearData = !targetIsInstantApp
20037                         || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED;
20038             }
20039             if (doClearData) {
20040                 synchronized (mInstallLock) {
20041                     final int flags = FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL;
20042                     // We're only clearing cache files, so we don't care if the
20043                     // app is unfrozen and still able to run
20044                     clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY);
20045                     clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
20046                 }
20047             }
20048             if (observer != null) {
20049                 try {
20050                     observer.onRemoveCompleted(packageName, true);
20051                 } catch (RemoteException e) {
20052                     Log.i(TAG, "Observer no longer exists.");
20053                 }
20054             }
20055         });
20056     }
20057
20058     @Override
20059     public void getPackageSizeInfo(final String packageName, int userHandle,
20060             final IPackageStatsObserver observer) {
20061         throw new UnsupportedOperationException(
20062                 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!");
20063     }
20064
20065     @GuardedBy("mInstallLock")
20066     private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) {
20067         final PackageSetting ps;
20068         synchronized (mPackages) {
20069             ps = mSettings.mPackages.get(packageName);
20070             if (ps == null) {
20071                 Slog.w(TAG, "Failed to find settings for " + packageName);
20072                 return false;
20073             }
20074         }
20075
20076         final String[] packageNames = { packageName };
20077         final long[] ceDataInodes = { ps.getCeDataInode(userId) };
20078         final String[] codePaths = { ps.codePathString };
20079
20080         try {
20081             mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0,
20082                     ps.appId, ceDataInodes, codePaths, stats);
20083
20084             // For now, ignore code size of packages on system partition
20085             if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) {
20086                 stats.codeSize = 0;
20087             }
20088
20089             // External clients expect these to be tracked separately
20090             stats.dataSize -= stats.cacheSize;
20091
20092         } catch (InstallerException e) {
20093             Slog.w(TAG, String.valueOf(e));
20094             return false;
20095         }
20096
20097         return true;
20098     }
20099
20100     @GuardedBy("mPackages")
20101     private int getUidTargetSdkVersionLockedLPr(int uid) {
20102         final int appId = UserHandle.getAppId(uid);
20103         final Object obj = mSettings.getSettingLPr(appId);
20104         if (obj instanceof SharedUserSetting) {
20105             final SharedUserSetting sus = (SharedUserSetting) obj;
20106             int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
20107             final Iterator<PackageSetting> it = sus.packages.iterator();
20108             while (it.hasNext()) {
20109                 final PackageSetting ps = it.next();
20110                 if (ps.pkg != null) {
20111                     int v = ps.pkg.applicationInfo.targetSdkVersion;
20112                     if (v < vers) vers = v;
20113                 }
20114             }
20115             return vers;
20116         } else if (obj instanceof PackageSetting) {
20117             final PackageSetting ps = (PackageSetting) obj;
20118             if (ps.pkg != null) {
20119                 return ps.pkg.applicationInfo.targetSdkVersion;
20120             }
20121         }
20122         return Build.VERSION_CODES.CUR_DEVELOPMENT;
20123     }
20124
20125     @GuardedBy("mPackages")
20126     private int getPackageTargetSdkVersionLockedLPr(String packageName) {
20127         final PackageParser.Package p = mPackages.get(packageName);
20128         if (p != null) {
20129             return p.applicationInfo.targetSdkVersion;
20130         }
20131         return Build.VERSION_CODES.CUR_DEVELOPMENT;
20132     }
20133
20134     @Override
20135     public void addPreferredActivity(IntentFilter filter, int match,
20136             ComponentName[] set, ComponentName activity, int userId) {
20137         addPreferredActivityInternal(filter, match, set, activity, true, userId,
20138                 "Adding preferred");
20139     }
20140
20141     private void addPreferredActivityInternal(IntentFilter filter, int match,
20142             ComponentName[] set, ComponentName activity, boolean always, int userId,
20143             String opname) {
20144         // writer
20145         int callingUid = Binder.getCallingUid();
20146         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20147                 true /* requireFullPermission */, false /* checkShell */, "add preferred activity");
20148         if (mContext.checkCallingOrSelfPermission(
20149                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20150                 != PackageManager.PERMISSION_GRANTED) {
20151             if (getUidTargetSdkVersionLockedLPr(callingUid)
20152                     < Build.VERSION_CODES.FROYO) {
20153                 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
20154                         + callingUid);
20155                 return;
20156             }
20157             mContext.enforceCallingOrSelfPermission(
20158                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20159         }
20160         if (filter.countActions() == 0) {
20161             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20162             return;
20163         }
20164         if (DEBUG_PREFERRED) {
20165             Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
20166                     + userId + ":");
20167             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20168         }
20169         synchronized (mPackages) {
20170             final PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
20171             pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
20172             scheduleWritePackageRestrictionsLocked(userId);
20173         }
20174         if (!updateDefaultHomeNotLocked(userId)) {
20175             postPreferredActivityChangedBroadcast(userId);
20176         }
20177     }
20178
20179     private void postPreferredActivityChangedBroadcast(int userId) {
20180         mHandler.post(() -> {
20181             final IActivityManager am = ActivityManager.getService();
20182             if (am == null) {
20183                 return;
20184             }
20185
20186             final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED);
20187             intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
20188             intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
20189             try {
20190                 am.broadcastIntent(null, intent, null, null,
20191                         0, null, null, null, android.app.AppOpsManager.OP_NONE,
20192                         null, false, false, userId);
20193             } catch (RemoteException e) {
20194             }
20195         });
20196     }
20197
20198     @Override
20199     public void replacePreferredActivity(IntentFilter filter, int match,
20200             ComponentName[] set, ComponentName activity, int userId) {
20201         if (filter.countActions() != 1) {
20202             throw new IllegalArgumentException(
20203                     "replacePreferredActivity expects filter to have only 1 action.");
20204         }
20205         if (filter.countDataAuthorities() != 0
20206                 || filter.countDataPaths() != 0
20207                 || filter.countDataSchemes() > 1
20208                 || filter.countDataTypes() != 0) {
20209             throw new IllegalArgumentException(
20210                     "replacePreferredActivity expects filter to have no data authorities, " +
20211                     "paths, or types; and at most one scheme.");
20212         }
20213
20214         final int callingUid = Binder.getCallingUid();
20215         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
20216                 true /* requireFullPermission */, false /* checkShell */,
20217                 "replace preferred activity");
20218         if (mContext.checkCallingOrSelfPermission(
20219                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20220                 != PackageManager.PERMISSION_GRANTED) {
20221             synchronized (mPackages) {
20222                 if (getUidTargetSdkVersionLockedLPr(callingUid)
20223                         < Build.VERSION_CODES.FROYO) {
20224                     Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
20225                             + Binder.getCallingUid());
20226                     return;
20227                 }
20228             }
20229             mContext.enforceCallingOrSelfPermission(
20230                     android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20231         }
20232
20233         synchronized (mPackages) {
20234             final PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20235             if (pir != null) {
20236                 // Get all of the existing entries that exactly match this filter.
20237                 final ArrayList<PreferredActivity> existing = pir.findFilters(filter);
20238                 if (existing != null && existing.size() == 1) {
20239                     final PreferredActivity cur = existing.get(0);
20240                     if (DEBUG_PREFERRED) {
20241                         Slog.i(TAG, "Checking replace of preferred:");
20242                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20243                         if (!cur.mPref.mAlways) {
20244                             Slog.i(TAG, "  -- CUR; not mAlways!");
20245                         } else {
20246                             Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
20247                             Slog.i(TAG, "  -- CUR: mSet="
20248                                     + Arrays.toString(cur.mPref.mSetComponents));
20249                             Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
20250                             Slog.i(TAG, "  -- NEW: mMatch="
20251                                     + (match&IntentFilter.MATCH_CATEGORY_MASK));
20252                             Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
20253                             Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
20254                         }
20255                     }
20256                     if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
20257                             && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
20258                             && cur.mPref.sameSet(set)) {
20259                         // Setting the preferred activity to what it happens to be already
20260                         if (DEBUG_PREFERRED) {
20261                             Slog.i(TAG, "Replacing with same preferred activity "
20262                                     + cur.mPref.mShortComponent + " for user "
20263                                     + userId + ":");
20264                             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20265                         }
20266                         return;
20267                     }
20268                 }
20269                 if (existing != null) {
20270                     if (DEBUG_PREFERRED) {
20271                         Slog.i(TAG, existing.size() + " existing preferred matches for:");
20272                         filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20273                     }
20274                     for (int i = existing.size() - 1; i >= 0; --i) {
20275                         final PreferredActivity pa = existing.get(i);
20276                         if (DEBUG_PREFERRED) {
20277                             Slog.i(TAG, "Removing existing preferred activity "
20278                                     + pa.mPref.mComponent + ":");
20279                             pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
20280                         }
20281                         pir.removeFilter(pa);
20282                     }
20283                 }
20284             }
20285         }
20286         addPreferredActivityInternal(filter, match, set, activity, true, userId,
20287                 "Replacing preferred");
20288     }
20289
20290     @Override
20291     public void clearPackagePreferredActivities(String packageName) {
20292         final int callingUid = Binder.getCallingUid();
20293         if (getInstantAppPackageName(callingUid) != null) {
20294             return;
20295         }
20296         // writer
20297         synchronized (mPackages) {
20298             PackageParser.Package pkg = mPackages.get(packageName);
20299             if (pkg == null || !isCallerSameApp(packageName, callingUid)) {
20300                 if (mContext.checkCallingOrSelfPermission(
20301                         android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
20302                         != PackageManager.PERMISSION_GRANTED) {
20303                     if (getUidTargetSdkVersionLockedLPr(callingUid)
20304                             < Build.VERSION_CODES.FROYO) {
20305                         Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
20306                                 + callingUid);
20307                         return;
20308                     }
20309                     mContext.enforceCallingOrSelfPermission(
20310                             android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20311                 }
20312             }
20313             final PackageSetting ps = mSettings.getPackageLPr(packageName);
20314             if (ps != null
20315                     && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
20316                 return;
20317             }
20318         }
20319         int callingUserId = UserHandle.getCallingUserId();
20320         final SparseBooleanArray changedUsers = new SparseBooleanArray();
20321         clearPackagePreferredActivitiesLPw(packageName, changedUsers, callingUserId);
20322         if (changedUsers.size() > 0) {
20323             updateDefaultHomeNotLocked(changedUsers);
20324             postPreferredActivityChangedBroadcast(callingUserId);
20325             synchronized (mPackages) {
20326                 scheduleWritePackageRestrictionsLocked(callingUserId);
20327             }
20328         }
20329     }
20330
20331     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20332     @GuardedBy("mPackages")
20333     private void clearPackagePreferredActivitiesLPw(String packageName,
20334             @NonNull SparseBooleanArray outUserChanged, int userId) {
20335         ArrayList<PreferredActivity> removed = null;
20336         for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
20337             final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
20338             PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
20339             if (userId != UserHandle.USER_ALL && userId != thisUserId) {
20340                 continue;
20341             }
20342             Iterator<PreferredActivity> it = pir.filterIterator();
20343             while (it.hasNext()) {
20344                 PreferredActivity pa = it.next();
20345                 // Mark entry for removal only if it matches the package name
20346                 // and the entry is of type "always".
20347                 if (packageName == null ||
20348                         (pa.mPref.mComponent.getPackageName().equals(packageName)
20349                                 && pa.mPref.mAlways)) {
20350                     if (removed == null) {
20351                         removed = new ArrayList<>();
20352                     }
20353                     removed.add(pa);
20354                 }
20355             }
20356             if (removed != null) {
20357                 for (int j=0; j<removed.size(); j++) {
20358                     PreferredActivity pa = removed.get(j);
20359                     pir.removeFilter(pa);
20360                 }
20361                 outUserChanged.put(thisUserId, true);
20362             }
20363         }
20364     }
20365
20366     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20367     @GuardedBy("mPackages")
20368     private void clearIntentFilterVerificationsLPw(int userId) {
20369         final int packageCount = mPackages.size();
20370         for (int i = 0; i < packageCount; i++) {
20371             PackageParser.Package pkg = mPackages.valueAt(i);
20372             clearIntentFilterVerificationsLPw(pkg.packageName, userId);
20373         }
20374     }
20375
20376     /** This method takes a specific user id as well as UserHandle.USER_ALL. */
20377     @GuardedBy("mPackages")
20378     void clearIntentFilterVerificationsLPw(String packageName, int userId) {
20379         if (userId == UserHandle.USER_ALL) {
20380             if (mSettings.removeIntentFilterVerificationLPw(packageName,
20381                     sUserManager.getUserIds())) {
20382                 for (int oneUserId : sUserManager.getUserIds()) {
20383                     scheduleWritePackageRestrictionsLocked(oneUserId);
20384                 }
20385             }
20386         } else {
20387             if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
20388                 scheduleWritePackageRestrictionsLocked(userId);
20389             }
20390         }
20391     }
20392
20393     /** Clears state for all users, and touches intent filter verification policy */
20394     void clearDefaultBrowserIfNeeded(String packageName) {
20395         for (int oneUserId : sUserManager.getUserIds()) {
20396             clearDefaultBrowserIfNeededForUser(packageName, oneUserId);
20397         }
20398     }
20399
20400     private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) {
20401         final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId);
20402         if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
20403             if (packageName.equals(defaultBrowserPackageName)) {
20404                 setDefaultBrowserPackageName(null, userId);
20405             }
20406         }
20407     }
20408
20409     @Override
20410     public void resetApplicationPreferences(int userId) {
20411         mContext.enforceCallingOrSelfPermission(
20412                 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
20413         final long identity = Binder.clearCallingIdentity();
20414         // writer
20415         try {
20416             final SparseBooleanArray changedUsers = new SparseBooleanArray();
20417             clearPackagePreferredActivitiesLPw(null, changedUsers, userId);
20418             if (changedUsers.size() > 0) {
20419                 postPreferredActivityChangedBroadcast(userId);
20420             }
20421             synchronized (mPackages) {
20422                 mSettings.applyDefaultPreferredAppsLPw(userId);
20423                 clearIntentFilterVerificationsLPw(userId);
20424                 primeDomainVerificationsLPw(userId);
20425                 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId);
20426             }
20427             updateDefaultHomeNotLocked(userId);
20428             // TODO: We have to reset the default SMS and Phone. This requires
20429             // significant refactoring to keep all default apps in the package
20430             // manager (cleaner but more work) or have the services provide
20431             // callbacks to the package manager to request a default app reset.
20432             setDefaultBrowserPackageName(null, userId);
20433             resetNetworkPolicies(userId);
20434             synchronized (mPackages) {
20435                 scheduleWritePackageRestrictionsLocked(userId);
20436             }
20437         } finally {
20438             Binder.restoreCallingIdentity(identity);
20439         }
20440     }
20441
20442     @Override
20443     public int getPreferredActivities(List<IntentFilter> outFilters,
20444             List<ComponentName> outActivities, String packageName) {
20445         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20446             return 0;
20447         }
20448         int num = 0;
20449         final int userId = UserHandle.getCallingUserId();
20450         // reader
20451         synchronized (mPackages) {
20452             PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
20453             if (pir != null) {
20454                 final Iterator<PreferredActivity> it = pir.filterIterator();
20455                 while (it.hasNext()) {
20456                     final PreferredActivity pa = it.next();
20457                     if (packageName == null
20458                             || (pa.mPref.mComponent.getPackageName().equals(packageName)
20459                                     && pa.mPref.mAlways)) {
20460                         if (outFilters != null) {
20461                             outFilters.add(new IntentFilter(pa));
20462                         }
20463                         if (outActivities != null) {
20464                             outActivities.add(pa.mPref.mComponent);
20465                         }
20466                     }
20467                 }
20468             }
20469         }
20470
20471         return num;
20472     }
20473
20474     @Override
20475     public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
20476             int userId) {
20477         int callingUid = Binder.getCallingUid();
20478         if (callingUid != Process.SYSTEM_UID) {
20479             throw new SecurityException(
20480                     "addPersistentPreferredActivity can only be run by the system");
20481         }
20482         if (filter.countActions() == 0) {
20483             Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
20484             return;
20485         }
20486         if (DEBUG_PREFERRED) {
20487             Slog.i(TAG, "Adding persistent preferred activity " + activity
20488                     + " for user " + userId + ":");
20489             filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
20490         }
20491         synchronized (mPackages) {
20492             mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
20493                     new PersistentPreferredActivity(filter, activity));
20494             scheduleWritePackageRestrictionsLocked(userId);
20495         }
20496         updateDefaultHomeNotLocked(userId);
20497         postPreferredActivityChangedBroadcast(userId);
20498     }
20499
20500     @Override
20501     public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
20502         int callingUid = Binder.getCallingUid();
20503         if (callingUid != Process.SYSTEM_UID) {
20504             throw new SecurityException(
20505                     "clearPackagePersistentPreferredActivities can only be run by the system");
20506         }
20507         ArrayList<PersistentPreferredActivity> removed = null;
20508         boolean changed = false;
20509         synchronized (mPackages) {
20510             for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
20511                 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
20512                 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
20513                         .valueAt(i);
20514                 if (userId != thisUserId) {
20515                     continue;
20516                 }
20517                 Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
20518                 while (it.hasNext()) {
20519                     PersistentPreferredActivity ppa = it.next();
20520                     // Mark entry for removal only if it matches the package name.
20521                     if (ppa.mComponent.getPackageName().equals(packageName)) {
20522                         if (removed == null) {
20523                             removed = new ArrayList<>();
20524                         }
20525                         removed.add(ppa);
20526                     }
20527                 }
20528                 if (removed != null) {
20529                     for (int j=0; j<removed.size(); j++) {
20530                         PersistentPreferredActivity ppa = removed.get(j);
20531                         ppir.removeFilter(ppa);
20532                     }
20533                     changed = true;
20534                 }
20535             }
20536         }
20537         if (changed) {
20538             updateDefaultHomeNotLocked(userId);
20539             postPreferredActivityChangedBroadcast(userId);
20540             synchronized (mPackages) {
20541                 scheduleWritePackageRestrictionsLocked(userId);
20542             }
20543         }
20544     }
20545
20546     /**
20547      * Common machinery for picking apart a restored XML blob and passing
20548      * it to a caller-supplied functor to be applied to the running system.
20549      */
20550     private void restoreFromXml(XmlPullParser parser, int userId,
20551             String expectedStartTag, BlobXmlRestorer functor)
20552             throws IOException, XmlPullParserException {
20553         int type;
20554         while ((type = parser.next()) != XmlPullParser.START_TAG
20555                 && type != XmlPullParser.END_DOCUMENT) {
20556         }
20557         if (type != XmlPullParser.START_TAG) {
20558             // oops didn't find a start tag?!
20559             if (DEBUG_BACKUP) {
20560                 Slog.e(TAG, "Didn't find start tag during restore");
20561             }
20562             return;
20563         }
20564         // this is supposed to be TAG_PREFERRED_BACKUP
20565         if (!expectedStartTag.equals(parser.getName())) {
20566             if (DEBUG_BACKUP) {
20567                 Slog.e(TAG, "Found unexpected tag " + parser.getName());
20568             }
20569             return;
20570         }
20571
20572         // skip interfering stuff, then we're aligned with the backing implementation
20573         while ((type = parser.next()) == XmlPullParser.TEXT) { }
20574         functor.apply(parser, userId);
20575     }
20576
20577     private interface BlobXmlRestorer {
20578         void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException;
20579     }
20580
20581     /**
20582      * Non-Binder method, support for the backup/restore mechanism: write the
20583      * full set of preferred activities in its canonical XML format.  Returns the
20584      * XML output as a byte array, or null if there is none.
20585      */
20586     @Override
20587     public byte[] getPreferredActivityBackup(int userId) {
20588         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20589             throw new SecurityException("Only the system may call getPreferredActivityBackup()");
20590         }
20591
20592         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20593         try {
20594             final XmlSerializer serializer = new FastXmlSerializer();
20595             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20596             serializer.startDocument(null, true);
20597             serializer.startTag(null, TAG_PREFERRED_BACKUP);
20598
20599             synchronized (mPackages) {
20600                 mSettings.writePreferredActivitiesLPr(serializer, userId, true);
20601             }
20602
20603             serializer.endTag(null, TAG_PREFERRED_BACKUP);
20604             serializer.endDocument();
20605             serializer.flush();
20606         } catch (Exception e) {
20607             if (DEBUG_BACKUP) {
20608                 Slog.e(TAG, "Unable to write preferred activities for backup", e);
20609             }
20610             return null;
20611         }
20612
20613         return dataStream.toByteArray();
20614     }
20615
20616     @Override
20617     public void restorePreferredActivities(byte[] backup, int userId) {
20618         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20619             throw new SecurityException("Only the system may call restorePreferredActivities()");
20620         }
20621
20622         try {
20623             final XmlPullParser parser = Xml.newPullParser();
20624             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20625             restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP,
20626                     (readParser, readUserId) -> {
20627                         synchronized (mPackages) {
20628                             mSettings.readPreferredActivitiesLPw(readParser, readUserId);
20629                         }
20630                         updateDefaultHomeNotLocked(readUserId);
20631                     });
20632         } catch (Exception e) {
20633             if (DEBUG_BACKUP) {
20634                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20635             }
20636         }
20637     }
20638
20639     /**
20640      * Non-Binder method, support for the backup/restore mechanism: write the
20641      * default browser (etc) settings in its canonical XML format.  Returns the default
20642      * browser XML representation as a byte array, or null if there is none.
20643      */
20644     @Override
20645     public byte[] getDefaultAppsBackup(int userId) {
20646         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20647             throw new SecurityException("Only the system may call getDefaultAppsBackup()");
20648         }
20649
20650         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20651         try {
20652             final XmlSerializer serializer = new FastXmlSerializer();
20653             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20654             serializer.startDocument(null, true);
20655             serializer.startTag(null, TAG_DEFAULT_APPS);
20656
20657             synchronized (mPackages) {
20658                 mSettings.writeDefaultAppsLPr(serializer, userId);
20659             }
20660
20661             serializer.endTag(null, TAG_DEFAULT_APPS);
20662             serializer.endDocument();
20663             serializer.flush();
20664         } catch (Exception e) {
20665             if (DEBUG_BACKUP) {
20666                 Slog.e(TAG, "Unable to write default apps for backup", e);
20667             }
20668             return null;
20669         }
20670
20671         return dataStream.toByteArray();
20672     }
20673
20674     @Override
20675     public void restoreDefaultApps(byte[] backup, int userId) {
20676         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20677             throw new SecurityException("Only the system may call restoreDefaultApps()");
20678         }
20679
20680         try {
20681             final XmlPullParser parser = Xml.newPullParser();
20682             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20683             restoreFromXml(parser, userId, TAG_DEFAULT_APPS,
20684                     (parser1, userId1) -> {
20685                         String defaultBrowser;
20686                         synchronized (mPackages) {
20687                             mSettings.readDefaultAppsLPw(parser1, userId1);
20688                             defaultBrowser = mSettings.removeDefaultBrowserPackageNameLPw(userId1);
20689                         }
20690                         if (defaultBrowser != null) {
20691                             PackageManagerInternal.DefaultBrowserProvider provider;
20692                             synchronized (mPackages) {
20693                                 provider = mDefaultBrowserProvider;
20694                             }
20695                             provider.setDefaultBrowser(defaultBrowser, userId1);
20696                         }
20697                     });
20698         } catch (Exception e) {
20699             if (DEBUG_BACKUP) {
20700                 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage());
20701             }
20702         }
20703     }
20704
20705     @Override
20706     public byte[] getIntentFilterVerificationBackup(int userId) {
20707         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20708             throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()");
20709         }
20710
20711         ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
20712         try {
20713             final XmlSerializer serializer = new FastXmlSerializer();
20714             serializer.setOutput(dataStream, StandardCharsets.UTF_8.name());
20715             serializer.startDocument(null, true);
20716             serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION);
20717
20718             synchronized (mPackages) {
20719                 mSettings.writeAllDomainVerificationsLPr(serializer, userId);
20720             }
20721
20722             serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION);
20723             serializer.endDocument();
20724             serializer.flush();
20725         } catch (Exception e) {
20726             if (DEBUG_BACKUP) {
20727                 Slog.e(TAG, "Unable to write default apps for backup", e);
20728             }
20729             return null;
20730         }
20731
20732         return dataStream.toByteArray();
20733     }
20734
20735     @Override
20736     public void restoreIntentFilterVerification(byte[] backup, int userId) {
20737         if (Binder.getCallingUid() != Process.SYSTEM_UID) {
20738             throw new SecurityException("Only the system may call restorePreferredActivities()");
20739         }
20740
20741         try {
20742             final XmlPullParser parser = Xml.newPullParser();
20743             parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name());
20744             restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION,
20745                     (parser1, userId1) -> {
20746                         synchronized (mPackages) {
20747                             mSettings.readAllDomainVerificationsLPr(parser1, userId1);
20748                             mSettings.writeLPr();
20749                         }
20750                     });
20751         } catch (Exception e) {
20752             if (DEBUG_BACKUP) {
20753                 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
20754             }
20755         }
20756     }
20757
20758     @Override
20759     public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
20760             int sourceUserId, int targetUserId, int flags) {
20761         mContext.enforceCallingOrSelfPermission(
20762                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20763         int callingUid = Binder.getCallingUid();
20764         enforceOwnerRights(ownerPackage, callingUid);
20765         PackageManagerServiceUtils.enforceShellRestriction(
20766                 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20767         if (intentFilter.countActions() == 0) {
20768             Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
20769             return;
20770         }
20771         synchronized (mPackages) {
20772             CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
20773                     ownerPackage, targetUserId, flags);
20774             CrossProfileIntentResolver resolver =
20775                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20776             ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
20777             // We have all those whose filter is equal. Now checking if the rest is equal as well.
20778             if (existing != null) {
20779                 int size = existing.size();
20780                 for (int i = 0; i < size; i++) {
20781                     if (newFilter.equalsIgnoreFilter(existing.get(i))) {
20782                         return;
20783                     }
20784                 }
20785             }
20786             resolver.addFilter(newFilter);
20787             scheduleWritePackageRestrictionsLocked(sourceUserId);
20788         }
20789     }
20790
20791     @Override
20792     public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
20793         mContext.enforceCallingOrSelfPermission(
20794                         android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
20795         final int callingUid = Binder.getCallingUid();
20796         enforceOwnerRights(ownerPackage, callingUid);
20797         PackageManagerServiceUtils.enforceShellRestriction(
20798                 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
20799         synchronized (mPackages) {
20800             CrossProfileIntentResolver resolver =
20801                     mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
20802             ArraySet<CrossProfileIntentFilter> set =
20803                     new ArraySet<>(resolver.filterSet());
20804             for (CrossProfileIntentFilter filter : set) {
20805                 if (filter.getOwnerPackage().equals(ownerPackage)) {
20806                     resolver.removeFilter(filter);
20807                 }
20808             }
20809             scheduleWritePackageRestrictionsLocked(sourceUserId);
20810         }
20811     }
20812
20813     // Enforcing that callingUid is owning pkg on userId
20814     private void enforceOwnerRights(String pkg, int callingUid) {
20815         // The system owns everything.
20816         if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
20817             return;
20818         }
20819         final int callingUserId = UserHandle.getUserId(callingUid);
20820         PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
20821         if (pi == null) {
20822             throw new IllegalArgumentException("Unknown package " + pkg + " on user "
20823                     + callingUserId);
20824         }
20825         if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
20826             throw new SecurityException("Calling uid " + callingUid
20827                     + " does not own package " + pkg);
20828         }
20829     }
20830
20831     @Override
20832     public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
20833         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
20834             return null;
20835         }
20836         return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId());
20837     }
20838
20839     /**
20840      * Send a {@code PackageInstaller.ACTION_SESSION_UPDATED} broadcast intent, containing
20841      * the {@code sessionInfo} in the extra field {@code PackageInstaller.EXTRA_SESSION}.
20842      */
20843     public void sendSessionUpdatedBroadcast(PackageInstaller.SessionInfo sessionInfo,
20844             int userId) {
20845         if (TextUtils.isEmpty(sessionInfo.installerPackageName)) {
20846             return;
20847         }
20848         Intent sessionUpdatedIntent = new Intent(PackageInstaller.ACTION_SESSION_UPDATED)
20849                 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20850                 .setPackage(sessionInfo.installerPackageName);
20851         mContext.sendBroadcastAsUser(sessionUpdatedIntent, UserHandle.of(userId));
20852     }
20853
20854     public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) {
20855         UserManagerService ums = UserManagerService.getInstance();
20856         if (ums != null) {
20857             final UserInfo parent = ums.getProfileParent(userId);
20858             final int launcherUid = (parent != null) ? parent.id : userId;
20859             final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid);
20860             if (launcherComponent != null) {
20861                 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20862                         .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20863                         .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20864                         .setPackage(launcherComponent.getPackageName());
20865                 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid));
20866             }
20867             // TODO(b/122900055) Change/Remove this and replace with new permission role.
20868             if (mAppPredictionServicePackage != null) {
20869                 Intent predictorIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED)
20870                         .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo)
20871                         .putExtra(Intent.EXTRA_USER, UserHandle.of(userId))
20872                         .setPackage(mAppPredictionServicePackage);
20873                 mContext.sendBroadcastAsUser(predictorIntent, UserHandle.of(launcherUid));
20874             }
20875         }
20876     }
20877
20878     /**
20879      * Report the 'Home' activity which is currently set as "always use this one". If non is set
20880      * then reports the most likely home activity or null if there are more than one.
20881      */
20882     private ComponentName getDefaultHomeActivity(int userId) {
20883         List<ResolveInfo> allHomeCandidates = new ArrayList<>();
20884         ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId);
20885         if (cn != null) {
20886             return cn;
20887         }
20888
20889         // Find the launcher with the highest priority and return that component if there are no
20890         // other home activity with the same priority.
20891         int lastPriority = Integer.MIN_VALUE;
20892         ComponentName lastComponent = null;
20893         final int size = allHomeCandidates.size();
20894         for (int i = 0; i < size; i++) {
20895             final ResolveInfo ri = allHomeCandidates.get(i);
20896             if (ri.priority > lastPriority) {
20897                 lastComponent = ri.activityInfo.getComponentName();
20898                 lastPriority = ri.priority;
20899             } else if (ri.priority == lastPriority) {
20900                 // Two components found with same priority.
20901                 lastComponent = null;
20902             }
20903         }
20904         return lastComponent;
20905     }
20906
20907     private Intent getHomeIntent() {
20908         Intent intent = new Intent(Intent.ACTION_MAIN);
20909         intent.addCategory(Intent.CATEGORY_HOME);
20910         intent.addCategory(Intent.CATEGORY_DEFAULT);
20911         return intent;
20912     }
20913
20914     private IntentFilter getHomeFilter() {
20915         IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
20916         filter.addCategory(Intent.CATEGORY_HOME);
20917         filter.addCategory(Intent.CATEGORY_DEFAULT);
20918         return filter;
20919     }
20920
20921     ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
20922             int userId) {
20923         Intent intent  = getHomeIntent();
20924         List<ResolveInfo> resolveInfos = queryIntentActivitiesInternal(intent, null,
20925                 PackageManager.GET_META_DATA, userId);
20926         allHomeCandidates.clear();
20927         if (resolveInfos == null) {
20928             return null;
20929         }
20930         allHomeCandidates.addAll(resolveInfos);
20931
20932         PackageManagerInternal.DefaultHomeProvider provider;
20933         synchronized (mPackages) {
20934             provider = mDefaultHomeProvider;
20935         }
20936         if (provider == null) {
20937             Slog.e(TAG, "mDefaultHomeProvider is null");
20938             return null;
20939         }
20940         String packageName = provider.getDefaultHome(userId);
20941         if (packageName == null) {
20942             return null;
20943         }
20944         int resolveInfosSize = resolveInfos.size();
20945         for (int i = 0; i < resolveInfosSize; i++) {
20946             ResolveInfo resolveInfo = resolveInfos.get(i);
20947
20948             if (resolveInfo.activityInfo != null && TextUtils.equals(
20949                     resolveInfo.activityInfo.packageName, packageName)) {
20950                 return new ComponentName(resolveInfo.activityInfo.packageName,
20951                         resolveInfo.activityInfo.name);
20952             }
20953         }
20954         return null;
20955     }
20956
20957     /** <b>must not hold {@link #mPackages}</b> */
20958     private void updateDefaultHomeNotLocked(SparseBooleanArray userIds) {
20959         if (Thread.holdsLock(mPackages)) {
20960             Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName()
20961                     + " is holding mPackages", new Throwable());
20962         }
20963         for (int i = userIds.size() - 1; i >= 0; --i) {
20964             final int userId = userIds.keyAt(i);
20965             updateDefaultHomeNotLocked(userId);
20966         }
20967     }
20968
20969     /**
20970      * <b>must not hold {@link #mPackages}</b>
20971      *
20972      * @return Whether the ACTION_PREFERRED_ACTIVITY_CHANGED broadcast has been scheduled.
20973      */
20974     private boolean updateDefaultHomeNotLocked(int userId) {
20975         if (Thread.holdsLock(mPackages)) {
20976             Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName()
20977                     + " is holding mPackages", new Throwable());
20978         }
20979         if (!mSystemReady) {
20980             // We might get called before system is ready because of package changes etc, but
20981             // finding preferred activity depends on settings provider, so we ignore the update
20982             // before that.
20983             return false;
20984         }
20985         final Intent intent = getHomeIntent();
20986         final List<ResolveInfo> resolveInfos = queryIntentActivitiesInternal(intent, null,
20987                 PackageManager.GET_META_DATA, userId);
20988         final ResolveInfo preferredResolveInfo = findPreferredActivityNotLocked(
20989                 intent, null, 0, resolveInfos, 0, true, false, false, userId);
20990         final String packageName = preferredResolveInfo != null
20991                 && preferredResolveInfo.activityInfo != null
20992                 ? preferredResolveInfo.activityInfo.packageName : null;
20993         final PackageManagerInternal.DefaultHomeProvider provider;
20994         synchronized (mPackages) {
20995             provider = mDefaultHomeProvider;
20996         }
20997         if (provider == null) {
20998             Slog.e(TAG, "Default home provider has not been set");
20999             return false;
21000         }
21001         final String currentPackageName = provider.getDefaultHome(userId);
21002         if (TextUtils.equals(currentPackageName, packageName)) {
21003             return false;
21004         }
21005         final String[] callingPackages = getPackagesForUid(Binder.getCallingUid());
21006         if (callingPackages != null && ArrayUtils.contains(callingPackages,
21007                 mRequiredPermissionControllerPackage)) {
21008             // PermissionController manages default home directly.
21009             return false;
21010         }
21011         provider.setDefaultHomeAsync(packageName, userId, (successful) -> {
21012             if (successful) {
21013                 postPreferredActivityChangedBroadcast(userId);
21014             }
21015         });
21016         return true;
21017     }
21018
21019     @Override
21020     public void setHomeActivity(ComponentName comp, int userId) {
21021         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21022             return;
21023         }
21024         ArrayList<ResolveInfo> homeActivities = new ArrayList<>();
21025         getHomeActivitiesAsUser(homeActivities, userId);
21026
21027         boolean found = false;
21028
21029         final int size = homeActivities.size();
21030         final ComponentName[] set = new ComponentName[size];
21031         for (int i = 0; i < size; i++) {
21032             final ResolveInfo candidate = homeActivities.get(i);
21033             final ActivityInfo info = candidate.activityInfo;
21034             final ComponentName activityName = new ComponentName(info.packageName, info.name);
21035             set[i] = activityName;
21036             if (!found && activityName.equals(comp)) {
21037                 found = true;
21038             }
21039         }
21040         if (!found) {
21041             throw new IllegalArgumentException("Component " + comp + " cannot be home on user "
21042                     + userId);
21043         }
21044         replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY,
21045                 set, comp, userId);
21046     }
21047
21048     private @Nullable String getSetupWizardPackageName() {
21049         final Intent intent = new Intent(Intent.ACTION_MAIN);
21050         intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
21051
21052         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21053                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21054                         | MATCH_DISABLED_COMPONENTS,
21055                 UserHandle.myUserId());
21056         if (matches.size() == 1) {
21057             return matches.get(0).getComponentInfo().packageName;
21058         } else {
21059             Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size()
21060                     + ": matches=" + matches);
21061             return null;
21062         }
21063     }
21064
21065     private @Nullable String getStorageManagerPackageName() {
21066         final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
21067
21068         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null,
21069                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21070                         | MATCH_DISABLED_COMPONENTS,
21071                 UserHandle.myUserId());
21072         if (matches.size() == 1) {
21073             return matches.get(0).getComponentInfo().packageName;
21074         } else {
21075             Slog.e(TAG, "There should probably be exactly one storage manager; found "
21076                     + matches.size() + ": matches=" + matches);
21077             return null;
21078         }
21079     }
21080
21081     @Override
21082     public String getSystemTextClassifierPackageName() {
21083         return mContext.getString(R.string.config_defaultTextClassifierPackage);
21084     }
21085
21086     @Override
21087     public @Nullable String getAttentionServicePackageName() {
21088         final String flattenedComponentName =
21089                 mContext.getString(R.string.config_defaultAttentionService);
21090         if (flattenedComponentName != null) {
21091             ComponentName componentName = ComponentName.unflattenFromString(flattenedComponentName);
21092             if (componentName != null && componentName.getPackageName() != null) {
21093                 return componentName.getPackageName();
21094             }
21095         }
21096         return null;
21097     }
21098
21099     private @Nullable String getDocumenterPackageName() {
21100         final Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
21101         intent.addCategory(Intent.CATEGORY_OPENABLE);
21102         intent.setType("*/*");
21103         final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
21104
21105         final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, resolvedType,
21106                 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE
21107                         | MATCH_DISABLED_COMPONENTS,
21108                 UserHandle.myUserId());
21109         if (matches.size() == 1) {
21110             return matches.get(0).getComponentInfo().packageName;
21111         } else {
21112             Slog.e(TAG, "There should probably be exactly one documenter; found "
21113                     + matches.size() + ": matches=" + matches);
21114             return null;
21115         }
21116     }
21117
21118     @Override
21119     public String getWellbeingPackageName() {
21120         return mContext.getString(R.string.config_defaultWellbeingPackage);
21121     }
21122
21123     @Override
21124     public String getAppPredictionServicePackageName() {
21125         String flattenedAppPredictionServiceComponentName =
21126                 mContext.getString(R.string.config_defaultAppPredictionService);
21127         if (flattenedAppPredictionServiceComponentName == null) {
21128             return null;
21129         }
21130         ComponentName appPredictionServiceComponentName =
21131                 ComponentName.unflattenFromString(flattenedAppPredictionServiceComponentName);
21132         if (appPredictionServiceComponentName == null) {
21133             return null;
21134         }
21135         return appPredictionServiceComponentName.getPackageName();
21136     }
21137
21138     @Override
21139     public String getSystemCaptionsServicePackageName() {
21140         String flattenedSystemCaptionsServiceComponentName =
21141                 mContext.getString(R.string.config_defaultSystemCaptionsService);
21142
21143         if (TextUtils.isEmpty(flattenedSystemCaptionsServiceComponentName)) {
21144             return null;
21145         }
21146
21147         ComponentName systemCaptionsServiceComponentName =
21148                 ComponentName.unflattenFromString(flattenedSystemCaptionsServiceComponentName);
21149         if (systemCaptionsServiceComponentName == null) {
21150             return null;
21151         }
21152         return systemCaptionsServiceComponentName.getPackageName();
21153     }
21154
21155     public String getIncidentReportApproverPackageName() {
21156         return mContext.getString(R.string.config_incidentReportApproverPackage);
21157     }
21158
21159     @Override
21160     public void setApplicationEnabledSetting(String appPackageName,
21161             int newState, int flags, int userId, String callingPackage) {
21162         if (!sUserManager.exists(userId)) return;
21163         if (callingPackage == null) {
21164             callingPackage = Integer.toString(Binder.getCallingUid());
21165         }
21166         setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
21167     }
21168
21169     @Override
21170     public void setUpdateAvailable(String packageName, boolean updateAvailable) {
21171         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
21172         synchronized (mPackages) {
21173             final PackageSetting pkgSetting = mSettings.mPackages.get(packageName);
21174             if (pkgSetting != null) {
21175                 pkgSetting.setUpdateAvailable(updateAvailable);
21176             }
21177         }
21178     }
21179
21180     @Override
21181     public void setComponentEnabledSetting(ComponentName componentName,
21182             int newState, int flags, int userId) {
21183         if (!sUserManager.exists(userId)) return;
21184         setEnabledSetting(componentName.getPackageName(),
21185                 componentName.getClassName(), newState, flags, userId, null);
21186     }
21187
21188     private void setEnabledSetting(final String packageName, String className, int newState,
21189             final int flags, int userId, String callingPackage) {
21190         if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
21191               || newState == COMPONENT_ENABLED_STATE_ENABLED
21192               || newState == COMPONENT_ENABLED_STATE_DISABLED
21193               || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21194               || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
21195             throw new IllegalArgumentException("Invalid new component state: "
21196                     + newState);
21197         }
21198         PackageSetting pkgSetting;
21199         final int callingUid = Binder.getCallingUid();
21200         final int permission;
21201         if (callingUid == Process.SYSTEM_UID) {
21202             permission = PackageManager.PERMISSION_GRANTED;
21203         } else {
21204             permission = mContext.checkCallingOrSelfPermission(
21205                     android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21206         }
21207         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21208                 false /* requireFullPermission */, true /* checkShell */, "set enabled");
21209         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21210         boolean sendNow = false;
21211         boolean isApp = (className == null);
21212         final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null);
21213         String componentName = isApp ? packageName : className;
21214         ArrayList<String> components;
21215
21216         // reader
21217         synchronized (mPackages) {
21218             pkgSetting = mSettings.mPackages.get(packageName);
21219             if (pkgSetting == null) {
21220                 if (!isCallerInstantApp) {
21221                     if (className == null) {
21222                         throw new IllegalArgumentException("Unknown package: " + packageName);
21223                     }
21224                     throw new IllegalArgumentException(
21225                             "Unknown component: " + packageName + "/" + className);
21226                 } else {
21227                     // throw SecurityException to prevent leaking package information
21228                     throw new SecurityException(
21229                             "Attempt to change component state; "
21230                             + "pid=" + Binder.getCallingPid()
21231                             + ", uid=" + callingUid
21232                             + (className == null
21233                                     ? ", package=" + packageName
21234                                     : ", component=" + packageName + "/" + className));
21235                 }
21236             }
21237         }
21238
21239         // Limit who can change which apps
21240         if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) {
21241             // Don't allow apps that don't have permission to modify other apps
21242             if (!allowedByPermission
21243                     || filterAppAccessLPr(pkgSetting, callingUid, userId)) {
21244                 throw new SecurityException(
21245                         "Attempt to change component state; "
21246                         + "pid=" + Binder.getCallingPid()
21247                         + ", uid=" + callingUid
21248                         + (className == null
21249                                 ? ", package=" + packageName
21250                                 : ", component=" + packageName + "/" + className));
21251             }
21252             // Don't allow changing protected packages.
21253             if (mProtectedPackages.isPackageStateProtected(userId, packageName)) {
21254                 throw new SecurityException("Cannot disable a protected package: " + packageName);
21255             }
21256         }
21257         // Only allow apps with CHANGE_COMPONENT_ENABLED_STATE permission to change hidden
21258         // app details activity
21259         if (PackageManager.APP_DETAILS_ACTIVITY_CLASS_NAME.equals(className)
21260                 && !allowedByPermission) {
21261             throw new SecurityException("Cannot disable a system-generated component");
21262         }
21263
21264         synchronized (mPackages) {
21265             if (callingUid == Process.SHELL_UID
21266                     && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) {
21267                 // Shell can only change whole packages between ENABLED and DISABLED_USER states
21268                 // unless it is a test package.
21269                 int oldState = pkgSetting.getEnabled(userId);
21270                 if (className == null
21271                         &&
21272                         (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER
21273                                 || oldState == COMPONENT_ENABLED_STATE_DEFAULT
21274                                 || oldState == COMPONENT_ENABLED_STATE_ENABLED)
21275                         &&
21276                         (newState == COMPONENT_ENABLED_STATE_DISABLED_USER
21277                                 || newState == COMPONENT_ENABLED_STATE_DEFAULT
21278                                 || newState == COMPONENT_ENABLED_STATE_ENABLED)) {
21279                     // ok
21280                 } else {
21281                     throw new SecurityException(
21282                             "Shell cannot change component state for " + packageName + "/"
21283                                     + className + " to " + newState);
21284                 }
21285             }
21286         }
21287         if (className == null) {
21288             // We're dealing with an application/package level state change
21289             synchronized (mPackages) {
21290                 if (pkgSetting.getEnabled(userId) == newState) {
21291                     // Nothing to do
21292                     return;
21293                 }
21294             }
21295             // If we're enabling a system stub, there's a little more work to do.
21296             // Prior to enabling the package, we need to decompress the APK(s) to the
21297             // data partition and then replace the version on the system partition.
21298             final PackageParser.Package deletedPkg = pkgSetting.pkg;
21299             final boolean isSystemStub = deletedPkg.isStub
21300                     && deletedPkg.isSystem();
21301             if (isSystemStub
21302                     && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21303                             || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) {
21304                 if (!enableCompressedPackage(deletedPkg)) {
21305                     return;
21306                 }
21307             }
21308             if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
21309                 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
21310                 // Don't care about who enables an app.
21311                 callingPackage = null;
21312             }
21313             synchronized (mPackages) {
21314                 pkgSetting.setEnabled(newState, userId, callingPackage);
21315             }
21316         } else {
21317             synchronized (mPackages) {
21318                 // We're dealing with a component level state change
21319                 // First, verify that this is a valid class name.
21320                 PackageParser.Package pkg = pkgSetting.pkg;
21321                 if (pkg == null || !pkg.hasComponentClassName(className)) {
21322                     if (pkg != null &&
21323                             pkg.applicationInfo.targetSdkVersion >=
21324                                     Build.VERSION_CODES.JELLY_BEAN) {
21325                         throw new IllegalArgumentException("Component class " + className
21326                                 + " does not exist in " + packageName);
21327                     } else {
21328                         Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
21329                                 + className + " does not exist in " + packageName);
21330                     }
21331                 }
21332                 switch (newState) {
21333                     case COMPONENT_ENABLED_STATE_ENABLED:
21334                         if (!pkgSetting.enableComponentLPw(className, userId)) {
21335                             return;
21336                         }
21337                         break;
21338                     case COMPONENT_ENABLED_STATE_DISABLED:
21339                         if (!pkgSetting.disableComponentLPw(className, userId)) {
21340                             return;
21341                         }
21342                         break;
21343                     case COMPONENT_ENABLED_STATE_DEFAULT:
21344                         if (!pkgSetting.restoreComponentLPw(className, userId)) {
21345                             return;
21346                         }
21347                         break;
21348                     default:
21349                         Slog.e(TAG, "Invalid new component state: " + newState);
21350                         return;
21351                 }
21352             }
21353         }
21354         synchronized (mPackages) {
21355             scheduleWritePackageRestrictionsLocked(userId);
21356             updateSequenceNumberLP(pkgSetting, new int[] { userId });
21357             final long callingId = Binder.clearCallingIdentity();
21358             try {
21359                 updateInstantAppInstallerLocked(packageName);
21360             } finally {
21361                 Binder.restoreCallingIdentity(callingId);
21362             }
21363             components = mPendingBroadcasts.get(userId, packageName);
21364             final boolean newPackage = components == null;
21365             if (newPackage) {
21366                 components = new ArrayList<>();
21367             }
21368             if (!components.contains(componentName)) {
21369                 components.add(componentName);
21370             }
21371             if ((flags&PackageManager.DONT_KILL_APP) == 0) {
21372                 sendNow = true;
21373                 // Purge entry from pending broadcast list if another one exists already
21374                 // since we are sending one right away.
21375                 mPendingBroadcasts.remove(userId, packageName);
21376             } else {
21377                 if (newPackage) {
21378                     mPendingBroadcasts.put(userId, packageName, components);
21379                 }
21380                 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
21381                     // Schedule a message - if it has been a "reasonably long time" since the
21382                     // service started, send the broadcast with a delay of one second to avoid
21383                     // delayed reactions from the receiver, else keep the default ten second delay
21384                     // to avoid extreme thrashing on service startup.
21385                     final long broadcastDelay = SystemClock.uptimeMillis() > mServiceStartWithDelay
21386                                                 ? BROADCAST_DELAY
21387                                                 : BROADCAST_DELAY_DURING_STARTUP;
21388                     mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, broadcastDelay);
21389                 }
21390             }
21391         }
21392
21393         long callingId = Binder.clearCallingIdentity();
21394         try {
21395             if (sendNow) {
21396                 int packageUid = UserHandle.getUid(userId, pkgSetting.appId);
21397                 sendPackageChangedBroadcast(packageName,
21398                         (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
21399             }
21400         } finally {
21401             Binder.restoreCallingIdentity(callingId);
21402         }
21403     }
21404
21405     @Override
21406     public void flushPackageRestrictionsAsUser(int userId) {
21407         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
21408             return;
21409         }
21410         if (!sUserManager.exists(userId)) {
21411             return;
21412         }
21413         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/,
21414                 false /* checkShell */, "flushPackageRestrictions");
21415         synchronized (mPackages) {
21416             mSettings.writePackageRestrictionsLPr(userId);
21417             mDirtyUsers.remove(userId);
21418             if (mDirtyUsers.isEmpty()) {
21419                 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS);
21420             }
21421         }
21422     }
21423
21424     private void sendPackageChangedBroadcast(String packageName,
21425             boolean killFlag, ArrayList<String> componentNames, int packageUid) {
21426         if (DEBUG_INSTALL)
21427             Log.v(TAG, "Sending package changed: package=" + packageName + " components="
21428                     + componentNames);
21429         Bundle extras = new Bundle(4);
21430         extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
21431         String nameList[] = new String[componentNames.size()];
21432         componentNames.toArray(nameList);
21433         extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
21434         extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
21435         extras.putInt(Intent.EXTRA_UID, packageUid);
21436         // If this is not reporting a change of the overall package, then only send it
21437         // to registered receivers.  We don't want to launch a swath of apps for every
21438         // little component state change.
21439         final int flags = !componentNames.contains(packageName)
21440                 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0;
21441         final int userId = UserHandle.getUserId(packageUid);
21442         final boolean isInstantApp = isInstantApp(packageName, userId);
21443         final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId };
21444         final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY;
21445         sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, flags, null, null,
21446                 userIds, instantUserIds);
21447     }
21448
21449     @Override
21450     public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
21451         if (!sUserManager.exists(userId)) return;
21452         final int callingUid = Binder.getCallingUid();
21453         if (getInstantAppPackageName(callingUid) != null) {
21454             return;
21455         }
21456         final int permission = mContext.checkCallingOrSelfPermission(
21457                 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
21458         final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
21459         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21460                 true /* requireFullPermission */, true /* checkShell */, "stop package");
21461         // writer
21462         synchronized (mPackages) {
21463             final PackageSetting ps = mSettings.mPackages.get(packageName);
21464             if (!filterAppAccessLPr(ps, callingUid, userId)
21465                     && mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
21466                             allowedByPermission, callingUid, userId)) {
21467                 scheduleWritePackageRestrictionsLocked(userId);
21468             }
21469         }
21470     }
21471
21472     @Override
21473     public String getInstallerPackageName(String packageName) {
21474         final int callingUid = Binder.getCallingUid();
21475         synchronized (mPackages) {
21476             final PackageSetting ps = mSettings.mPackages.get(packageName);
21477             if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) {
21478                 return null;
21479             }
21480             // InstallerPackageName for Apex is not stored in PackageManager
21481             if (ps == null && mApexManager.isApexPackage(packageName)) {
21482                 return null;
21483             }
21484             return mSettings.getInstallerPackageNameLPr(packageName);
21485         }
21486     }
21487
21488     public boolean isOrphaned(String packageName) {
21489         // reader
21490         synchronized (mPackages) {
21491             if (!mPackages.containsKey(packageName)) {
21492                 return false;
21493             }
21494             return mSettings.isOrphaned(packageName);
21495         }
21496     }
21497
21498     @Override
21499     public int getApplicationEnabledSetting(String packageName, int userId) {
21500         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21501         int callingUid = Binder.getCallingUid();
21502         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21503                 false /* requireFullPermission */, false /* checkShell */, "get enabled");
21504         // reader
21505         synchronized (mPackages) {
21506             if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) {
21507                 return COMPONENT_ENABLED_STATE_DISABLED;
21508             }
21509             return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
21510         }
21511     }
21512
21513     @Override
21514     public int getComponentEnabledSetting(@NonNull ComponentName component, int userId) {
21515         if (component == null) return COMPONENT_ENABLED_STATE_DEFAULT;
21516         if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
21517         int callingUid = Binder.getCallingUid();
21518         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
21519                 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled");
21520         synchronized (mPackages) {
21521             if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid,
21522                     component, TYPE_UNKNOWN, userId)) {
21523                 return COMPONENT_ENABLED_STATE_DISABLED;
21524             }
21525             return mSettings.getComponentEnabledSettingLPr(component, userId);
21526         }
21527     }
21528
21529     @Override
21530     public void enterSafeMode() {
21531         enforceSystemOrRoot("Only the system can request entering safe mode");
21532
21533         if (!mSystemReady) {
21534             mSafeMode = true;
21535         }
21536     }
21537
21538     @Override
21539     public void systemReady() {
21540         enforceSystemOrRoot("Only the system can claim the system is ready");
21541
21542         mSystemReady = true;
21543         final ContentResolver resolver = mContext.getContentResolver();
21544         ContentObserver co = new ContentObserver(mHandler) {
21545             @Override
21546             public void onChange(boolean selfChange) {
21547                 final boolean ephemeralFeatureDisabled =
21548                         Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0;
21549                 for (int userId : UserManagerService.getInstance().getUserIds()) {
21550                     final boolean instantAppsDisabledForUser =
21551                             ephemeralFeatureDisabled || Secure.getIntForUser(resolver,
21552                                     Secure.INSTANT_APPS_ENABLED, 1, userId) == 0;
21553                     mWebInstantAppsDisabled.put(userId, instantAppsDisabledForUser);
21554                 }
21555             }
21556         };
21557         mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global
21558                         .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE),
21559                 false, co, UserHandle.USER_ALL);
21560         mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure
21561                         .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_ALL);
21562         co.onChange(true);
21563
21564         // Disable any carrier apps. We do this very early in boot to prevent the apps from being
21565         // disabled after already being started.
21566         CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this,
21567                 mContext.getContentResolver(), UserHandle.USER_SYSTEM);
21568
21569         disableSkuSpecificApps();
21570
21571         // Read the compatibilty setting when the system is ready.
21572         boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
21573                 mContext.getContentResolver(),
21574                 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
21575         PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
21576
21577         if (DEBUG_SETTINGS) {
21578             Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
21579         }
21580
21581         int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
21582
21583         synchronized (mPackages) {
21584             // Verify that all of the preferred activity components actually
21585             // exist.  It is possible for applications to be updated and at
21586             // that point remove a previously declared activity component that
21587             // had been set as a preferred activity.  We try to clean this up
21588             // the next time we encounter that preferred activity, but it is
21589             // possible for the user flow to never be able to return to that
21590             // situation so here we do a sanity check to make sure we haven't
21591             // left any junk around.
21592             ArrayList<PreferredActivity> removed = new ArrayList<>();
21593             for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
21594                 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
21595                 removed.clear();
21596                 for (PreferredActivity pa : pir.filterSet()) {
21597                     if (!mComponentResolver.isActivityDefined(pa.mPref.mComponent)) {
21598                         removed.add(pa);
21599                     }
21600                 }
21601                 if (removed.size() > 0) {
21602                     for (int r=0; r<removed.size(); r++) {
21603                         PreferredActivity pa = removed.get(r);
21604                         Slog.w(TAG, "Removing dangling preferred activity: "
21605                                 + pa.mPref.mComponent);
21606                         pir.removeFilter(pa);
21607                     }
21608                     mSettings.writePackageRestrictionsLPr(
21609                             mSettings.mPreferredActivities.keyAt(i));
21610                 }
21611             }
21612
21613             for (int userId : UserManagerService.getInstance().getUserIds()) {
21614                 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
21615                     grantPermissionsUserIds = ArrayUtils.appendInt(
21616                             grantPermissionsUserIds, userId);
21617                 }
21618             }
21619         }
21620
21621         sUserManager.systemReady();
21622         // If we upgraded grant all default permissions before kicking off.
21623         for (int userId : grantPermissionsUserIds) {
21624             mDefaultPermissionPolicy.grantDefaultPermissions(userId);
21625         }
21626
21627         if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
21628             // If we did not grant default permissions, we preload from this the
21629             // default permission exceptions lazily to ensure we don't hit the
21630             // disk on a new user creation.
21631             mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
21632         }
21633
21634         // Now that we've scanned all packages, and granted any default
21635         // permissions, ensure permissions are updated. Beware of dragons if you
21636         // try optimizing this.
21637         synchronized (mPackages) {
21638             mPermissionManager.updateAllPermissions(
21639                     StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(),
21640                     mPermissionCallback);
21641
21642             final PermissionPolicyInternal permissionPolicyInternal =
21643                     LocalServices.getService(PermissionPolicyInternal.class);
21644             permissionPolicyInternal.setOnInitializedCallback(userId -> {
21645                 // The SDK updated case is already handled when we run during the ctor.
21646                 synchronized (mPackages) {
21647                     mPermissionManager.updateAllPermissions(
21648                             StorageManager.UUID_PRIVATE_INTERNAL, false /*sdkUpdated*/,
21649                             mPackages.values(), mPermissionCallback);
21650                 }
21651             });
21652         }
21653
21654         // Watch for external volumes that come and go over time
21655         final StorageManager storage = mContext.getSystemService(StorageManager.class);
21656         storage.registerListener(mStorageListener);
21657
21658         mInstallerService.systemReady();
21659         mApexManager.systemReady();
21660         mPackageDexOptimizer.systemReady();
21661
21662         getStorageManagerInternal().addExternalStoragePolicy(
21663                 new StorageManagerInternal.ExternalStorageMountPolicy() {
21664             @Override
21665             public int getMountMode(int uid, String packageName) {
21666                 if (Process.isIsolated(uid)) {
21667                     return Zygote.MOUNT_EXTERNAL_NONE;
21668                 }
21669                 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21670                     return Zygote.MOUNT_EXTERNAL_DEFAULT;
21671                 }
21672                 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
21673                     return Zygote.MOUNT_EXTERNAL_READ;
21674                 }
21675                 return Zygote.MOUNT_EXTERNAL_WRITE;
21676             }
21677
21678             @Override
21679             public boolean hasExternalStorage(int uid, String packageName) {
21680                 return true;
21681             }
21682         });
21683
21684         // Now that we're mostly running, clean up stale users and apps
21685         sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
21686         reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
21687
21688         mPermissionManager.systemReady();
21689
21690         if (mInstantAppResolverConnection != null) {
21691             mContext.registerReceiver(new BroadcastReceiver() {
21692                 @Override
21693                 public void onReceive(Context context, Intent intent) {
21694                     mInstantAppResolverConnection.optimisticBind();
21695                     mContext.unregisterReceiver(this);
21696                 }
21697             }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
21698         }
21699
21700         mModuleInfoProvider.systemReady();
21701
21702         // Installer service might attempt to install some packages that have been staged for
21703         // installation on reboot. Make sure this is the last component to be call since the
21704         // installation might require other components to be ready.
21705         mInstallerService.restoreAndApplyStagedSessionIfNeeded();
21706     }
21707
21708     public void waitForAppDataPrepared() {
21709         if (mPrepareAppDataFuture == null) {
21710             return;
21711         }
21712         ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData");
21713         mPrepareAppDataFuture = null;
21714     }
21715
21716     @Override
21717     public boolean isSafeMode() {
21718         // allow instant applications
21719         return mSafeMode;
21720     }
21721
21722     @Override
21723     public boolean hasSystemUidErrors() {
21724         // allow instant applications
21725         return mHasSystemUidErrors;
21726     }
21727
21728     static String arrayToString(int[] array) {
21729         StringBuilder stringBuilder = new StringBuilder(128);
21730         stringBuilder.append('[');
21731         if (array != null) {
21732             for (int i=0; i<array.length; i++) {
21733                 if (i > 0) stringBuilder.append(", ");
21734                 stringBuilder.append(array[i]);
21735             }
21736         }
21737         stringBuilder.append(']');
21738         return stringBuilder.toString();
21739     }
21740
21741     @Override
21742     public void onShellCommand(FileDescriptor in, FileDescriptor out,
21743             FileDescriptor err, String[] args, ShellCallback callback,
21744             ResultReceiver resultReceiver) {
21745         (new PackageManagerShellCommand(this)).exec(
21746                 this, in, out, err, args, callback, resultReceiver);
21747     }
21748
21749     @SuppressWarnings("resource")
21750     @Override
21751     protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
21752         if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return;
21753
21754         DumpState dumpState = new DumpState();
21755         boolean fullPreferred = false;
21756         boolean checkin = false;
21757
21758         String packageName = null;
21759         ArraySet<String> permissionNames = null;
21760
21761         int opti = 0;
21762         while (opti < args.length) {
21763             String opt = args[opti];
21764             if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
21765                 break;
21766             }
21767             opti++;
21768
21769             if ("-a".equals(opt)) {
21770                 // Right now we only know how to print all.
21771             } else if ("-h".equals(opt)) {
21772                 pw.println("Package manager dump options:");
21773                 pw.println("  [-h] [-f] [--checkin] [--all-components] [cmd] ...");
21774                 pw.println("    --checkin: dump for a checkin");
21775                 pw.println("    -f: print details of intent filters");
21776                 pw.println("    -h: print this help");
21777                 pw.println("    --all-components: include all component names in package dump");
21778                 pw.println("  cmd may be one of:");
21779                 pw.println("    apex: list active APEXes and APEX session state");
21780                 pw.println("    l[ibraries]: list known shared libraries");
21781                 pw.println("    f[eatures]: list device features");
21782                 pw.println("    k[eysets]: print known keysets");
21783                 pw.println("    r[esolvers] [activity|service|receiver|content]: dump intent resolvers");
21784                 pw.println("    perm[issions]: dump permissions");
21785                 pw.println("    permission [name ...]: dump declaration and use of given permission");
21786                 pw.println("    pref[erred]: print preferred package settings");
21787                 pw.println("    preferred-xml [--full]: print preferred package settings as xml");
21788                 pw.println("    prov[iders]: dump content providers");
21789                 pw.println("    p[ackages]: dump installed packages");
21790                 pw.println("    s[hared-users]: dump shared user IDs");
21791                 pw.println("    m[essages]: print collected runtime messages");
21792                 pw.println("    v[erifiers]: print package verifier info");
21793                 pw.println("    d[omain-preferred-apps]: print domains preferred apps");
21794                 pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
21795                 pw.println("    version: print database version info");
21796                 pw.println("    write: write current settings now");
21797                 pw.println("    installs: details about install sessions");
21798                 pw.println("    check-permission <permission> <package> [<user>]: does pkg hold perm?");
21799                 pw.println("    dexopt: dump dexopt state");
21800                 pw.println("    compiler-stats: dump compiler statistics");
21801                 pw.println("    service-permissions: dump permissions required by services");
21802                 pw.println("    <package.name>: info about given package");
21803                 return;
21804             } else if ("--checkin".equals(opt)) {
21805                 checkin = true;
21806             } else if ("--all-components".equals(opt)) {
21807                 dumpState.setOptionEnabled(DumpState.OPTION_DUMP_ALL_COMPONENTS);
21808             } else if ("-f".equals(opt)) {
21809                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21810             } else if ("--proto".equals(opt)) {
21811                 dumpProto(fd);
21812                 return;
21813             } else {
21814                 pw.println("Unknown argument: " + opt + "; use -h for help");
21815             }
21816         }
21817
21818         // Is the caller requesting to dump a particular piece of data?
21819         if (opti < args.length) {
21820             String cmd = args[opti];
21821             opti++;
21822             // Is this a package name?
21823             if ("android".equals(cmd) || cmd.contains(".")) {
21824                 packageName = cmd;
21825                 // When dumping a single package, we always dump all of its
21826                 // filter information since the amount of data will be reasonable.
21827                 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
21828             } else if ("check-permission".equals(cmd)) {
21829                 if (opti >= args.length) {
21830                     pw.println("Error: check-permission missing permission argument");
21831                     return;
21832                 }
21833                 String perm = args[opti];
21834                 opti++;
21835                 if (opti >= args.length) {
21836                     pw.println("Error: check-permission missing package argument");
21837                     return;
21838                 }
21839
21840                 String pkg = args[opti];
21841                 opti++;
21842                 int user = UserHandle.getUserId(Binder.getCallingUid());
21843                 if (opti < args.length) {
21844                     try {
21845                         user = Integer.parseInt(args[opti]);
21846                     } catch (NumberFormatException e) {
21847                         pw.println("Error: check-permission user argument is not a number: "
21848                                 + args[opti]);
21849                         return;
21850                     }
21851                 }
21852
21853                 // Normalize package name to handle renamed packages and static libs
21854                 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST);
21855
21856                 pw.println(checkPermission(perm, pkg, user));
21857                 return;
21858             } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
21859                 dumpState.setDump(DumpState.DUMP_LIBS);
21860             } else if ("f".equals(cmd) || "features".equals(cmd)) {
21861                 dumpState.setDump(DumpState.DUMP_FEATURES);
21862             } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
21863                 if (opti >= args.length) {
21864                     dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS
21865                             | DumpState.DUMP_SERVICE_RESOLVERS
21866                             | DumpState.DUMP_RECEIVER_RESOLVERS
21867                             | DumpState.DUMP_CONTENT_RESOLVERS);
21868                 } else {
21869                     while (opti < args.length) {
21870                         String name = args[opti];
21871                         if ("a".equals(name) || "activity".equals(name)) {
21872                             dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS);
21873                         } else if ("s".equals(name) || "service".equals(name)) {
21874                             dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS);
21875                         } else if ("r".equals(name) || "receiver".equals(name)) {
21876                             dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS);
21877                         } else if ("c".equals(name) || "content".equals(name)) {
21878                             dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS);
21879                         } else {
21880                             pw.println("Error: unknown resolver table type: " + name);
21881                             return;
21882                         }
21883                         opti++;
21884                     }
21885                 }
21886             } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
21887                 dumpState.setDump(DumpState.DUMP_PERMISSIONS);
21888             } else if ("permission".equals(cmd)) {
21889                 if (opti >= args.length) {
21890                     pw.println("Error: permission requires permission name");
21891                     return;
21892                 }
21893                 permissionNames = new ArraySet<>();
21894                 while (opti < args.length) {
21895                     permissionNames.add(args[opti]);
21896                     opti++;
21897                 }
21898                 dumpState.setDump(DumpState.DUMP_PERMISSIONS
21899                         | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS);
21900             } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
21901                 dumpState.setDump(DumpState.DUMP_PREFERRED);
21902             } else if ("preferred-xml".equals(cmd)) {
21903                 dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
21904                 if (opti < args.length && "--full".equals(args[opti])) {
21905                     fullPreferred = true;
21906                     opti++;
21907                 }
21908             } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
21909                 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
21910             } else if ("p".equals(cmd) || "packages".equals(cmd)) {
21911                 dumpState.setDump(DumpState.DUMP_PACKAGES);
21912             } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
21913                 dumpState.setDump(DumpState.DUMP_SHARED_USERS);
21914                 if (opti < args.length && "noperm".equals(args[opti])) {
21915                     dumpState.setOptionEnabled(DumpState.OPTION_SKIP_PERMISSIONS);
21916                 }
21917             } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
21918                 dumpState.setDump(DumpState.DUMP_PROVIDERS);
21919             } else if ("m".equals(cmd) || "messages".equals(cmd)) {
21920                 dumpState.setDump(DumpState.DUMP_MESSAGES);
21921             } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
21922                 dumpState.setDump(DumpState.DUMP_VERIFIERS);
21923             } else if ("i".equals(cmd) || "ifv".equals(cmd)
21924                     || "intent-filter-verifiers".equals(cmd)) {
21925                 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
21926             } else if ("version".equals(cmd)) {
21927                 dumpState.setDump(DumpState.DUMP_VERSION);
21928             } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
21929                 dumpState.setDump(DumpState.DUMP_KEYSETS);
21930             } else if ("installs".equals(cmd)) {
21931                 dumpState.setDump(DumpState.DUMP_INSTALLS);
21932             } else if ("frozen".equals(cmd)) {
21933                 dumpState.setDump(DumpState.DUMP_FROZEN);
21934             } else if ("volumes".equals(cmd)) {
21935                 dumpState.setDump(DumpState.DUMP_VOLUMES);
21936             } else if ("dexopt".equals(cmd)) {
21937                 dumpState.setDump(DumpState.DUMP_DEXOPT);
21938             } else if ("compiler-stats".equals(cmd)) {
21939                 dumpState.setDump(DumpState.DUMP_COMPILER_STATS);
21940             } else if ("changes".equals(cmd)) {
21941                 dumpState.setDump(DumpState.DUMP_CHANGES);
21942             } else if ("service-permissions".equals(cmd)) {
21943                 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS);
21944             } else if ("write".equals(cmd)) {
21945                 synchronized (mPackages) {
21946                     mSettings.writeLPr();
21947                     pw.println("Settings written.");
21948                     return;
21949                 }
21950             }
21951         }
21952
21953         if (checkin) {
21954             pw.println("vers,1");
21955         }
21956
21957         // reader
21958         synchronized (mPackages) {
21959             if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
21960                 if (!checkin) {
21961                     if (dumpState.onTitlePrinted())
21962                         pw.println();
21963                     pw.println("Database versions:");
21964                     mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, "  "));
21965                 }
21966             }
21967
21968             if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
21969                 if (!checkin) {
21970                     if (dumpState.onTitlePrinted())
21971                         pw.println();
21972                     pw.println("Verifiers:");
21973                     pw.print("  Required: ");
21974                     pw.print(mRequiredVerifierPackage);
21975                     pw.print(" (uid=");
21976                     pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21977                             UserHandle.USER_SYSTEM));
21978                     pw.println(")");
21979                 } else if (mRequiredVerifierPackage != null) {
21980                     pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
21981                     pw.print(",");
21982                     pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING,
21983                             UserHandle.USER_SYSTEM));
21984                 }
21985             }
21986
21987             if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
21988                     packageName == null) {
21989                 if (mIntentFilterVerifierComponent != null) {
21990                     String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
21991                     if (!checkin) {
21992                         if (dumpState.onTitlePrinted())
21993                             pw.println();
21994                         pw.println("Intent Filter Verifier:");
21995                         pw.print("  Using: ");
21996                         pw.print(verifierPackageName);
21997                         pw.print(" (uid=");
21998                         pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
21999                                 UserHandle.USER_SYSTEM));
22000                         pw.println(")");
22001                     } else if (verifierPackageName != null) {
22002                         pw.print("ifv,"); pw.print(verifierPackageName);
22003                         pw.print(",");
22004                         pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING,
22005                                 UserHandle.USER_SYSTEM));
22006                     }
22007                 } else {
22008                     pw.println();
22009                     pw.println("No Intent Filter Verifier available!");
22010                 }
22011             }
22012
22013             if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
22014                 boolean printedHeader = false;
22015                 final Iterator<String> it = mSharedLibraries.keySet().iterator();
22016                 while (it.hasNext()) {
22017                     String libName = it.next();
22018                     LongSparseArray<SharedLibraryInfo> versionedLib
22019                             = mSharedLibraries.get(libName);
22020                     if (versionedLib == null) {
22021                         continue;
22022                     }
22023                     final int versionCount = versionedLib.size();
22024                     for (int i = 0; i < versionCount; i++) {
22025                         SharedLibraryInfo libraryInfo = versionedLib.valueAt(i);
22026                         if (!checkin) {
22027                             if (!printedHeader) {
22028                                 if (dumpState.onTitlePrinted())
22029                                     pw.println();
22030                                 pw.println("Libraries:");
22031                                 printedHeader = true;
22032                             }
22033                             pw.print("  ");
22034                         } else {
22035                             pw.print("lib,");
22036                         }
22037                         pw.print(libraryInfo.getName());
22038                         if (libraryInfo.isStatic()) {
22039                             pw.print(" version=" + libraryInfo.getLongVersion());
22040                         }
22041                         if (!checkin) {
22042                             pw.print(" -> ");
22043                         }
22044                         if (libraryInfo.getPath() != null) {
22045                             pw.print(" (jar) ");
22046                             pw.print(libraryInfo.getPath());
22047                         } else {
22048                             pw.print(" (apk) ");
22049                             pw.print(libraryInfo.getPackageName());
22050                         }
22051                         pw.println();
22052                     }
22053                 }
22054             }
22055
22056             if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
22057                 if (dumpState.onTitlePrinted())
22058                     pw.println();
22059                 if (!checkin) {
22060                     pw.println("Features:");
22061                 }
22062
22063                 synchronized (mAvailableFeatures) {
22064                     for (FeatureInfo feat : mAvailableFeatures.values()) {
22065                         if (checkin) {
22066                             pw.print("feat,");
22067                             pw.print(feat.name);
22068                             pw.print(",");
22069                             pw.println(feat.version);
22070                         } else {
22071                             pw.print("  ");
22072                             pw.print(feat.name);
22073                             if (feat.version > 0) {
22074                                 pw.print(" version=");
22075                                 pw.print(feat.version);
22076                             }
22077                             pw.println();
22078                         }
22079                     }
22080                 }
22081             }
22082
22083             if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) {
22084                 mComponentResolver.dumpActivityResolvers(pw, dumpState, packageName);
22085             }
22086             if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) {
22087                 mComponentResolver.dumpReceiverResolvers(pw, dumpState, packageName);
22088             }
22089             if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) {
22090                 mComponentResolver.dumpServiceResolvers(pw, dumpState, packageName);
22091             }
22092             if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) {
22093                 mComponentResolver.dumpProviderResolvers(pw, dumpState, packageName);
22094             }
22095
22096             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
22097                 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
22098                     PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
22099                     int user = mSettings.mPreferredActivities.keyAt(i);
22100                     if (pir.dump(pw,
22101                             dumpState.getTitlePrinted()
22102                                 ? "\nPreferred Activities User " + user + ":"
22103                                 : "Preferred Activities User " + user + ":", "  ",
22104                             packageName, true, false)) {
22105                         dumpState.setTitlePrinted(true);
22106                     }
22107                 }
22108             }
22109
22110             if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
22111                 pw.flush();
22112                 FileOutputStream fout = new FileOutputStream(fd);
22113                 BufferedOutputStream str = new BufferedOutputStream(fout);
22114                 XmlSerializer serializer = new FastXmlSerializer();
22115                 try {
22116                     serializer.setOutput(str, StandardCharsets.UTF_8.name());
22117                     serializer.startDocument(null, true);
22118                     serializer.setFeature(
22119                             "http://xmlpull.org/v1/doc/features.html#indent-output", true);
22120                     mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
22121                     serializer.endDocument();
22122                     serializer.flush();
22123                 } catch (IllegalArgumentException e) {
22124                     pw.println("Failed writing: " + e);
22125                 } catch (IllegalStateException e) {
22126                     pw.println("Failed writing: " + e);
22127                 } catch (IOException e) {
22128                     pw.println("Failed writing: " + e);
22129                 }
22130             }
22131
22132             if (!checkin
22133                     && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)
22134                     && packageName == null) {
22135                 pw.println();
22136                 int count = mSettings.mPackages.size();
22137                 if (count == 0) {
22138                     pw.println("No applications!");
22139                     pw.println();
22140                 } else {
22141                     final String prefix = "  ";
22142                     Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
22143                     if (allPackageSettings.size() == 0) {
22144                         pw.println("No domain preferred apps!");
22145                         pw.println();
22146                     } else {
22147                         pw.println("App verification status:");
22148                         pw.println();
22149                         count = 0;
22150                         for (PackageSetting ps : allPackageSettings) {
22151                             IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
22152                             if (ivi == null || ivi.getPackageName() == null) continue;
22153                             pw.println(prefix + "Package: " + ivi.getPackageName());
22154                             pw.println(prefix + "Domains: " + ivi.getDomainsString());
22155                             pw.println(prefix + "Status:  " + ivi.getStatusString());
22156                             pw.println();
22157                             count++;
22158                         }
22159                         if (count == 0) {
22160                             pw.println(prefix + "No app verification established.");
22161                             pw.println();
22162                         }
22163                         for (int userId : sUserManager.getUserIds()) {
22164                             pw.println("App linkages for user " + userId + ":");
22165                             pw.println();
22166                             count = 0;
22167                             for (PackageSetting ps : allPackageSettings) {
22168                                 final long status = ps.getDomainVerificationStatusForUser(userId);
22169                                 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED
22170                                         && !DEBUG_DOMAIN_VERIFICATION) {
22171                                     continue;
22172                                 }
22173                                 pw.println(prefix + "Package: " + ps.name);
22174                                 pw.println(prefix + "Domains: " + dumpDomainString(ps.name));
22175                                 String statusStr = IntentFilterVerificationInfo.
22176                                         getStatusStringFromValue(status);
22177                                 pw.println(prefix + "Status:  " + statusStr);
22178                                 pw.println();
22179                                 count++;
22180                             }
22181                             if (count == 0) {
22182                                 pw.println(prefix + "No configured app linkages.");
22183                                 pw.println();
22184                             }
22185                         }
22186                     }
22187                 }
22188             }
22189
22190             if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
22191                 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState);
22192             }
22193
22194             if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
22195                 mComponentResolver.dumpContentProviders(pw, dumpState, packageName);
22196             }
22197
22198             if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
22199                 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
22200             }
22201
22202             if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
22203                 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin);
22204             }
22205
22206             if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
22207                 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin);
22208             }
22209
22210             if (dumpState.isDumping(DumpState.DUMP_CHANGES)) {
22211                 if (dumpState.onTitlePrinted()) pw.println();
22212                 pw.println("Package Changes:");
22213                 pw.print("  Sequence number="); pw.println(mChangedPackagesSequenceNumber);
22214                 final int K = mChangedPackages.size();
22215                 for (int i = 0; i < K; i++) {
22216                     final SparseArray<String> changes = mChangedPackages.valueAt(i);
22217                     pw.print("  User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":");
22218                     final int N = changes.size();
22219                     if (N == 0) {
22220                         pw.print("    "); pw.println("No packages changed");
22221                     } else {
22222                         for (int j = 0; j < N; j++) {
22223                             final String pkgName = changes.valueAt(j);
22224                             final int sequenceNumber = changes.keyAt(j);
22225                             pw.print("    ");
22226                             pw.print("seq=");
22227                             pw.print(sequenceNumber);
22228                             pw.print(", package=");
22229                             pw.println(pkgName);
22230                         }
22231                     }
22232                 }
22233             }
22234
22235             if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) {
22236                 // XXX should handle packageName != null by dumping only install data that
22237                 // the given package is involved with.
22238                 if (dumpState.onTitlePrinted()) pw.println();
22239
22240                 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22241                 ipw.println();
22242                 ipw.println("Frozen packages:");
22243                 ipw.increaseIndent();
22244                 if (mFrozenPackages.size() == 0) {
22245                     ipw.println("(none)");
22246                 } else {
22247                     for (int i = 0; i < mFrozenPackages.size(); i++) {
22248                         ipw.println(mFrozenPackages.valueAt(i));
22249                     }
22250                 }
22251                 ipw.decreaseIndent();
22252             }
22253
22254             if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) {
22255                 if (dumpState.onTitlePrinted()) pw.println();
22256
22257                 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ", 120);
22258                 ipw.println();
22259                 ipw.println("Loaded volumes:");
22260                 ipw.increaseIndent();
22261                 if (mLoadedVolumes.size() == 0) {
22262                     ipw.println("(none)");
22263                 } else {
22264                     for (int i = 0; i < mLoadedVolumes.size(); i++) {
22265                         ipw.println(mLoadedVolumes.valueAt(i));
22266                     }
22267                 }
22268                 ipw.decreaseIndent();
22269             }
22270
22271             if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS)
22272                     && packageName == null) {
22273                 mComponentResolver.dumpServicePermissions(pw, dumpState, packageName);
22274             }
22275
22276             if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) {
22277                 if (dumpState.onTitlePrinted()) pw.println();
22278                 dumpDexoptStateLPr(pw, packageName);
22279             }
22280
22281             if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) {
22282                 if (dumpState.onTitlePrinted()) pw.println();
22283                 dumpCompilerStatsLPr(pw, packageName);
22284             }
22285
22286             if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
22287                 if (dumpState.onTitlePrinted()) pw.println();
22288                 mSettings.dumpReadMessagesLPr(pw, dumpState);
22289
22290                 pw.println();
22291                 pw.println("Package warning messages:");
22292                 dumpCriticalInfo(pw, null);
22293             }
22294
22295             if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
22296                 dumpCriticalInfo(pw, "msg,");
22297             }
22298         }
22299
22300         // PackageInstaller should be called outside of mPackages lock
22301         if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
22302             // XXX should handle packageName != null by dumping only install data that
22303             // the given package is involved with.
22304             if (dumpState.onTitlePrinted()) pw.println();
22305             mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
22306         }
22307
22308         if (!checkin && dumpState.isDumping(DumpState.DUMP_APEX)) {
22309             mApexManager.dump(pw, packageName);
22310         }
22311     }
22312
22313     //TODO: b/111402650
22314     private void disableSkuSpecificApps() {
22315         String apkList[] = mContext.getResources().getStringArray(
22316                 R.array.config_disableApksUnlessMatchedSku_apk_list);
22317         String skuArray[] = mContext.getResources().getStringArray(
22318                 R.array.config_disableApkUnlessMatchedSku_skus_list);
22319         if (ArrayUtils.isEmpty(apkList)) {
22320            return;
22321         }
22322         String sku = SystemProperties.get("ro.boot.hardware.sku");
22323         if (!TextUtils.isEmpty(sku) && ArrayUtils.contains(skuArray, sku)) {
22324             return;
22325         }
22326         for (String packageName : apkList) {
22327             setSystemAppHiddenUntilInstalled(packageName, true);
22328             for (UserInfo user : sUserManager.getUsers(false)) {
22329                 setSystemAppInstallState(packageName, false, user.id);
22330             }
22331         }
22332     }
22333
22334     private void dumpProto(FileDescriptor fd) {
22335         final ProtoOutputStream proto = new ProtoOutputStream(fd);
22336
22337         synchronized (mPackages) {
22338             final long requiredVerifierPackageToken =
22339                     proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE);
22340             proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage);
22341             proto.write(
22342                     PackageServiceDumpProto.PackageShortProto.UID,
22343                     getPackageUid(
22344                             mRequiredVerifierPackage,
22345                             MATCH_DEBUG_TRIAGED_MISSING,
22346                             UserHandle.USER_SYSTEM));
22347             proto.end(requiredVerifierPackageToken);
22348
22349             if (mIntentFilterVerifierComponent != null) {
22350                 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
22351                 final long verifierPackageToken =
22352                         proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE);
22353                 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName);
22354                 proto.write(
22355                         PackageServiceDumpProto.PackageShortProto.UID,
22356                         getPackageUid(
22357                                 verifierPackageName,
22358                                 MATCH_DEBUG_TRIAGED_MISSING,
22359                                 UserHandle.USER_SYSTEM));
22360                 proto.end(verifierPackageToken);
22361             }
22362
22363             dumpSharedLibrariesProto(proto);
22364             dumpFeaturesProto(proto);
22365             mSettings.dumpPackagesProto(proto);
22366             mSettings.dumpSharedUsersProto(proto);
22367             dumpCriticalInfo(proto);
22368         }
22369         proto.flush();
22370     }
22371
22372     private void dumpFeaturesProto(ProtoOutputStream proto) {
22373         synchronized (mAvailableFeatures) {
22374             final int count = mAvailableFeatures.size();
22375             for (int i = 0; i < count; i++) {
22376                 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES);
22377             }
22378         }
22379     }
22380
22381     private void dumpSharedLibrariesProto(ProtoOutputStream proto) {
22382         final int count = mSharedLibraries.size();
22383         for (int i = 0; i < count; i++) {
22384             final String libName = mSharedLibraries.keyAt(i);
22385             LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.get(libName);
22386             if (versionedLib == null) {
22387                 continue;
22388             }
22389             final int versionCount = versionedLib.size();
22390             for (int j = 0; j < versionCount; j++) {
22391                 final SharedLibraryInfo libraryInfo = versionedLib.valueAt(j);
22392                 final long sharedLibraryToken =
22393                         proto.start(PackageServiceDumpProto.SHARED_LIBRARIES);
22394                 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libraryInfo.getName());
22395                 final boolean isJar = (libraryInfo.getPath() != null);
22396                 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar);
22397                 if (isJar) {
22398                     proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH,
22399                             libraryInfo.getPath());
22400                 } else {
22401                     proto.write(PackageServiceDumpProto.SharedLibraryProto.APK,
22402                             libraryInfo.getPackageName());
22403                 }
22404                 proto.end(sharedLibraryToken);
22405             }
22406         }
22407     }
22408
22409     @GuardedBy("mPackages")
22410     @SuppressWarnings("resource")
22411     private void dumpDexoptStateLPr(PrintWriter pw, String packageName) {
22412         final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
22413         ipw.println();
22414         ipw.println("Dexopt state:");
22415         ipw.increaseIndent();
22416         Collection<PackageParser.Package> packages;
22417         if (packageName != null) {
22418             PackageParser.Package targetPackage = mPackages.get(packageName);
22419             if (targetPackage != null) {
22420                 packages = Collections.singletonList(targetPackage);
22421             } else {
22422                 ipw.println("Unable to find package: " + packageName);
22423                 return;
22424             }
22425         } else {
22426             packages = mPackages.values();
22427         }
22428
22429         for (PackageParser.Package pkg : packages) {
22430             ipw.println("[" + pkg.packageName + "]");
22431             ipw.increaseIndent();
22432             mPackageDexOptimizer.dumpDexoptState(ipw, pkg,
22433                     mDexManager.getPackageUseInfoOrDefault(pkg.packageName));
22434             ipw.decreaseIndent();
22435         }
22436     }
22437
22438     @GuardedBy("mPackages")
22439     @SuppressWarnings("resource")
22440     private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) {
22441         final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, "  ");
22442         ipw.println();
22443         ipw.println("Compiler stats:");
22444         ipw.increaseIndent();
22445         Collection<PackageParser.Package> packages;
22446         if (packageName != null) {
22447             PackageParser.Package targetPackage = mPackages.get(packageName);
22448             if (targetPackage != null) {
22449                 packages = Collections.singletonList(targetPackage);
22450             } else {
22451                 ipw.println("Unable to find package: " + packageName);
22452                 return;
22453             }
22454         } else {
22455             packages = mPackages.values();
22456         }
22457
22458         for (PackageParser.Package pkg : packages) {
22459             ipw.println("[" + pkg.packageName + "]");
22460             ipw.increaseIndent();
22461
22462             CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName);
22463             if (stats == null) {
22464                 ipw.println("(No recorded stats)");
22465             } else {
22466                 stats.dump(ipw);
22467             }
22468             ipw.decreaseIndent();
22469         }
22470     }
22471
22472     private String dumpDomainString(String packageName) {
22473         List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName)
22474                 .getList();
22475         List<IntentFilter> filters = getAllIntentFilters(packageName).getList();
22476
22477         ArraySet<String> result = new ArraySet<>();
22478         if (iviList.size() > 0) {
22479             for (IntentFilterVerificationInfo ivi : iviList) {
22480                 result.addAll(ivi.getDomains());
22481             }
22482         }
22483         if (filters != null && filters.size() > 0) {
22484             for (IntentFilter filter : filters) {
22485                 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
22486                         && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
22487                                 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
22488                     result.addAll(filter.getHostsList());
22489                 }
22490             }
22491         }
22492
22493         StringBuilder sb = new StringBuilder(result.size() * 16);
22494         for (String domain : result) {
22495             if (sb.length() > 0) sb.append(" ");
22496             sb.append(domain);
22497         }
22498         return sb.toString();
22499     }
22500
22501     // ------- apps on sdcard specific code -------
22502     static final boolean DEBUG_SD_INSTALL = false;
22503
22504     private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
22505
22506     private static final String SD_ENCRYPTION_ALGORITHM = "AES";
22507
22508     private boolean mMediaMounted = false;
22509
22510     static String getEncryptKey() {
22511         try {
22512             String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
22513                     SD_ENCRYPTION_KEYSTORE_NAME);
22514             if (sdEncKey == null) {
22515                 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
22516                         SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
22517                 if (sdEncKey == null) {
22518                     Slog.e(TAG, "Failed to create encryption keys");
22519                     return null;
22520                 }
22521             }
22522             return sdEncKey;
22523         } catch (NoSuchAlgorithmException nsae) {
22524             Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
22525             return null;
22526         } catch (IOException ioe) {
22527             Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
22528             return null;
22529         }
22530     }
22531
22532     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22533             ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
22534         final int size = infos.size();
22535         final String[] packageNames = new String[size];
22536         final int[] packageUids = new int[size];
22537         for (int i = 0; i < size; i++) {
22538             final ApplicationInfo info = infos.get(i);
22539             packageNames[i] = info.packageName;
22540             packageUids[i] = info.uid;
22541         }
22542         sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
22543                 finishedReceiver);
22544     }
22545
22546     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22547             ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22548         sendResourcesChangedBroadcast(mediaStatus, replacing,
22549                 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
22550     }
22551
22552     private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
22553             String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
22554         int size = pkgList.length;
22555         if (size > 0) {
22556             // Send broadcasts here
22557             Bundle extras = new Bundle();
22558             extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
22559             if (uidArr != null) {
22560                 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
22561             }
22562             if (replacing) {
22563                 extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
22564             }
22565             String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
22566                     : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
22567             sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null);
22568         }
22569     }
22570
22571     private void loadPrivatePackages(final VolumeInfo vol) {
22572         mHandler.post(() -> loadPrivatePackagesInner(vol));
22573     }
22574
22575     private void loadPrivatePackagesInner(VolumeInfo vol) {
22576         final String volumeUuid = vol.fsUuid;
22577         if (TextUtils.isEmpty(volumeUuid)) {
22578             Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
22579             return;
22580         }
22581
22582         final ArrayList<PackageFreezer> freezers = new ArrayList<>();
22583         final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
22584         final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
22585
22586         final VersionInfo ver;
22587         final List<PackageSetting> packages;
22588         synchronized (mPackages) {
22589             ver = mSettings.findOrCreateVersion(volumeUuid);
22590             packages = mSettings.getVolumePackagesLPr(volumeUuid);
22591         }
22592
22593         for (PackageSetting ps : packages) {
22594             freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
22595             synchronized (mInstallLock) {
22596                 final PackageParser.Package pkg;
22597                 try {
22598                     pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
22599                     loaded.add(pkg.applicationInfo);
22600
22601                 } catch (PackageManagerException e) {
22602                     Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
22603                 }
22604
22605                 if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
22606                     clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE | FLAG_STORAGE_CE
22607                             | FLAG_STORAGE_EXTERNAL | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
22608                 }
22609             }
22610         }
22611
22612         // Reconcile app data for all started/unlocked users
22613         final StorageManager sm = mContext.getSystemService(StorageManager.class);
22614         final UserManager um = mContext.getSystemService(UserManager.class);
22615         UserManagerInternal umInternal = getUserManagerInternal();
22616         for (UserInfo user : um.getUsers()) {
22617             final int flags;
22618             if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22619                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22620             } else if (umInternal.isUserRunning(user.id)) {
22621                 flags = StorageManager.FLAG_STORAGE_DE;
22622             } else {
22623                 continue;
22624             }
22625
22626             try {
22627                 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
22628                 synchronized (mInstallLock) {
22629                     reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */);
22630                 }
22631             } catch (IllegalStateException e) {
22632                 // Device was probably ejected, and we'll process that event momentarily
22633                 Slog.w(TAG, "Failed to prepare storage: " + e);
22634             }
22635         }
22636
22637         synchronized (mPackages) {
22638             final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
22639             if (sdkUpdated) {
22640                 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to "
22641                         + mSdkVersion + "; regranting permissions for " + volumeUuid);
22642             }
22643             mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(),
22644                     mPermissionCallback);
22645
22646             // Yay, everything is now upgraded
22647             ver.forceCurrent();
22648
22649             mSettings.writeLPr();
22650         }
22651
22652         for (PackageFreezer freezer : freezers) {
22653             freezer.close();
22654         }
22655
22656         if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded);
22657         sendResourcesChangedBroadcast(true, false, loaded, null);
22658         mLoadedVolumes.add(vol.getId());
22659     }
22660
22661     private void unloadPrivatePackages(final VolumeInfo vol) {
22662         mHandler.post(() -> unloadPrivatePackagesInner(vol));
22663     }
22664
22665     private void unloadPrivatePackagesInner(VolumeInfo vol) {
22666         final String volumeUuid = vol.fsUuid;
22667         if (TextUtils.isEmpty(volumeUuid)) {
22668             Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring");
22669             return;
22670         }
22671
22672         final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
22673         synchronized (mInstallLock) {
22674         synchronized (mPackages) {
22675             final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid);
22676             for (PackageSetting ps : packages) {
22677                 if (ps.pkg == null) continue;
22678
22679                 final ApplicationInfo info = ps.pkg.applicationInfo;
22680                 final int deleteFlags = PackageManager.DELETE_KEEP_DATA;
22681                 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this);
22682
22683                 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags,
22684                         "unloadPrivatePackagesInner")) {
22685                     if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo,
22686                             false, null)) {
22687                         unloaded.add(info);
22688                     } else {
22689                         Slog.w(TAG, "Failed to unload " + ps.codePath);
22690                     }
22691                 }
22692
22693                 // Try very hard to release any references to this package
22694                 // so we don't risk the system server being killed due to
22695                 // open FDs
22696                 AttributeCache.instance().removePackage(ps.name);
22697             }
22698
22699             mSettings.writeLPr();
22700         }
22701         }
22702
22703         if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded);
22704         sendResourcesChangedBroadcast(false, false, unloaded, null);
22705         mLoadedVolumes.remove(vol.getId());
22706
22707         // Try very hard to release any references to this path so we don't risk
22708         // the system server being killed due to open FDs
22709         ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath());
22710
22711         for (int i = 0; i < 3; i++) {
22712             System.gc();
22713             System.runFinalization();
22714         }
22715     }
22716
22717     private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId)
22718             throws PackageManagerException {
22719         synchronized (mPackages) {
22720             // Normalize package name to handle renamed packages
22721             packageName = normalizePackageNameLPr(packageName);
22722
22723             final PackageSetting ps = mSettings.mPackages.get(packageName);
22724             if (ps == null) {
22725                 throw new PackageManagerException("Package " + packageName + " is unknown");
22726             } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) {
22727                 throw new PackageManagerException(
22728                         "Package " + packageName + " found on unknown volume " + volumeUuid
22729                                 + "; expected volume " + ps.volumeUuid);
22730             } else if (!ps.getInstalled(userId)) {
22731                 throw new PackageManagerException(
22732                         "Package " + packageName + " not installed for user " + userId);
22733             }
22734         }
22735     }
22736
22737     private List<String> collectAbsoluteCodePaths() {
22738         synchronized (mPackages) {
22739             List<String> codePaths = new ArrayList<>();
22740             final int packageCount = mSettings.mPackages.size();
22741             for (int i = 0; i < packageCount; i++) {
22742                 final PackageSetting ps = mSettings.mPackages.valueAt(i);
22743                 codePaths.add(ps.codePath.getAbsolutePath());
22744             }
22745             return codePaths;
22746         }
22747     }
22748
22749     /**
22750      * Examine all apps present on given mounted volume, and destroy apps that
22751      * aren't expected, either due to uninstallation or reinstallation on
22752      * another volume.
22753      */
22754     private void reconcileApps(String volumeUuid) {
22755         List<String> absoluteCodePaths = collectAbsoluteCodePaths();
22756         List<File> filesToDelete = null;
22757
22758         final File[] files = FileUtils.listFilesOrEmpty(
22759                 Environment.getDataAppDirectory(volumeUuid));
22760         for (File file : files) {
22761             final boolean isPackage = (isApkFile(file) || file.isDirectory())
22762                     && !PackageInstallerService.isStageName(file.getName());
22763             if (!isPackage) {
22764                 // Ignore entries which are not packages
22765                 continue;
22766             }
22767
22768             String absolutePath = file.getAbsolutePath();
22769
22770             boolean pathValid = false;
22771             final int absoluteCodePathCount = absoluteCodePaths.size();
22772             for (int i = 0; i < absoluteCodePathCount; i++) {
22773                 String absoluteCodePath = absoluteCodePaths.get(i);
22774                 if (absolutePath.startsWith(absoluteCodePath)) {
22775                     pathValid = true;
22776                     break;
22777                 }
22778             }
22779
22780             if (!pathValid) {
22781                 if (filesToDelete == null) {
22782                     filesToDelete = new ArrayList<>();
22783                 }
22784                 filesToDelete.add(file);
22785             }
22786         }
22787
22788         if (filesToDelete != null) {
22789             final int fileToDeleteCount = filesToDelete.size();
22790             for (int i = 0; i < fileToDeleteCount; i++) {
22791                 File fileToDelete = filesToDelete.get(i);
22792                 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete);
22793                 synchronized (mInstallLock) {
22794                     removeCodePathLI(fileToDelete);
22795                 }
22796             }
22797         }
22798     }
22799
22800     /**
22801      * Reconcile all app data for the given user.
22802      * <p>
22803      * Verifies that directories exist and that ownership and labeling is
22804      * correct for all installed apps on all mounted volumes.
22805      */
22806     void reconcileAppsData(int userId, int flags, boolean migrateAppsData) {
22807         final StorageManager storage = mContext.getSystemService(StorageManager.class);
22808         for (VolumeInfo vol : storage.getWritablePrivateVolumes()) {
22809             final String volumeUuid = vol.getFsUuid();
22810             synchronized (mInstallLock) {
22811                 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData);
22812             }
22813         }
22814     }
22815
22816     @GuardedBy("mInstallLock")
22817     private void reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22818             boolean migrateAppData) {
22819         reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */);
22820     }
22821
22822     /**
22823      * Reconcile all app data on given mounted volume.
22824      * <p>
22825      * Destroys app data that isn't expected, either due to uninstallation or
22826      * reinstallation on another volume.
22827      * <p>
22828      * Verifies that directories exist and that ownership and labeling is
22829      * correct for all installed apps.
22830      * @return list of skipped non-core packages (if {@code onlyCoreApps} is true)
22831      */
22832     @GuardedBy("mInstallLock")
22833     private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags,
22834             boolean migrateAppData, boolean onlyCoreApps) {
22835         Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x"
22836                 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData);
22837         List<String> result = onlyCoreApps ? new ArrayList<>() : null;
22838
22839         final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId);
22840         final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId);
22841
22842         // First look for stale data that doesn't belong, and check if things
22843         // have changed since we did our last restorecon
22844         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
22845             if (StorageManager.isFileEncryptedNativeOrEmulated()
22846                     && !StorageManager.isUserKeyUnlocked(userId)) {
22847                 throw new RuntimeException(
22848                         "Yikes, someone asked us to reconcile CE storage while " + userId
22849                                 + " was still locked; this would have caused massive data loss!");
22850             }
22851
22852             final File[] files = FileUtils.listFilesOrEmpty(ceDir);
22853             for (File file : files) {
22854                 final String packageName = file.getName();
22855                 try {
22856                     assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22857                 } catch (PackageManagerException e) {
22858                     logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22859                     try {
22860                         mInstaller.destroyAppData(volumeUuid, packageName, userId,
22861                                 StorageManager.FLAG_STORAGE_CE, 0);
22862                     } catch (InstallerException e2) {
22863                         logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22864                     }
22865                 }
22866             }
22867         }
22868         if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) {
22869             final File[] files = FileUtils.listFilesOrEmpty(deDir);
22870             for (File file : files) {
22871                 final String packageName = file.getName();
22872                 try {
22873                     assertPackageKnownAndInstalled(volumeUuid, packageName, userId);
22874                 } catch (PackageManagerException e) {
22875                     logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e);
22876                     try {
22877                         mInstaller.destroyAppData(volumeUuid, packageName, userId,
22878                                 StorageManager.FLAG_STORAGE_DE, 0);
22879                     } catch (InstallerException e2) {
22880                         logCriticalInfo(Log.WARN, "Failed to destroy: " + e2);
22881                     }
22882                 }
22883             }
22884         }
22885
22886         // Ensure that data directories are ready to roll for all packages
22887         // installed for this volume and user
22888         final List<PackageSetting> packages;
22889         synchronized (mPackages) {
22890             packages = mSettings.getVolumePackagesLPr(volumeUuid);
22891         }
22892         int preparedCount = 0;
22893         for (PackageSetting ps : packages) {
22894             final String packageName = ps.name;
22895             if (ps.pkg == null) {
22896                 Slog.w(TAG, "Odd, missing scanned package " + packageName);
22897                 // TODO: might be due to legacy ASEC apps; we should circle back
22898                 // and reconcile again once they're scanned
22899                 continue;
22900             }
22901             // Skip non-core apps if requested
22902             if (onlyCoreApps && !ps.pkg.coreApp) {
22903                 result.add(packageName);
22904                 continue;
22905             }
22906
22907             if (ps.getInstalled(userId)) {
22908                 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData);
22909                 preparedCount++;
22910             }
22911         }
22912
22913         Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages");
22914         return result;
22915     }
22916
22917     /**
22918      * Prepare app data for the given app just after it was installed or
22919      * upgraded. This method carefully only touches users that it's installed
22920      * for, and it forces a restorecon to handle any seinfo changes.
22921      * <p>
22922      * Verifies that directories exist and that ownership and labeling is
22923      * correct for all installed apps. If there is an ownership mismatch, it
22924      * will try recovering system apps by wiping data; third-party app data is
22925      * left intact.
22926      * <p>
22927      * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em>
22928      */
22929     private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) {
22930         final PackageSetting ps;
22931         synchronized (mPackages) {
22932             ps = mSettings.mPackages.get(pkg.packageName);
22933             mSettings.writeKernelMappingLPr(ps);
22934         }
22935
22936         final UserManager um = mContext.getSystemService(UserManager.class);
22937         UserManagerInternal umInternal = getUserManagerInternal();
22938         for (UserInfo user : um.getUsers()) {
22939             final int flags;
22940             if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
22941                 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
22942             } else if (umInternal.isUserRunning(user.id)) {
22943                 flags = StorageManager.FLAG_STORAGE_DE;
22944             } else {
22945                 continue;
22946             }
22947
22948             if (ps.getInstalled(user.id)) {
22949                 // TODO: when user data is locked, mark that we're still dirty
22950                 prepareAppDataLIF(pkg, user.id, flags);
22951             }
22952         }
22953     }
22954
22955     /**
22956      * Prepare app data for the given app.
22957      * <p>
22958      * Verifies that directories exist and that ownership and labeling is
22959      * correct for all installed apps. If there is an ownership mismatch, this
22960      * will try recovering system apps by wiping data; third-party app data is
22961      * left intact.
22962      */
22963     private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) {
22964         if (pkg == null) {
22965             Slog.wtf(TAG, "Package was null!", new Throwable());
22966             return;
22967         }
22968         prepareAppDataLeafLIF(pkg, userId, flags);
22969         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
22970         for (int i = 0; i < childCount; i++) {
22971             prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags);
22972         }
22973     }
22974
22975     private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags,
22976             boolean maybeMigrateAppData) {
22977         prepareAppDataLIF(pkg, userId, flags);
22978
22979         if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) {
22980             // We may have just shuffled around app data directories, so
22981             // prepare them one more time
22982             prepareAppDataLIF(pkg, userId, flags);
22983         }
22984     }
22985
22986     private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) {
22987         if (DEBUG_APP_DATA) {
22988             Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x"
22989                     + Integer.toHexString(flags));
22990         }
22991
22992         final PackageSetting ps;
22993         synchronized (mPackages) {
22994             ps = mSettings.mPackages.get(pkg.packageName);
22995         }
22996         final String volumeUuid = pkg.volumeUuid;
22997         final String packageName = pkg.packageName;
22998
22999         ApplicationInfo app = (ps == null)
23000                 ? pkg.applicationInfo
23001                 : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId);
23002         if (app == null) {
23003             app = pkg.applicationInfo;
23004         }
23005
23006         final int appId = UserHandle.getAppId(app.uid);
23007
23008         Preconditions.checkNotNull(app.seInfo);
23009
23010         final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : "");
23011         long ceDataInode = -1;
23012         try {
23013             ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23014                     appId, seInfo, app.targetSdkVersion);
23015         } catch (InstallerException e) {
23016             if (app.isSystemApp()) {
23017                 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName
23018                         + ", but trying to recover: " + e);
23019                 destroyAppDataLeafLIF(pkg, userId, flags);
23020                 try {
23021                     ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
23022                             appId, seInfo, app.targetSdkVersion);
23023                     logCriticalInfo(Log.DEBUG, "Recovery succeeded!");
23024                 } catch (InstallerException e2) {
23025                     logCriticalInfo(Log.DEBUG, "Recovery failed!");
23026                 }
23027             } else {
23028                 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e);
23029             }
23030         }
23031         // Prepare the application profiles only for upgrades and first boot (so that we don't
23032         // repeat the same operation at each boot).
23033         // We only have to cover the upgrade and first boot here because for app installs we
23034         // prepare the profiles before invoking dexopt (in installPackageLI).
23035         //
23036         // We also have to cover non system users because we do not call the usual install package
23037         // methods for them.
23038         //
23039         // NOTE: in order to speed up first boot time we only create the current profile and do not
23040         // update the content of the reference profile. A system image should already be configured
23041         // with the right profile keys and the profiles for the speed-profile prebuilds should
23042         // already be copied. That's done in #performDexOptUpgrade.
23043         //
23044         // TODO(calin, mathieuc): We should use .dm files for prebuilds profiles instead of
23045         // manually copying them in #performDexOptUpgrade. When we do that we should have a more
23046         // granular check here and only update the existing profiles.
23047         if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) {
23048             mArtManagerService.prepareAppProfiles(pkg, userId,
23049                 /* updateReferenceProfileContent= */ false);
23050         }
23051
23052         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) {
23053             // TODO: mark this structure as dirty so we persist it!
23054             synchronized (mPackages) {
23055                 if (ps != null) {
23056                     ps.setCeDataInode(ceDataInode, userId);
23057                 }
23058             }
23059         }
23060
23061         prepareAppDataContentsLeafLIF(pkg, userId, flags);
23062     }
23063
23064     private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) {
23065         if (pkg == null) {
23066             Slog.wtf(TAG, "Package was null!", new Throwable());
23067             return;
23068         }
23069         prepareAppDataContentsLeafLIF(pkg, userId, flags);
23070         final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0;
23071         for (int i = 0; i < childCount; i++) {
23072             prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags);
23073         }
23074     }
23075
23076     private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) {
23077         final String volumeUuid = pkg.volumeUuid;
23078         final String packageName = pkg.packageName;
23079         final ApplicationInfo app = pkg.applicationInfo;
23080
23081         if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) {
23082             // Create a native library symlink only if we have native libraries
23083             // and if the native libraries are 32 bit libraries. We do not provide
23084             // this symlink for 64 bit libraries.
23085             if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) {
23086                 final String nativeLibPath = app.nativeLibraryDir;
23087                 try {
23088                     mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName,
23089                             nativeLibPath, userId);
23090                 } catch (InstallerException e) {
23091                     Slog.e(TAG, "Failed to link native for " + packageName + ": " + e);
23092                 }
23093             }
23094         }
23095     }
23096
23097     /**
23098      * For system apps on non-FBE devices, this method migrates any existing
23099      * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag
23100      * requested by the app.
23101      */
23102     private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) {
23103         if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated()
23104                 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) {
23105             final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage()
23106                     ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE;
23107             try {
23108                 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId,
23109                         storageTarget);
23110             } catch (InstallerException e) {
23111                 logCriticalInfo(Log.WARN,
23112                         "Failed to migrate " + pkg.packageName + ": " + e.getMessage());
23113             }
23114             return true;
23115         } else {
23116             return false;
23117         }
23118     }
23119
23120     public PackageFreezer freezePackage(String packageName, String killReason) {
23121         return freezePackage(packageName, UserHandle.USER_ALL, killReason);
23122     }
23123
23124     public PackageFreezer freezePackage(String packageName, int userId, String killReason) {
23125         return new PackageFreezer(packageName, userId, killReason);
23126     }
23127
23128     public PackageFreezer freezePackageForInstall(String packageName, int installFlags,
23129             String killReason) {
23130         return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason);
23131     }
23132
23133     public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags,
23134             String killReason) {
23135         if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) {
23136             return new PackageFreezer();
23137         } else {
23138             return freezePackage(packageName, userId, killReason);
23139         }
23140     }
23141
23142     public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags,
23143             String killReason) {
23144         return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason);
23145     }
23146
23147     public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags,
23148             String killReason) {
23149         if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) {
23150             return new PackageFreezer();
23151         } else {
23152             return freezePackage(packageName, userId, killReason);
23153         }
23154     }
23155
23156     /**
23157      * Class that freezes and kills the given package upon creation, and
23158      * unfreezes it upon closing. This is typically used when doing surgery on
23159      * app code/data to prevent the app from running while you're working.
23160      */
23161     private class PackageFreezer implements AutoCloseable {
23162         private final String mPackageName;
23163         private final PackageFreezer[] mChildren;
23164
23165         private final boolean mWeFroze;
23166
23167         private final AtomicBoolean mClosed = new AtomicBoolean();
23168         private final CloseGuard mCloseGuard = CloseGuard.get();
23169
23170         /**
23171          * Create and return a stub freezer that doesn't actually do anything,
23172          * typically used when someone requested
23173          * {@link PackageManager#INSTALL_DONT_KILL_APP} or
23174          * {@link PackageManager#DELETE_DONT_KILL_APP}.
23175          */
23176         public PackageFreezer() {
23177             mPackageName = null;
23178             mChildren = null;
23179             mWeFroze = false;
23180             mCloseGuard.open("close");
23181         }
23182
23183         public PackageFreezer(String packageName, int userId, String killReason) {
23184             synchronized (mPackages) {
23185                 mPackageName = packageName;
23186                 mWeFroze = mFrozenPackages.add(mPackageName);
23187
23188                 final PackageSetting ps = mSettings.mPackages.get(mPackageName);
23189                 if (ps != null) {
23190                     killApplication(ps.name, ps.appId, userId, killReason);
23191                 }
23192
23193                 final PackageParser.Package p = mPackages.get(packageName);
23194                 if (p != null && p.childPackages != null) {
23195                     final int N = p.childPackages.size();
23196                     mChildren = new PackageFreezer[N];
23197                     for (int i = 0; i < N; i++) {
23198                         mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName,
23199                                 userId, killReason);
23200                     }
23201                 } else {
23202                     mChildren = null;
23203                 }
23204             }
23205             mCloseGuard.open("close");
23206         }
23207
23208         @Override
23209         protected void finalize() throws Throwable {
23210             try {
23211                 mCloseGuard.warnIfOpen();
23212                 close();
23213             } finally {
23214                 super.finalize();
23215             }
23216         }
23217
23218         @Override
23219         public void close() {
23220             mCloseGuard.close();
23221             if (mClosed.compareAndSet(false, true)) {
23222                 synchronized (mPackages) {
23223                     if (mWeFroze) {
23224                         mFrozenPackages.remove(mPackageName);
23225                     }
23226
23227                     if (mChildren != null) {
23228                         for (PackageFreezer freezer : mChildren) {
23229                             freezer.close();
23230                         }
23231                     }
23232                 }
23233             }
23234         }
23235     }
23236
23237     /**
23238      * Verify that given package is currently frozen.
23239      */
23240     private void checkPackageFrozen(String packageName) {
23241         synchronized (mPackages) {
23242             if (!mFrozenPackages.contains(packageName)) {
23243                 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable());
23244             }
23245         }
23246     }
23247
23248     @Override
23249     public int movePackage(final String packageName, final String volumeUuid) {
23250         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23251
23252         final int callingUid = Binder.getCallingUid();
23253         final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid));
23254         final int moveId = mNextMoveId.getAndIncrement();
23255         mHandler.post(() -> {
23256             try {
23257                 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user);
23258             } catch (PackageManagerException e) {
23259                 Slog.w(TAG, "Failed to move " + packageName, e);
23260                 mMoveCallbacks.notifyStatusChanged(moveId, e.error);
23261             }
23262         });
23263         return moveId;
23264     }
23265
23266     private void movePackageInternal(final String packageName, final String volumeUuid,
23267             final int moveId, final int callingUid, UserHandle user)
23268                     throws PackageManagerException {
23269         final StorageManager storage = mContext.getSystemService(StorageManager.class);
23270         final PackageManager pm = mContext.getPackageManager();
23271
23272         final String currentVolumeUuid;
23273         final File codeFile;
23274         final String installerPackageName;
23275         final String packageAbiOverride;
23276         final int appId;
23277         final String seinfo;
23278         final String label;
23279         final int targetSdkVersion;
23280         final PackageFreezer freezer;
23281         final int[] installedUserIds;
23282         final boolean isCurrentLocationExternal;
23283
23284         // reader
23285         synchronized (mPackages) {
23286             final PackageParser.Package pkg = mPackages.get(packageName);
23287             final PackageSetting ps = mSettings.mPackages.get(packageName);
23288             if (pkg == null
23289                     || ps == null
23290                     || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) {
23291                 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
23292             }
23293             if (pkg.applicationInfo.isSystemApp()) {
23294                 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
23295                         "Cannot move system application");
23296             }
23297
23298             final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid);
23299             final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean(
23300                     com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
23301             if (isInternalStorage && !allow3rdPartyOnInternal) {
23302                 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL,
23303                         "3rd party apps are not allowed on internal storage");
23304             }
23305
23306             currentVolumeUuid = ps.volumeUuid;
23307
23308             final File probe = new File(pkg.codePath);
23309             final File probeOat = new File(probe, "oat");
23310             if (!probe.isDirectory() || !probeOat.isDirectory()) {
23311                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23312                         "Move only supported for modern cluster style installs");
23313             }
23314
23315             if (Objects.equals(currentVolumeUuid, volumeUuid)) {
23316                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23317                         "Package already moved to " + volumeUuid);
23318             }
23319             if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
23320                 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN,
23321                         "Device admin cannot be moved");
23322             }
23323
23324             if (mFrozenPackages.contains(packageName)) {
23325                 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
23326                         "Failed to move already frozen package");
23327             }
23328
23329             isCurrentLocationExternal = isExternal(pkg);
23330             codeFile = new File(pkg.codePath);
23331             installerPackageName = ps.installerPackageName;
23332             packageAbiOverride = ps.cpuAbiOverrideString;
23333             appId = UserHandle.getAppId(pkg.applicationInfo.uid);
23334             seinfo = pkg.applicationInfo.seInfo;
23335             label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
23336             targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
23337             freezer = freezePackage(packageName, "movePackageInternal");
23338             installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
23339         }
23340
23341         final Bundle extras = new Bundle();
23342         extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
23343         extras.putString(Intent.EXTRA_TITLE, label);
23344         mMoveCallbacks.notifyCreated(moveId, extras);
23345
23346         int installFlags;
23347         final boolean moveCompleteApp;
23348         final File measurePath;
23349
23350         installFlags = INSTALL_INTERNAL;
23351         if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
23352             moveCompleteApp = true;
23353             measurePath = Environment.getDataAppDirectory(volumeUuid);
23354         } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
23355             moveCompleteApp = false;
23356             measurePath = storage.getPrimaryPhysicalVolume().getPath();
23357         } else {
23358             final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
23359             if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
23360                     || !volume.isMountedWritable()) {
23361                 freezer.close();
23362                 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23363                         "Move location not mounted private volume");
23364             }
23365
23366             moveCompleteApp = true;
23367             measurePath = Environment.getDataAppDirectory(volumeUuid);
23368         }
23369
23370         // If we're moving app data around, we need all the users unlocked
23371         if (moveCompleteApp) {
23372             for (int userId : installedUserIds) {
23373                 if (StorageManager.isFileEncryptedNativeOrEmulated()
23374                         && !StorageManager.isUserKeyUnlocked(userId)) {
23375                     throw new PackageManagerException(MOVE_FAILED_LOCKED_USER,
23376                             "User " + userId + " must be unlocked");
23377                 }
23378             }
23379         }
23380
23381         final PackageStats stats = new PackageStats(null, -1);
23382         synchronized (mInstaller) {
23383             for (int userId : installedUserIds) {
23384                 if (!getPackageSizeInfoLI(packageName, userId, stats)) {
23385                     freezer.close();
23386                     throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23387                             "Failed to measure package size");
23388                 }
23389             }
23390         }
23391
23392         if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size "
23393                 + stats.dataSize);
23394
23395         final long startFreeBytes = measurePath.getUsableSpace();
23396         final long sizeBytes;
23397         if (moveCompleteApp) {
23398             sizeBytes = stats.codeSize + stats.dataSize;
23399         } else {
23400             sizeBytes = stats.codeSize;
23401         }
23402
23403         if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
23404             freezer.close();
23405             throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
23406                     "Not enough free space to move");
23407         }
23408
23409         mMoveCallbacks.notifyStatusChanged(moveId, 10);
23410
23411         final CountDownLatch installedLatch = new CountDownLatch(1);
23412         final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
23413             @Override
23414             public void onUserActionRequired(Intent intent) throws RemoteException {
23415                 throw new IllegalStateException();
23416             }
23417
23418             @Override
23419             public void onPackageInstalled(String basePackageName, int returnCode, String msg,
23420                     Bundle extras) throws RemoteException {
23421                 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: "
23422                         + PackageManager.installStatusToString(returnCode, msg));
23423
23424                 installedLatch.countDown();
23425                 freezer.close();
23426
23427                 final int status = PackageManager.installStatusToPublicStatus(returnCode);
23428                 switch (status) {
23429                     case PackageInstaller.STATUS_SUCCESS:
23430                         mMoveCallbacks.notifyStatusChanged(moveId,
23431                                 PackageManager.MOVE_SUCCEEDED);
23432                         logAppMovedStorage(packageName, isCurrentLocationExternal);
23433                         break;
23434                     case PackageInstaller.STATUS_FAILURE_STORAGE:
23435                         mMoveCallbacks.notifyStatusChanged(moveId,
23436                                 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
23437                         break;
23438                     default:
23439                         mMoveCallbacks.notifyStatusChanged(moveId,
23440                                 PackageManager.MOVE_FAILED_INTERNAL_ERROR);
23441                         break;
23442                 }
23443             }
23444         };
23445
23446         final MoveInfo move;
23447         if (moveCompleteApp) {
23448             // Kick off a thread to report progress estimates
23449             new Thread(() -> {
23450                 while (true) {
23451                     try {
23452                         if (installedLatch.await(1, TimeUnit.SECONDS)) {
23453                             break;
23454                         }
23455                     } catch (InterruptedException ignored) {
23456                     }
23457
23458                     final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace();
23459                     final int progress = 10 + (int) MathUtils.constrain(
23460                             ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
23461                     mMoveCallbacks.notifyStatusChanged(moveId, progress);
23462                 }
23463             }).start();
23464
23465             final String dataAppName = codeFile.getName();
23466             move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
23467                     dataAppName, appId, seinfo, targetSdkVersion);
23468         } else {
23469             move = null;
23470         }
23471
23472         installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
23473
23474         final Message msg = mHandler.obtainMessage(INIT_COPY);
23475         final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
23476         final InstallParams params = new InstallParams(origin, move, installObserver, installFlags,
23477                 installerPackageName, volumeUuid, null /*verificationInfo*/, user,
23478                 packageAbiOverride, null /*grantedPermissions*/,
23479                 null /*whitelistedRestrictedPermissions*/, PackageParser.SigningDetails.UNKNOWN,
23480                 PackageManager.INSTALL_REASON_UNKNOWN, PackageManager.VERSION_CODE_HIGHEST);
23481         params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
23482         msg.obj = params;
23483
23484         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage",
23485                 System.identityHashCode(msg.obj));
23486         Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
23487                 System.identityHashCode(msg.obj));
23488
23489         mHandler.sendMessage(msg);
23490     }
23491
23492     /**
23493      * Logs that an app has been moved from internal to external storage and vice versa.
23494      * @param packageName The package that was moved.
23495      */
23496     private void logAppMovedStorage(String packageName, boolean isPreviousLocationExternal) {
23497         final PackageParser.Package pkg;
23498         synchronized (mPackages) {
23499             pkg = mPackages.get(packageName);
23500         }
23501         if (pkg == null) {
23502             return;
23503         }
23504
23505         final StorageManager storage = mContext.getSystemService(StorageManager.class);
23506         VolumeInfo volume = storage.findVolumeByUuid(pkg.applicationInfo.storageUuid.toString());
23507         int packageExternalStorageType = getPackageExternalStorageType(volume, isExternal(pkg));
23508
23509         if (!isPreviousLocationExternal && isExternal(pkg)) {
23510             // Move from internal to external storage.
23511             StatsLog.write(StatsLog.APP_MOVED_STORAGE_REPORTED, packageExternalStorageType,
23512                     StatsLog.APP_MOVED_STORAGE_REPORTED__MOVE_TYPE__TO_EXTERNAL,
23513                     packageName);
23514         } else if (isPreviousLocationExternal && !isExternal(pkg)) {
23515             // Move from external to internal storage.
23516             StatsLog.write(StatsLog.APP_MOVED_STORAGE_REPORTED, packageExternalStorageType,
23517                     StatsLog.APP_MOVED_STORAGE_REPORTED__MOVE_TYPE__TO_INTERNAL,
23518                     packageName);
23519         }
23520     }
23521
23522     @Override
23523     public int movePrimaryStorage(String volumeUuid) throws RemoteException {
23524         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
23525
23526         final int realMoveId = mNextMoveId.getAndIncrement();
23527         final Bundle extras = new Bundle();
23528         extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
23529         mMoveCallbacks.notifyCreated(realMoveId, extras);
23530
23531         final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
23532             @Override
23533             public void onCreated(int moveId, Bundle extras) {
23534                 // Ignored
23535             }
23536
23537             @Override
23538             public void onStatusChanged(int moveId, int status, long estMillis) {
23539                 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
23540             }
23541         };
23542
23543         final StorageManager storage = mContext.getSystemService(StorageManager.class);
23544         storage.setPrimaryStorageUuid(volumeUuid, callback);
23545         return realMoveId;
23546     }
23547
23548     @Override
23549     public int getMoveStatus(int moveId) {
23550         mContext.enforceCallingOrSelfPermission(
23551                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23552         return mMoveCallbacks.mLastStatus.get(moveId);
23553     }
23554
23555     @Override
23556     public void registerMoveCallback(IPackageMoveObserver callback) {
23557         mContext.enforceCallingOrSelfPermission(
23558                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23559         mMoveCallbacks.register(callback);
23560     }
23561
23562     @Override
23563     public void unregisterMoveCallback(IPackageMoveObserver callback) {
23564         mContext.enforceCallingOrSelfPermission(
23565                 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
23566         mMoveCallbacks.unregister(callback);
23567     }
23568
23569     @Override
23570     public boolean setInstallLocation(int loc) {
23571         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
23572                 null);
23573         if (getInstallLocation() == loc) {
23574             return true;
23575         }
23576         if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
23577                 || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
23578             android.provider.Settings.Global.putInt(mContext.getContentResolver(),
23579                     android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
23580             return true;
23581         }
23582         return false;
23583    }
23584
23585     @Override
23586     public int getInstallLocation() {
23587         // allow instant app access
23588         return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
23589                 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
23590                 PackageHelper.APP_INSTALL_AUTO);
23591     }
23592
23593     /** Called by UserManagerService */
23594     void cleanUpUser(UserManagerService userManager, int userHandle) {
23595         synchronized (mPackages) {
23596             mDirtyUsers.remove(userHandle);
23597             mUserNeedsBadging.delete(userHandle);
23598             mSettings.removeUserLPw(userHandle);
23599             mPendingBroadcasts.remove(userHandle);
23600             mInstantAppRegistry.onUserRemovedLPw(userHandle);
23601             removeUnusedPackagesLPw(userManager, userHandle);
23602         }
23603     }
23604
23605     /**
23606      * We're removing userHandle and would like to remove any downloaded packages
23607      * that are no longer in use by any other user.
23608      * @param userHandle the user being removed
23609      */
23610     @GuardedBy("mPackages")
23611     private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) {
23612         final boolean DEBUG_CLEAN_APKS = false;
23613         int [] users = userManager.getUserIds();
23614         Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
23615         while (psit.hasNext()) {
23616             PackageSetting ps = psit.next();
23617             if (ps.pkg == null) {
23618                 continue;
23619             }
23620             final String packageName = ps.pkg.packageName;
23621             // Skip over if system app
23622             if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
23623                 continue;
23624             }
23625             if (DEBUG_CLEAN_APKS) {
23626                 Slog.i(TAG, "Checking package " + packageName);
23627             }
23628             boolean keep = shouldKeepUninstalledPackageLPr(packageName);
23629             if (keep) {
23630                 if (DEBUG_CLEAN_APKS) {
23631                     Slog.i(TAG, "  Keeping package " + packageName + " - requested by DO");
23632                 }
23633             } else {
23634                 for (int i = 0; i < users.length; i++) {
23635                     if (users[i] != userHandle && ps.getInstalled(users[i])) {
23636                         keep = true;
23637                         if (DEBUG_CLEAN_APKS) {
23638                             Slog.i(TAG, "  Keeping package " + packageName + " for user "
23639                                     + users[i]);
23640                         }
23641                         break;
23642                     }
23643                 }
23644             }
23645             if (!keep) {
23646                 if (DEBUG_CLEAN_APKS) {
23647                     Slog.i(TAG, "  Removing package " + packageName);
23648                 }
23649                 //end run
23650                 mHandler.post(() -> deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23651                         userHandle, 0));
23652             }
23653         }
23654     }
23655
23656     /** Called by UserManagerService */
23657     void createNewUser(int userId, String[] disallowedPackages) {
23658         synchronized (mInstallLock) {
23659             mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages);
23660         }
23661         synchronized (mPackages) {
23662             scheduleWritePackageRestrictionsLocked(userId);
23663             scheduleWritePackageListLocked(userId);
23664             primeDomainVerificationsLPw(userId);
23665         }
23666     }
23667
23668     void onNewUserCreated(final int userId) {
23669         mDefaultPermissionPolicy.grantDefaultPermissions(userId);
23670         synchronized(mPackages) {
23671             // NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG
23672             mPermissionManager.updateAllPermissions(
23673                     StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(),
23674                     mPermissionCallback);
23675         }
23676     }
23677
23678     @Override
23679     public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
23680         mContext.enforceCallingOrSelfPermission(
23681                 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
23682                 "Only package verification agents can read the verifier device identity");
23683
23684         synchronized (mPackages) {
23685             return mSettings.getVerifierDeviceIdentityLPw();
23686         }
23687     }
23688
23689     @Override
23690     public void setPermissionEnforced(String permission, boolean enforced) {
23691         // TODO: Now that we no longer change GID for storage, this should to away.
23692         mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
23693                 "setPermissionEnforced");
23694         if (READ_EXTERNAL_STORAGE.equals(permission)) {
23695             synchronized (mPackages) {
23696                 if (mSettings.mReadExternalStorageEnforced == null
23697                         || mSettings.mReadExternalStorageEnforced != enforced) {
23698                     mSettings.mReadExternalStorageEnforced =
23699                             enforced ? Boolean.TRUE : Boolean.FALSE;
23700                     mSettings.writeLPr();
23701                 }
23702             }
23703             // kill any non-foreground processes so we restart them and
23704             // grant/revoke the GID.
23705             final IActivityManager am = ActivityManager.getService();
23706             if (am != null) {
23707                 final long token = Binder.clearCallingIdentity();
23708                 try {
23709                     am.killProcessesBelowForeground("setPermissionEnforcement");
23710                 } catch (RemoteException e) {
23711                 } finally {
23712                     Binder.restoreCallingIdentity(token);
23713                 }
23714             }
23715         } else {
23716             throw new IllegalArgumentException("No selective enforcement for " + permission);
23717         }
23718     }
23719
23720     @Override
23721     @Deprecated
23722     public boolean isPermissionEnforced(String permission) {
23723         // allow instant applications
23724         return true;
23725     }
23726
23727     @Override
23728     public boolean isStorageLow() {
23729         // allow instant applications
23730         final long token = Binder.clearCallingIdentity();
23731         try {
23732             final DeviceStorageMonitorInternal
23733                     dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
23734             if (dsm != null) {
23735                 return dsm.isMemoryLow();
23736             } else {
23737                 return false;
23738             }
23739         } finally {
23740             Binder.restoreCallingIdentity(token);
23741         }
23742     }
23743
23744     @Override
23745     public IPackageInstaller getPackageInstaller() {
23746         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
23747             return null;
23748         }
23749         return mInstallerService;
23750     }
23751
23752     @Override
23753     public IArtManager getArtManager() {
23754         return mArtManagerService;
23755     }
23756
23757     private boolean userNeedsBadging(int userId) {
23758         int index = mUserNeedsBadging.indexOfKey(userId);
23759         if (index < 0) {
23760             final UserInfo userInfo;
23761             final long token = Binder.clearCallingIdentity();
23762             try {
23763                 userInfo = sUserManager.getUserInfo(userId);
23764             } finally {
23765                 Binder.restoreCallingIdentity(token);
23766             }
23767             final boolean b;
23768             if (userInfo != null && userInfo.isManagedProfile()) {
23769                 b = true;
23770             } else {
23771                 b = false;
23772             }
23773             mUserNeedsBadging.put(userId, b);
23774             return b;
23775         }
23776         return mUserNeedsBadging.valueAt(index);
23777     }
23778
23779     @Override
23780     public KeySet getKeySetByAlias(String packageName, String alias) {
23781         if (packageName == null || alias == null) {
23782             return null;
23783         }
23784         synchronized(mPackages) {
23785             final PackageParser.Package pkg = mPackages.get(packageName);
23786             if (pkg == null) {
23787                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23788                 throw new IllegalArgumentException("Unknown package: " + packageName);
23789             }
23790             final PackageSetting ps = (PackageSetting) pkg.mExtras;
23791             if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) {
23792                 Slog.w(TAG, "KeySet requested for filtered package: " + packageName);
23793                 throw new IllegalArgumentException("Unknown package: " + packageName);
23794             }
23795             final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23796             return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
23797         }
23798     }
23799
23800     @Override
23801     public KeySet getSigningKeySet(String packageName) {
23802         if (packageName == null) {
23803             return null;
23804         }
23805         synchronized(mPackages) {
23806             final int callingUid = Binder.getCallingUid();
23807             final int callingUserId = UserHandle.getUserId(callingUid);
23808             final PackageParser.Package pkg = mPackages.get(packageName);
23809             if (pkg == null) {
23810                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23811                 throw new IllegalArgumentException("Unknown package: " + packageName);
23812             }
23813             final PackageSetting ps = (PackageSetting) pkg.mExtras;
23814             if (filterAppAccessLPr(ps, callingUid, callingUserId)) {
23815                 // filter and pretend the package doesn't exist
23816                 Slog.w(TAG, "KeySet requested for filtered package: " + packageName
23817                         + ", uid:" + callingUid);
23818                 throw new IllegalArgumentException("Unknown package: " + packageName);
23819             }
23820             if (pkg.applicationInfo.uid != callingUid
23821                     && Process.SYSTEM_UID != callingUid) {
23822                 throw new SecurityException("May not access signing KeySet of other apps.");
23823             }
23824             final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23825             return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
23826         }
23827     }
23828
23829     @Override
23830     public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
23831         final int callingUid = Binder.getCallingUid();
23832         if (getInstantAppPackageName(callingUid) != null) {
23833             return false;
23834         }
23835         if (packageName == null || ks == null) {
23836             return false;
23837         }
23838         synchronized(mPackages) {
23839             final PackageParser.Package pkg = mPackages.get(packageName);
23840             if (pkg == null
23841                     || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23842                             UserHandle.getUserId(callingUid))) {
23843                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23844                 throw new IllegalArgumentException("Unknown package: " + packageName);
23845             }
23846             IBinder ksh = ks.getToken();
23847             if (ksh instanceof KeySetHandle) {
23848                 final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23849                 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
23850             }
23851             return false;
23852         }
23853     }
23854
23855     @Override
23856     public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
23857         final int callingUid = Binder.getCallingUid();
23858         if (getInstantAppPackageName(callingUid) != null) {
23859             return false;
23860         }
23861         if (packageName == null || ks == null) {
23862             return false;
23863         }
23864         synchronized(mPackages) {
23865             final PackageParser.Package pkg = mPackages.get(packageName);
23866             if (pkg == null
23867                     || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid,
23868                             UserHandle.getUserId(callingUid))) {
23869                 Slog.w(TAG, "KeySet requested for unknown package: " + packageName);
23870                 throw new IllegalArgumentException("Unknown package: " + packageName);
23871             }
23872             IBinder ksh = ks.getToken();
23873             if (ksh instanceof KeySetHandle) {
23874                 final KeySetManagerService ksms = mSettings.mKeySetManagerService;
23875                 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
23876             }
23877             return false;
23878         }
23879     }
23880
23881     @GuardedBy("mPackages")
23882     private void deletePackageIfUnusedLPr(final String packageName) {
23883         PackageSetting ps = mSettings.mPackages.get(packageName);
23884         if (ps == null) {
23885             return;
23886         }
23887         if (!ps.isAnyInstalled(sUserManager.getUserIds())) {
23888             // TODO Implement atomic delete if package is unused
23889             // It is currently possible that the package will be deleted even if it is installed
23890             // after this method returns.
23891             mHandler.post(() -> deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST,
23892                     0, PackageManager.DELETE_ALL_USERS));
23893         }
23894     }
23895
23896     /**
23897      * Check and throw if the given before/after packages would be considered a
23898      * downgrade.
23899      */
23900     private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
23901             throws PackageManagerException {
23902         if (after.getLongVersionCode() < before.getLongVersionCode()) {
23903             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23904                     "Update version code " + after.versionCode + " is older than current "
23905                     + before.getLongVersionCode());
23906         } else if (after.getLongVersionCode() == before.getLongVersionCode()) {
23907             if (after.baseRevisionCode < before.baseRevisionCode) {
23908                 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23909                         "Update base revision code " + after.baseRevisionCode
23910                         + " is older than current " + before.baseRevisionCode);
23911             }
23912
23913             if (!ArrayUtils.isEmpty(after.splitNames)) {
23914                 for (int i = 0; i < after.splitNames.length; i++) {
23915                     final String splitName = after.splitNames[i];
23916                     final int j = ArrayUtils.indexOf(before.splitNames, splitName);
23917                     if (j != -1) {
23918                         if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
23919                             throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
23920                                     "Update split " + splitName + " revision code "
23921                                     + after.splitRevisionCodes[i] + " is older than current "
23922                                     + before.splitRevisionCodes[j]);
23923                         }
23924                     }
23925                 }
23926             }
23927         }
23928     }
23929
23930     private static class MoveCallbacks extends Handler {
23931         private static final int MSG_CREATED = 1;
23932         private static final int MSG_STATUS_CHANGED = 2;
23933
23934         private final RemoteCallbackList<IPackageMoveObserver>
23935                 mCallbacks = new RemoteCallbackList<>();
23936
23937         private final SparseIntArray mLastStatus = new SparseIntArray();
23938
23939         public MoveCallbacks(Looper looper) {
23940             super(looper);
23941         }
23942
23943         public void register(IPackageMoveObserver callback) {
23944             mCallbacks.register(callback);
23945         }
23946
23947         public void unregister(IPackageMoveObserver callback) {
23948             mCallbacks.unregister(callback);
23949         }
23950
23951         @Override
23952         public void handleMessage(Message msg) {
23953             final SomeArgs args = (SomeArgs) msg.obj;
23954             final int n = mCallbacks.beginBroadcast();
23955             for (int i = 0; i < n; i++) {
23956                 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
23957                 try {
23958                     invokeCallback(callback, msg.what, args);
23959                 } catch (RemoteException ignored) {
23960                 }
23961             }
23962             mCallbacks.finishBroadcast();
23963             args.recycle();
23964         }
23965
23966         private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
23967                 throws RemoteException {
23968             switch (what) {
23969                 case MSG_CREATED: {
23970                     callback.onCreated(args.argi1, (Bundle) args.arg2);
23971                     break;
23972                 }
23973                 case MSG_STATUS_CHANGED: {
23974                     callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
23975                     break;
23976                 }
23977             }
23978         }
23979
23980         private void notifyCreated(int moveId, Bundle extras) {
23981             Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
23982
23983             final SomeArgs args = SomeArgs.obtain();
23984             args.argi1 = moveId;
23985             args.arg2 = extras;
23986             obtainMessage(MSG_CREATED, args).sendToTarget();
23987         }
23988
23989         private void notifyStatusChanged(int moveId, int status) {
23990             notifyStatusChanged(moveId, status, -1);
23991         }
23992
23993         private void notifyStatusChanged(int moveId, int status, long estMillis) {
23994             Slog.v(TAG, "Move " + moveId + " status " + status);
23995
23996             final SomeArgs args = SomeArgs.obtain();
23997             args.argi1 = moveId;
23998             args.argi2 = status;
23999             args.arg3 = estMillis;
24000             obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
24001
24002             synchronized (mLastStatus) {
24003                 mLastStatus.put(moveId, status);
24004             }
24005         }
24006     }
24007
24008     private final static class OnPermissionChangeListeners extends Handler {
24009         private static final int MSG_ON_PERMISSIONS_CHANGED = 1;
24010
24011         private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners =
24012                 new RemoteCallbackList<>();
24013
24014         public OnPermissionChangeListeners(Looper looper) {
24015             super(looper);
24016         }
24017
24018         @Override
24019         public void handleMessage(Message msg) {
24020             switch (msg.what) {
24021                 case MSG_ON_PERMISSIONS_CHANGED: {
24022                     final int uid = msg.arg1;
24023                     handleOnPermissionsChanged(uid);
24024                 } break;
24025             }
24026         }
24027
24028         public void addListenerLocked(IOnPermissionsChangeListener listener) {
24029             mPermissionListeners.register(listener);
24030
24031         }
24032
24033         public void removeListenerLocked(IOnPermissionsChangeListener listener) {
24034             mPermissionListeners.unregister(listener);
24035         }
24036
24037         public void onPermissionsChanged(int uid) {
24038             if (mPermissionListeners.getRegisteredCallbackCount() > 0) {
24039                 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget();
24040             }
24041         }
24042
24043         private void handleOnPermissionsChanged(int uid) {
24044             final int count = mPermissionListeners.beginBroadcast();
24045             try {
24046                 for (int i = 0; i < count; i++) {
24047                     IOnPermissionsChangeListener callback = mPermissionListeners
24048                             .getBroadcastItem(i);
24049                     try {
24050                         callback.onPermissionsChanged(uid);
24051                     } catch (RemoteException e) {
24052                         Log.e(TAG, "Permission listener is dead", e);
24053                     }
24054                 }
24055             } finally {
24056                 mPermissionListeners.finishBroadcast();
24057             }
24058         }
24059     }
24060
24061     private class PackageManagerNative extends IPackageManagerNative.Stub {
24062         @Override
24063         public String[] getNamesForUids(int[] uids) throws RemoteException {
24064             final String[] results = PackageManagerService.this.getNamesForUids(uids);
24065             // massage results so they can be parsed by the native binder
24066             for (int i = results.length - 1; i >= 0; --i) {
24067                 if (results[i] == null) {
24068                     results[i] = "";
24069                 }
24070             }
24071             return results;
24072         }
24073
24074         // NB: this differentiates between preloads and sideloads
24075         @Override
24076         public String getInstallerForPackage(String packageName) throws RemoteException {
24077             final String installerName = getInstallerPackageName(packageName);
24078             if (!TextUtils.isEmpty(installerName)) {
24079                 return installerName;
24080             }
24081             // differentiate between preload and sideload
24082             int callingUser = UserHandle.getUserId(Binder.getCallingUid());
24083             ApplicationInfo appInfo = getApplicationInfo(packageName,
24084                                     /*flags*/ 0,
24085                                     /*userId*/ callingUser);
24086             if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
24087                 return "preload";
24088             }
24089             return "";
24090         }
24091
24092         @Override
24093         public long getVersionCodeForPackage(String packageName) throws RemoteException {
24094             try {
24095                 int callingUser = UserHandle.getUserId(Binder.getCallingUid());
24096                 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser);
24097                 if (pInfo != null) {
24098                     return pInfo.getLongVersionCode();
24099                 }
24100             } catch (Exception e) {
24101             }
24102             return 0;
24103         }
24104
24105         @Override
24106         public int getTargetSdkVersionForPackage(String packageName)
24107                 throws RemoteException {
24108             int callingUser = UserHandle.getUserId(Binder.getCallingUid());
24109             ApplicationInfo info = getApplicationInfo(packageName, 0, callingUser);
24110             if (info == null) {
24111                 throw new RemoteException(
24112                         "Couldn't get ApplicationInfo for package " + packageName);
24113             }
24114             return info.targetSdkVersion;
24115         }
24116
24117         @Override
24118         public boolean[] isAudioPlaybackCaptureAllowed(String[] packageNames)
24119                 throws RemoteException {
24120             int callingUser = UserHandle.getUserId(Binder.getCallingUid());
24121             boolean[] results = new boolean[packageNames.length];
24122             for (int i = results.length - 1; i >= 0; --i) {
24123                 ApplicationInfo appInfo = getApplicationInfo(packageNames[i], 0, callingUser);
24124                 results[i] = appInfo == null ? false : appInfo.isAudioPlaybackCaptureAllowed();
24125             }
24126             return results;
24127         }
24128
24129         @Override
24130         public int getLocationFlags(String packageName) throws RemoteException {
24131             int callingUser = UserHandle.getUserId(Binder.getCallingUid());
24132             ApplicationInfo appInfo = getApplicationInfo(packageName,
24133                     /*flags*/ 0,
24134                     /*userId*/ callingUser);
24135             if (appInfo == null) {
24136                 throw new RemoteException(
24137                         "Couldn't get ApplicationInfo for package " + packageName);
24138             }
24139             return ((appInfo.isSystemApp() ? IPackageManagerNative.LOCATION_SYSTEM : 0)
24140                     | (appInfo.isVendor() ? IPackageManagerNative.LOCATION_VENDOR : 0)
24141                     | (appInfo.isProduct() ? IPackageManagerNative.LOCATION_PRODUCT : 0));
24142         }
24143
24144         @Override
24145         public String getModuleMetadataPackageName() throws RemoteException {
24146             return PackageManagerService.this.mModuleInfoProvider.getPackageName();
24147         }
24148     }
24149
24150     private class PackageManagerInternalImpl extends PackageManagerInternal {
24151         @Override
24152         public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask,
24153                 int flagValues, int userId) {
24154             PackageManagerService.this.updatePermissionFlags(
24155                     permName, packageName, flagMask, flagValues, true, userId);
24156         }
24157
24158         @Override
24159         public List<ApplicationInfo> getInstalledApplications(int flags, int userId,
24160                 int callingUid) {
24161             return PackageManagerService.this.getInstalledApplicationsListInternal(flags, userId,
24162                     callingUid);
24163         }
24164
24165
24166         @Override
24167         public boolean isPlatformSigned(String packageName) {
24168             PackageSetting packageSetting = mSettings.mPackages.get(packageName);
24169             if (packageSetting == null) {
24170                 return false;
24171             }
24172             PackageParser.Package pkg = packageSetting.pkg;
24173             if (pkg == null) {
24174                 // May happen if package in on a removable sd card
24175                 return false;
24176             }
24177             return pkg.mSigningDetails.hasAncestorOrSelf(mPlatformPackage.mSigningDetails)
24178                     || mPlatformPackage.mSigningDetails.checkCapability(pkg.mSigningDetails,
24179                     PackageParser.SigningDetails.CertCapabilities.PERMISSION);
24180         }
24181
24182         @Override
24183         public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
24184             SigningDetails sd = getSigningDetails(packageName);
24185             if (sd == null) {
24186                 return false;
24187             }
24188             return sd.hasSha256Certificate(restoringFromSigHash,
24189                     SigningDetails.CertCapabilities.INSTALLED_DATA);
24190         }
24191
24192         @Override
24193         public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) {
24194             SigningDetails sd = getSigningDetails(packageName);
24195             if (sd == null) {
24196                 return false;
24197             }
24198             return sd.hasCertificate(restoringFromSig,
24199                     SigningDetails.CertCapabilities.INSTALLED_DATA);
24200         }
24201
24202         @Override
24203         public boolean hasSignatureCapability(int serverUid, int clientUid,
24204                 @SigningDetails.CertCapabilities int capability) {
24205             SigningDetails serverSigningDetails = getSigningDetails(serverUid);
24206             SigningDetails clientSigningDetails = getSigningDetails(clientUid);
24207             return serverSigningDetails.checkCapability(clientSigningDetails, capability)
24208                     || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails);
24209
24210         }
24211
24212         private SigningDetails getSigningDetails(@NonNull String packageName) {
24213             synchronized (mPackages) {
24214                 PackageParser.Package p = mPackages.get(packageName);
24215                 if (p == null) {
24216                     return null;
24217                 }
24218                 return p.mSigningDetails;
24219             }
24220         }
24221
24222         private SigningDetails getSigningDetails(int uid) {
24223             synchronized (mPackages) {
24224                 final int appId = UserHandle.getAppId(uid);
24225                 final Object obj = mSettings.getSettingLPr(appId);
24226                 if (obj != null) {
24227                     if (obj instanceof SharedUserSetting) {
24228                         return ((SharedUserSetting) obj).signatures.mSigningDetails;
24229                     } else if (obj instanceof PackageSetting) {
24230                         final PackageSetting ps = (PackageSetting) obj;
24231                         return ps.signatures.mSigningDetails;
24232                     }
24233                 }
24234                 return SigningDetails.UNKNOWN;
24235             }
24236         }
24237
24238         @Override
24239         public int getPermissionFlagsTEMP(String permName, String packageName, int userId) {
24240             return PackageManagerService.this.getPermissionFlags(permName, packageName, userId);
24241         }
24242
24243         @Override
24244         public boolean isInstantApp(String packageName, int userId) {
24245             return PackageManagerService.this.isInstantApp(packageName, userId);
24246         }
24247
24248         @Override
24249         public String getInstantAppPackageName(int uid) {
24250             return PackageManagerService.this.getInstantAppPackageName(uid);
24251         }
24252
24253         @Override
24254         public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) {
24255             synchronized (mPackages) {
24256                 return PackageManagerService.this.filterAppAccessLPr(
24257                         (PackageSetting) pkg.mExtras, callingUid, userId);
24258             }
24259         }
24260
24261         @Override
24262         public PackageParser.Package getPackage(String packageName) {
24263             synchronized (mPackages) {
24264                 packageName = resolveInternalPackageNameLPr(
24265                         packageName, PackageManager.VERSION_CODE_HIGHEST);
24266                 return mPackages.get(packageName);
24267             }
24268         }
24269
24270         @Override
24271         public PackageList getPackageList(PackageListObserver observer) {
24272             synchronized (mPackages) {
24273                 final int N = mPackages.size();
24274                 final ArrayList<String> list = new ArrayList<>(N);
24275                 for (int i = 0; i < N; i++) {
24276                     list.add(mPackages.keyAt(i));
24277                 }
24278                 final PackageList packageList = new PackageList(list, observer);
24279                 if (observer != null) {
24280                     mPackageListObservers.add(packageList);
24281                 }
24282                 return packageList;
24283             }
24284         }
24285
24286         @Override
24287         public void removePackageListObserver(PackageListObserver observer) {
24288             synchronized (mPackages) {
24289                 mPackageListObservers.remove(observer);
24290             }
24291         }
24292
24293         @Override
24294         public PackageParser.Package getDisabledSystemPackage(String packageName) {
24295             synchronized (mPackages) {
24296                 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
24297                 return (ps != null) ? ps.pkg : null;
24298             }
24299         }
24300
24301         @Override
24302         public @Nullable String getDisabledSystemPackageName(@NonNull String packageName) {
24303             PackageParser.Package pkg = getDisabledSystemPackage(packageName);
24304             return pkg == null ? null : pkg.packageName;
24305         }
24306
24307         @Override
24308         public String getKnownPackageName(int knownPackage, int userId) {
24309             switch(knownPackage) {
24310                 case PackageManagerInternal.PACKAGE_BROWSER:
24311                     return getDefaultBrowserPackageName(userId);
24312                 case PackageManagerInternal.PACKAGE_INSTALLER:
24313                     return mRequiredInstallerPackage;
24314                 case PackageManagerInternal.PACKAGE_SETUP_WIZARD:
24315                     return mSetupWizardPackage;
24316                 case PackageManagerInternal.PACKAGE_SYSTEM:
24317                     return "android";
24318                 case PackageManagerInternal.PACKAGE_VERIFIER:
24319                     return mRequiredVerifierPackage;
24320                 case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER:
24321                     return mSystemTextClassifierPackage;
24322                 case PackageManagerInternal.PACKAGE_PERMISSION_CONTROLLER:
24323                     return mRequiredPermissionControllerPackage;
24324                 case PackageManagerInternal.PACKAGE_WELLBEING:
24325                     return mWellbeingPackage;
24326                 case PackageManagerInternal.PACKAGE_DOCUMENTER:
24327                     return mDocumenterPackage;
24328                 case PackageManagerInternal.PACKAGE_CONFIGURATOR:
24329                     return mConfiguratorPackage;
24330                 case PackageManagerInternal.PACKAGE_INCIDENT_REPORT_APPROVER:
24331                     return mIncidentReportApproverPackage;
24332                 case PackageManagerInternal.PACKAGE_APP_PREDICTOR:
24333                     return mAppPredictionServicePackage;
24334             }
24335             return null;
24336         }
24337
24338         @Override
24339         public boolean isResolveActivityComponent(ComponentInfo component) {
24340             return mResolveActivity.packageName.equals(component.packageName)
24341                     && mResolveActivity.name.equals(component.name);
24342         }
24343
24344         @Override
24345         public void setLocationPackagesProvider(PackagesProvider provider) {
24346             mDefaultPermissionPolicy.setLocationPackagesProvider(provider);
24347         }
24348
24349         @Override
24350         public void setLocationExtraPackagesProvider(PackagesProvider provider) {
24351             mDefaultPermissionPolicy.setLocationExtraPackagesProvider(provider);
24352         }
24353
24354         @Override
24355         public void setVoiceInteractionPackagesProvider(PackagesProvider provider) {
24356             mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider);
24357         }
24358
24359         @Override
24360         public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
24361             mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
24362         }
24363
24364         @Override
24365         public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) {
24366             mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider);
24367         }
24368
24369         @Override
24370         public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
24371             mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp(
24372                     packageName, userId);
24373         }
24374
24375         @Override
24376         public void setKeepUninstalledPackages(final List<String> packageList) {
24377             Preconditions.checkNotNull(packageList);
24378             List<String> removedFromList = null;
24379             synchronized (mPackages) {
24380                 if (mKeepUninstalledPackages != null) {
24381                     final int packagesCount = mKeepUninstalledPackages.size();
24382                     for (int i = 0; i < packagesCount; i++) {
24383                         String oldPackage = mKeepUninstalledPackages.get(i);
24384                         if (packageList != null && packageList.contains(oldPackage)) {
24385                             continue;
24386                         }
24387                         if (removedFromList == null) {
24388                             removedFromList = new ArrayList<>();
24389                         }
24390                         removedFromList.add(oldPackage);
24391                     }
24392                 }
24393                 mKeepUninstalledPackages = new ArrayList<>(packageList);
24394                 if (removedFromList != null) {
24395                     final int removedCount = removedFromList.size();
24396                     for (int i = 0; i < removedCount; i++) {
24397                         deletePackageIfUnusedLPr(removedFromList.get(i));
24398                     }
24399                 }
24400             }
24401         }
24402
24403         @Override
24404         public boolean isPermissionsReviewRequired(String packageName, int userId) {
24405             synchronized (mPackages) {
24406                 final PackageParser.Package pkg = mPackages.get(packageName);
24407                 if (pkg == null) {
24408                     return false;
24409                 }
24410
24411                 return mPermissionManager.isPermissionsReviewRequired(pkg, userId);
24412             }
24413         }
24414
24415         @Override
24416         public PackageInfo getPackageInfo(
24417                 String packageName, int flags, int filterCallingUid, int userId) {
24418             return PackageManagerService.this
24419                     .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST,
24420                             flags, filterCallingUid, userId);
24421         }
24422
24423         @Override
24424         public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) {
24425             synchronized (mPackages) {
24426                 final PackageSetting ps = mSettings.mPackages.get(packageName);
24427                 PersistableBundle launcherExtras = null;
24428                 if (ps != null) {
24429                     launcherExtras = ps.readUserState(userId).suspendedLauncherExtras;
24430                 }
24431                 return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null;
24432             }
24433         }
24434
24435         @Override
24436         public boolean isPackageSuspended(String packageName, int userId) {
24437             synchronized (mPackages) {
24438                 final PackageSetting ps = mSettings.mPackages.get(packageName);
24439                 return (ps != null) ? ps.getSuspended(userId) : false;
24440             }
24441         }
24442
24443         @Override
24444         public String getSuspendingPackage(String suspendedPackage, int userId) {
24445             synchronized (mPackages) {
24446                 final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
24447                 return (ps != null) ? ps.readUserState(userId).suspendingPackage : null;
24448             }
24449         }
24450
24451         @Override
24452         public SuspendDialogInfo getSuspendedDialogInfo(String suspendedPackage, int userId) {
24453             synchronized (mPackages) {
24454                 final PackageSetting ps = mSettings.mPackages.get(suspendedPackage);
24455                 return (ps != null) ? ps.readUserState(userId).dialogInfo : null;
24456             }
24457         }
24458
24459         @Override
24460         public int getDistractingPackageRestrictions(String packageName, int userId) {
24461             synchronized (mPackages) {
24462                 final PackageSetting ps = mSettings.mPackages.get(packageName);
24463                 return (ps != null) ? ps.getDistractionFlags(userId) : RESTRICTION_NONE;
24464             }
24465         }
24466
24467         @Override
24468         public int getPackageUid(String packageName, int flags, int userId) {
24469             return PackageManagerService.this
24470                     .getPackageUid(packageName, flags, userId);
24471         }
24472
24473         @Override
24474         public ApplicationInfo getApplicationInfo(
24475                 String packageName, int flags, int filterCallingUid, int userId) {
24476             return PackageManagerService.this
24477                     .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId);
24478         }
24479
24480         @Override
24481         public ActivityInfo getActivityInfo(
24482                 ComponentName component, int flags, int filterCallingUid, int userId) {
24483             return PackageManagerService.this
24484                     .getActivityInfoInternal(component, flags, filterCallingUid, userId);
24485         }
24486
24487         @Override
24488         public List<ResolveInfo> queryIntentActivities(
24489                 Intent intent, int flags, int filterCallingUid, int userId) {
24490             final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24491             return PackageManagerService.this
24492                     .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid,
24493                             userId, false /*resolveForStart*/, true /*allowDynamicSplits*/);
24494         }
24495
24496         @Override
24497         public List<ResolveInfo> queryIntentServices(
24498                 Intent intent, int flags, int callingUid, int userId) {
24499             final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver());
24500             return PackageManagerService.this
24501                     .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid,
24502                             false);
24503         }
24504
24505         @Override
24506         public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates,
24507                 int userId) {
24508             return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId);
24509         }
24510
24511         @Override
24512         public ComponentName getDefaultHomeActivity(int userId) {
24513             return PackageManagerService.this.getDefaultHomeActivity(userId);
24514         }
24515
24516         @Override
24517         public void setDeviceAndProfileOwnerPackages(
24518                 int deviceOwnerUserId, String deviceOwnerPackage,
24519                 SparseArray<String> profileOwnerPackages) {
24520             mProtectedPackages.setDeviceAndProfileOwnerPackages(
24521                     deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages);
24522
24523             final ArraySet<Integer> usersWithPoOrDo = new ArraySet<>();
24524             if (deviceOwnerPackage != null) {
24525                 usersWithPoOrDo.add(deviceOwnerUserId);
24526             }
24527             final int sz = profileOwnerPackages.size();
24528             for (int i = 0; i < sz; i++) {
24529                 if (profileOwnerPackages.valueAt(i) != null) {
24530                     usersWithPoOrDo.add(profileOwnerPackages.keyAt(i));
24531                 }
24532             }
24533             unsuspendForNonSystemSuspendingPackages(usersWithPoOrDo);
24534         }
24535
24536         @Override
24537         public boolean isPackageDataProtected(int userId, String packageName) {
24538             return mProtectedPackages.isPackageDataProtected(userId, packageName);
24539         }
24540
24541         @Override
24542         public boolean isPackageStateProtected(String packageName, int userId) {
24543             return mProtectedPackages.isPackageStateProtected(userId, packageName);
24544         }
24545
24546         @Override
24547         public boolean isPackageEphemeral(int userId, String packageName) {
24548             synchronized (mPackages) {
24549                 final PackageSetting ps = mSettings.mPackages.get(packageName);
24550                 return ps != null ? ps.getInstantApp(userId) : false;
24551             }
24552         }
24553
24554         @Override
24555         public boolean wasPackageEverLaunched(String packageName, int userId) {
24556             synchronized (mPackages) {
24557                 return mSettings.wasPackageEverLaunchedLPr(packageName, userId);
24558             }
24559         }
24560
24561         @Override
24562         public boolean isEnabledAndMatches(ComponentInfo info, int flags, int userId) {
24563             synchronized (mPackages) {
24564                 return mSettings.isEnabledAndMatchLPr(info, flags, userId);
24565             }
24566         }
24567
24568         @Override
24569         public boolean userNeedsBadging(int userId) {
24570             synchronized (mPackages) {
24571                 return PackageManagerService.this.userNeedsBadging(userId);
24572             }
24573         }
24574
24575         @Override
24576         public void grantRuntimePermission(String packageName, String permName, int userId,
24577                 boolean overridePolicy) {
24578             PackageManagerService.this.mPermissionManager.grantRuntimePermission(
24579                     permName, packageName, overridePolicy, getCallingUid(), userId,
24580                     mPermissionCallback);
24581         }
24582
24583         @Override
24584         public void revokeRuntimePermission(String packageName, String permName, int userId,
24585                 boolean overridePolicy) {
24586             mPermissionManager.revokeRuntimePermission(
24587                     permName, packageName, overridePolicy, userId,
24588                     mPermissionCallback);
24589         }
24590
24591         @Override
24592         public String getNameForUid(int uid) {
24593             return PackageManagerService.this.getNameForUid(uid);
24594         }
24595
24596         @Override
24597         public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj,
24598                 Intent origIntent, String resolvedType, String callingPackage,
24599                 Bundle verificationBundle, int userId) {
24600             PackageManagerService.this.requestInstantAppResolutionPhaseTwo(
24601                     responseObj, origIntent, resolvedType, callingPackage, verificationBundle,
24602                     userId);
24603         }
24604
24605         @Override
24606         public void grantEphemeralAccess(int userId, Intent intent,
24607                 int targetAppId, int ephemeralAppId) {
24608             synchronized (mPackages) {
24609                 mInstantAppRegistry.grantInstantAccessLPw(userId, intent,
24610                         targetAppId, ephemeralAppId);
24611             }
24612         }
24613
24614         @Override
24615         public boolean isInstantAppInstallerComponent(ComponentName component) {
24616             synchronized (mPackages) {
24617                 return mInstantAppInstallerActivity != null
24618                         && mInstantAppInstallerActivity.getComponentName().equals(component);
24619             }
24620         }
24621
24622         @Override
24623         public void pruneInstantApps() {
24624             mInstantAppRegistry.pruneInstantApps();
24625         }
24626
24627         @Override
24628         public String getSetupWizardPackageName() {
24629             return mSetupWizardPackage;
24630         }
24631
24632         public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) {
24633             if (policy != null) {
24634                 mExternalSourcesPolicy = policy;
24635             }
24636         }
24637
24638         @Override
24639         public boolean isPackagePersistent(String packageName) {
24640             synchronized (mPackages) {
24641                 PackageParser.Package pkg = mPackages.get(packageName);
24642                 return pkg != null
24643                         ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM
24644                                         | ApplicationInfo.FLAG_PERSISTENT)) ==
24645                                 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT))
24646                         : false;
24647             }
24648         }
24649
24650         @Override
24651         public boolean isLegacySystemApp(PackageParser.Package pkg) {
24652             synchronized (mPackages) {
24653                 final PackageSetting ps = (PackageSetting) pkg.mExtras;
24654                 return mPromoteSystemApps
24655                         && ps.isSystem()
24656                         && mExistingSystemPackages.contains(ps.name);
24657             }
24658         }
24659
24660         @Override
24661         public List<PackageInfo> getOverlayPackages(int userId) {
24662             final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>();
24663             synchronized (mPackages) {
24664                 for (PackageParser.Package p : mPackages.values()) {
24665                     if (p.mOverlayTarget != null) {
24666                         PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId);
24667                         if (pkg != null) {
24668                             overlayPackages.add(pkg);
24669                         }
24670                     }
24671                 }
24672             }
24673             return overlayPackages;
24674         }
24675
24676         @Override
24677         public List<String> getTargetPackageNames(int userId) {
24678             List<String> targetPackages = new ArrayList<>();
24679             synchronized (mPackages) {
24680                 for (PackageParser.Package p : mPackages.values()) {
24681                     if (p.mOverlayTarget == null) {
24682                         targetPackages.add(p.packageName);
24683                     }
24684                 }
24685             }
24686             return targetPackages;
24687         }
24688
24689         @Override
24690         public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName,
24691                 @Nullable List<String> overlayPackageNames) {
24692             synchronized (mPackages) {
24693                 if (targetPackageName == null || mPackages.get(targetPackageName) == null) {
24694                     Slog.e(TAG, "failed to find package " + targetPackageName);
24695                     return false;
24696                 }
24697                 ArrayList<String> overlayPaths = null;
24698                 if (overlayPackageNames != null && overlayPackageNames.size() > 0) {
24699                     final int N = overlayPackageNames.size();
24700                     overlayPaths = new ArrayList<>(N);
24701                     for (int i = 0; i < N; i++) {
24702                         final String packageName = overlayPackageNames.get(i);
24703                         final PackageParser.Package pkg = mPackages.get(packageName);
24704                         if (pkg == null) {
24705                             Slog.e(TAG, "failed to find package " + packageName);
24706                             return false;
24707                         }
24708                         overlayPaths.add(pkg.baseCodePath);
24709                     }
24710                 }
24711
24712                 final PackageSetting ps = mSettings.mPackages.get(targetPackageName);
24713                 ps.setOverlayPaths(overlayPaths, userId);
24714                 return true;
24715             }
24716         }
24717
24718         @Override
24719         public ResolveInfo resolveIntent(Intent intent, String resolvedType,
24720                 int flags, int userId, boolean resolveForStart, int filterCallingUid) {
24721             return resolveIntentInternal(
24722                     intent, resolvedType, flags, userId, resolveForStart, filterCallingUid);
24723         }
24724
24725         @Override
24726         public ResolveInfo resolveService(Intent intent, String resolvedType,
24727                 int flags, int userId, int callingUid) {
24728             return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid);
24729         }
24730
24731         @Override
24732         public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
24733             return PackageManagerService.this.resolveContentProviderInternal(
24734                     name, flags, userId);
24735         }
24736
24737         @Override
24738         public void addIsolatedUid(int isolatedUid, int ownerUid) {
24739             synchronized (mPackages) {
24740                 mIsolatedOwners.put(isolatedUid, ownerUid);
24741             }
24742         }
24743
24744         @Override
24745         public void removeIsolatedUid(int isolatedUid) {
24746             synchronized (mPackages) {
24747                 mIsolatedOwners.delete(isolatedUid);
24748             }
24749         }
24750
24751         @Override
24752         public int getUidTargetSdkVersion(int uid) {
24753             synchronized (mPackages) {
24754                 return getUidTargetSdkVersionLockedLPr(uid);
24755             }
24756         }
24757
24758         @Override
24759         public int getPackageTargetSdkVersion(String packageName) {
24760             synchronized (mPackages) {
24761                 return getPackageTargetSdkVersionLockedLPr(packageName);
24762             }
24763         }
24764
24765         @Override
24766         public boolean canAccessInstantApps(int callingUid, int userId) {
24767             return PackageManagerService.this.canViewInstantApps(callingUid, userId);
24768         }
24769
24770         @Override
24771         public boolean canAccessComponent(int callingUid, ComponentName component, int userId) {
24772             synchronized (mPackages) {
24773                 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
24774                 return ps != null && !PackageManagerService.this.filterAppAccessLPr(
24775                         ps, callingUid, component, TYPE_UNKNOWN, userId);
24776             }
24777         }
24778
24779         @Override
24780         public boolean hasInstantApplicationMetadata(String packageName, int userId) {
24781             synchronized (mPackages) {
24782                 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId);
24783             }
24784         }
24785
24786         @Override
24787         public void notifyPackageUse(String packageName, int reason) {
24788             synchronized (mPackages) {
24789                 PackageManagerService.this.notifyPackageUseLocked(packageName, reason);
24790             }
24791         }
24792
24793         @Override
24794         public CheckPermissionDelegate getCheckPermissionDelegate() {
24795             synchronized (mPackages) {
24796                 return PackageManagerService.this.getCheckPermissionDelegateLocked();
24797             }
24798         }
24799
24800         @Override
24801         public void setCheckPermissionDelegate(CheckPermissionDelegate delegate) {
24802             synchronized (mPackages) {
24803                 PackageManagerService.this.setCheckPermissionDelegateLocked(delegate);
24804             }
24805         }
24806
24807         @Override
24808         public SparseArray<String> getAppsWithSharedUserIds() {
24809             synchronized (mPackages) {
24810                 return getAppsWithSharedUserIdsLocked();
24811             }
24812         }
24813
24814         @Override
24815         public String getSharedUserIdForPackage(String packageName) {
24816             synchronized (mPackages) {
24817                 return getSharedUserIdForPackageLocked(packageName);
24818             }
24819         }
24820
24821         @Override
24822         public String[] getPackagesForSharedUserId(String sharedUserId, int userId) {
24823             synchronized (mPackages) {
24824                 return getPackagesForSharedUserIdLocked(sharedUserId, userId);
24825             }
24826         }
24827
24828         @Override
24829         public boolean isOnlyCoreApps() {
24830             return PackageManagerService.this.isOnlyCoreApps();
24831         }
24832
24833         @Override
24834         public void freeStorage(String volumeUuid, long bytes, int storageFlags)
24835                 throws IOException {
24836             PackageManagerService.this.freeStorage(volumeUuid, bytes, storageFlags);
24837         }
24838
24839         @Override
24840         public void forEachPackage(Consumer<PackageParser.Package> actionLocked) {
24841             PackageManagerService.this.forEachPackage(actionLocked);
24842         }
24843
24844         @Override
24845         public void forEachInstalledPackage(@NonNull Consumer<PackageParser.Package> actionLocked,
24846                 @UserIdInt int userId) {
24847             PackageManagerService.this.forEachInstalledPackage(actionLocked, userId);
24848         }
24849
24850         @Override
24851         public ArraySet<String> getEnabledComponents(String packageName, int userId) {
24852             synchronized (mPackages) {
24853                 PackageSetting setting = mSettings.getPackageLPr(packageName);
24854                 if (setting == null) {
24855                     return new ArraySet<>();
24856                 }
24857                 return setting.getEnabledComponents(userId);
24858             }
24859         }
24860
24861         @Override
24862         public ArraySet<String> getDisabledComponents(String packageName, int userId) {
24863             synchronized (mPackages) {
24864                 PackageSetting setting = mSettings.getPackageLPr(packageName);
24865                 if (setting == null) {
24866                     return new ArraySet<>();
24867                 }
24868                 return setting.getDisabledComponents(userId);
24869             }
24870         }
24871
24872         @Override
24873         public @PackageManager.EnabledState int getApplicationEnabledState(
24874                 String packageName, int userId) {
24875             synchronized (mPackages) {
24876                 PackageSetting setting = mSettings.getPackageLPr(packageName);
24877                 if (setting == null) {
24878                     return COMPONENT_ENABLED_STATE_DEFAULT;
24879                 }
24880                 return setting.getEnabled(userId);
24881             }
24882         }
24883
24884         @Override
24885         public void setEnableRollbackCode(int token, int enableRollbackCode) {
24886             PackageManagerService.this.setEnableRollbackCode(token, enableRollbackCode);
24887         }
24888
24889         /**
24890          * Ask the package manager to compile layouts in the given package.
24891          */
24892         @Override
24893         public boolean compileLayouts(String packageName) {
24894             PackageParser.Package pkg;
24895             synchronized (mPackages) {
24896                 pkg = mPackages.get(packageName);
24897                 if (pkg == null) {
24898                     return false;
24899                 }
24900             }
24901             return mArtManagerService.compileLayouts(pkg);
24902         }
24903
24904         @Override
24905         public void finishPackageInstall(int token, boolean didLaunch) {
24906             PackageManagerService.this.finishPackageInstall(token, didLaunch);
24907         }
24908
24909         @Nullable
24910         @Override
24911         public String removeLegacyDefaultBrowserPackageName(int userId) {
24912             synchronized (mPackages) {
24913                 return mSettings.removeDefaultBrowserPackageNameLPw(userId);
24914             }
24915         }
24916
24917         @Override
24918         public void setDefaultBrowserProvider(@NonNull DefaultBrowserProvider provider) {
24919             synchronized (mPackages) {
24920                 mDefaultBrowserProvider = provider;
24921             }
24922         }
24923
24924         @Override
24925         public void setDefaultDialerProvider(@NonNull DefaultDialerProvider provider) {
24926             synchronized (mPackages) {
24927                 mDefaultDialerProvider = provider;
24928             }
24929         }
24930
24931         @Override
24932         public void setDefaultHomeProvider(@NonNull DefaultHomeProvider provider) {
24933             synchronized (mPackages) {
24934                 mDefaultHomeProvider = provider;
24935             }
24936         }
24937
24938         @Override
24939         public boolean isApexPackage(String packageName) {
24940             return PackageManagerService.this.mApexManager.isApexPackage(packageName);
24941         }
24942
24943         @Override
24944         public void uninstallApex(String packageName, long versionCode, int userId,
24945                 IntentSender intentSender) {
24946             final int callerUid = Binder.getCallingUid();
24947             if (callerUid != Process.ROOT_UID && callerUid != Process.SHELL_UID) {
24948                 throw new SecurityException("Not allowed to uninstall apexes");
24949             }
24950             PackageInstallerService.PackageDeleteObserverAdapter adapter =
24951                     new PackageInstallerService.PackageDeleteObserverAdapter(
24952                             PackageManagerService.this.mContext, intentSender, packageName,
24953                             false, userId);
24954             if (userId != UserHandle.USER_ALL) {
24955                 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED,
24956                         "Can't uninstall an apex for a single user");
24957                 return;
24958             }
24959             final ApexManager am = PackageManagerService.this.mApexManager;
24960             PackageInfo activePackage = am.getPackageInfo(packageName,
24961                     ApexManager.MATCH_ACTIVE_PACKAGE);
24962             if (activePackage == null) {
24963                 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED,
24964                         packageName + " is not an apex package");
24965                 return;
24966             }
24967             if (versionCode != PackageManager.VERSION_CODE_HIGHEST
24968                     && activePackage.getLongVersionCode() != versionCode) {
24969                 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED,
24970                         "Active version " + activePackage.getLongVersionCode()
24971                                 + " is not equal to " + versionCode + "]");
24972                 return;
24973             }
24974             if (!am.uninstallApex(activePackage.applicationInfo.sourceDir)) {
24975                 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED,
24976                         "Failed to uninstall apex " + packageName);
24977             } else {
24978                 adapter.onPackageDeleted(packageName, PackageManager.DELETE_SUCCEEDED,
24979                         null);
24980             }
24981         }
24982
24983         @Override
24984         public boolean wereDefaultPermissionsGrantedSinceBoot(int userId) {
24985             synchronized (mPackages) {
24986                 return mDefaultPermissionPolicy.wereDefaultPermissionsGrantedSinceBoot(userId);
24987             }
24988         }
24989
24990         @Override
24991         public void setRuntimePermissionsFingerPrint(@NonNull String fingerPrint,
24992                 @UserIdInt int userId) {
24993             synchronized (mPackages) {
24994                 mSettings.setRuntimePermissionsFingerPrintLPr(fingerPrint, userId);
24995             }
24996         }
24997
24998         @Override
24999         public void migrateLegacyObbData() {
25000             try {
25001                 mInstaller.migrateLegacyObbData();
25002             } catch (Exception e) {
25003                 Slog.wtf(TAG, e);
25004             }
25005         }
25006     }
25007
25008     @GuardedBy("mPackages")
25009     private SparseArray<String> getAppsWithSharedUserIdsLocked() {
25010         final SparseArray<String> sharedUserIds = new SparseArray<>();
25011         synchronized (mPackages) {
25012             for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
25013                 sharedUserIds.put(UserHandle.getAppId(setting.userId), setting.name);
25014             }
25015         }
25016         return sharedUserIds;
25017     }
25018
25019     @GuardedBy("mPackages")
25020     private String getSharedUserIdForPackageLocked(String packageName) {
25021         final PackageSetting ps = mSettings.mPackages.get(packageName);
25022         return (ps != null && ps.isSharedUser()) ? ps.sharedUser.name : null;
25023     }
25024
25025     @GuardedBy("mPackages")
25026     private String[] getPackagesForSharedUserIdLocked(String sharedUserId, int userId) {
25027         try {
25028             final SharedUserSetting sus = mSettings.getSharedUserLPw(
25029                     sharedUserId, 0, 0, false);
25030             if (sus == null) {
25031                 return EmptyArray.STRING;
25032             }
25033             String[] res = new String[sus.packages.size()];
25034             final Iterator<PackageSetting> it = sus.packages.iterator();
25035             int i = 0;
25036             while (it.hasNext()) {
25037                 PackageSetting ps = it.next();
25038                 if (ps.getInstalled(userId)) {
25039                     res[i++] = ps.name;
25040                 } else {
25041                     res = ArrayUtils.removeElement(String.class, res, res[i]);
25042                 }
25043             }
25044             return res;
25045         } catch (PackageManagerException e) {
25046             // Should not happen
25047         }
25048         return EmptyArray.STRING;
25049     }
25050
25051     @Override
25052     public int getRuntimePermissionsVersion(@UserIdInt int userId) {
25053         Preconditions.checkArgumentNonnegative(userId);
25054         mContext.enforceCallingOrSelfPermission(
25055                 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY,
25056                 "setRuntimePermissionVersion");
25057         synchronized (mPackages) {
25058             return mSettings.getDefaultRuntimePermissionsVersionLPr(userId);
25059         }
25060     }
25061
25062     @Override
25063     public void setRuntimePermissionsVersion(int version, @UserIdInt int userId) {
25064         Preconditions.checkArgumentNonnegative(version);
25065         Preconditions.checkArgumentNonnegative(userId);
25066         mContext.enforceCallingOrSelfPermission(
25067                 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY,
25068                 "setRuntimePermissionVersion");
25069         synchronized (mPackages) {
25070             mSettings.setDefaultRuntimePermissionsVersionLPr(version, userId);
25071         }
25072     }
25073
25074     @Override
25075     public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
25076         enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps");
25077         synchronized (mPackages) {
25078             final long identity = Binder.clearCallingIdentity();
25079             try {
25080                 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps(
25081                         packageNames, userId);
25082             } finally {
25083                 Binder.restoreCallingIdentity(identity);
25084             }
25085         }
25086     }
25087
25088     @Override
25089     public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) {
25090         enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices");
25091         synchronized (mPackages) {
25092             final long identity = Binder.clearCallingIdentity();
25093             try {
25094                 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices(
25095                         packageNames, userId);
25096             } finally {
25097                 Binder.restoreCallingIdentity(identity);
25098             }
25099         }
25100     }
25101
25102     @Override
25103     public void grantDefaultPermissionsToEnabledTelephonyDataServices(
25104             String[] packageNames, int userId) {
25105         enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices");
25106         synchronized (mPackages) {
25107             Binder.withCleanCallingIdentity( () -> mDefaultPermissionPolicy.
25108                     grantDefaultPermissionsToEnabledTelephonyDataServices(
25109                             packageNames, userId));
25110         }
25111     }
25112
25113     @Override
25114     public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
25115             String[] packageNames, int userId) {
25116         enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices");
25117         synchronized (mPackages) {
25118             Binder.withCleanCallingIdentity( () -> mDefaultPermissionPolicy.
25119                     revokeDefaultPermissionsFromDisabledTelephonyDataServices(
25120                             packageNames, userId));
25121         }
25122     }
25123
25124     @Override
25125     public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
25126         enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp");
25127         synchronized (mPackages) {
25128             final long identity = Binder.clearCallingIdentity();
25129             try {
25130                 mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp(
25131                         packageName, userId);
25132             } finally {
25133                 Binder.restoreCallingIdentity(identity);
25134             }
25135         }
25136     }
25137
25138     @Override
25139     public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
25140         enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps");
25141         synchronized (mPackages) {
25142             final long identity = Binder.clearCallingIdentity();
25143             try {
25144                 mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId);
25145             } finally {
25146                 Binder.restoreCallingIdentity(identity);
25147             }
25148         }
25149     }
25150
25151     void forEachPackage(Consumer<PackageParser.Package> actionLocked) {
25152         synchronized (mPackages) {
25153             int numPackages = mPackages.size();
25154             for (int i = 0; i < numPackages; i++) {
25155                 actionLocked.accept(mPackages.valueAt(i));
25156             }
25157         }
25158     }
25159
25160     void forEachInstalledPackage(@NonNull Consumer<PackageParser.Package> actionLocked,
25161             @UserIdInt int userId) {
25162         synchronized (mPackages) {
25163             int numPackages = mPackages.size();
25164             for (int i = 0; i < numPackages; i++) {
25165                 PackageParser.Package pkg = mPackages.valueAt(i);
25166                 PackageSetting setting = mSettings.getPackageLPr(pkg.packageName);
25167                 if (setting == null || !setting.getInstalled(userId)) {
25168                     continue;
25169                 }
25170                 actionLocked.accept(pkg);
25171             }
25172         }
25173     }
25174
25175     private static void enforceSystemOrPhoneCaller(String tag) {
25176         int callingUid = Binder.getCallingUid();
25177         if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) {
25178             throw new SecurityException(
25179                     "Cannot call " + tag + " from UID " + callingUid);
25180         }
25181     }
25182
25183     boolean isHistoricalPackageUsageAvailable() {
25184         return mPackageUsage.isHistoricalPackageUsageAvailable();
25185     }
25186
25187     /**
25188      * Return a <b>copy</b> of the collection of packages known to the package manager.
25189      * @return A copy of the values of mPackages.
25190      */
25191     Collection<PackageParser.Package> getPackages() {
25192         synchronized (mPackages) {
25193             return new ArrayList<>(mPackages.values());
25194         }
25195     }
25196
25197     /**
25198      * Logs process start information (including base APK hash) to the security log.
25199      * @hide
25200      */
25201     @Override
25202     public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo,
25203             String apkFile, int pid) {
25204         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25205             return;
25206         }
25207         if (!SecurityLog.isLoggingEnabled()) {
25208             return;
25209         }
25210         Bundle data = new Bundle();
25211         data.putLong("startTimestamp", System.currentTimeMillis());
25212         data.putString("processName", processName);
25213         data.putInt("uid", uid);
25214         data.putString("seinfo", seinfo);
25215         data.putString("apkFile", apkFile);
25216         data.putInt("pid", pid);
25217         Message msg = mProcessLoggingHandler.obtainMessage(
25218                 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG);
25219         msg.setData(data);
25220         mProcessLoggingHandler.sendMessage(msg);
25221     }
25222
25223     public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) {
25224         return mCompilerStats.getPackageStats(pkgName);
25225     }
25226
25227     public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) {
25228         return getOrCreateCompilerPackageStats(pkg.packageName);
25229     }
25230
25231     public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) {
25232         return mCompilerStats.getOrCreatePackageStats(pkgName);
25233     }
25234
25235     public void deleteCompilerPackageStats(String pkgName) {
25236         mCompilerStats.deletePackageStats(pkgName);
25237     }
25238
25239     @Override
25240     public int getInstallReason(String packageName, int userId) {
25241         final int callingUid = Binder.getCallingUid();
25242         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
25243                 true /* requireFullPermission */, false /* checkShell */,
25244                 "get install reason");
25245         synchronized (mPackages) {
25246             final PackageSetting ps = mSettings.mPackages.get(packageName);
25247             if (filterAppAccessLPr(ps, callingUid, userId)) {
25248                 return PackageManager.INSTALL_REASON_UNKNOWN;
25249             }
25250             if (ps != null) {
25251                 return ps.getInstallReason(userId);
25252             }
25253         }
25254         return PackageManager.INSTALL_REASON_UNKNOWN;
25255     }
25256
25257     @Override
25258     public boolean canRequestPackageInstalls(String packageName, int userId) {
25259         return canRequestPackageInstallsInternal(packageName, 0, userId,
25260                 true /* throwIfPermNotDeclared*/);
25261     }
25262
25263     private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId,
25264             boolean throwIfPermNotDeclared) {
25265         int callingUid = Binder.getCallingUid();
25266         int uid = getPackageUid(packageName, 0, userId);
25267         if (callingUid != uid && callingUid != Process.ROOT_UID
25268                 && callingUid != Process.SYSTEM_UID) {
25269             throw new SecurityException(
25270                     "Caller uid " + callingUid + " does not own package " + packageName);
25271         }
25272         ApplicationInfo info = getApplicationInfo(packageName, flags, userId);
25273         if (info == null) {
25274             return false;
25275         }
25276         if (info.targetSdkVersion < Build.VERSION_CODES.O) {
25277             return false;
25278         }
25279         if (isInstantApp(packageName, userId)) {
25280             return false;
25281         }
25282         String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES;
25283         String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission);
25284         if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) {
25285             if (throwIfPermNotDeclared) {
25286                 throw new SecurityException("Need to declare " + appOpPermission
25287                         + " to call this api");
25288             } else {
25289                 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api");
25290                 return false;
25291             }
25292         }
25293         if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)
25294                   || sUserManager.hasUserRestriction(
25295                         UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, userId)) {
25296             return false;
25297         }
25298         if (mExternalSourcesPolicy != null) {
25299             int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid);
25300             return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED;
25301         }
25302         return false;
25303     }
25304
25305     @Override
25306     public ComponentName getInstantAppResolverSettingsComponent() {
25307         return mInstantAppResolverSettingsComponent;
25308     }
25309
25310     @Override
25311     public ComponentName getInstantAppInstallerComponent() {
25312         if (getInstantAppPackageName(Binder.getCallingUid()) != null) {
25313             return null;
25314         }
25315         return mInstantAppInstallerActivity == null
25316                 ? null : mInstantAppInstallerActivity.getComponentName();
25317     }
25318
25319     @Override
25320     public String getInstantAppAndroidId(String packageName, int userId) {
25321         mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS,
25322                 "getInstantAppAndroidId");
25323         mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId,
25324                 true /* requireFullPermission */, false /* checkShell */,
25325                 "getInstantAppAndroidId");
25326         // Make sure the target is an Instant App.
25327         if (!isInstantApp(packageName, userId)) {
25328             return null;
25329         }
25330         synchronized (mPackages) {
25331             return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId);
25332         }
25333     }
25334
25335     boolean canHaveOatDir(String packageName) {
25336         synchronized (mPackages) {
25337             PackageParser.Package p = mPackages.get(packageName);
25338             if (p == null) {
25339                 return false;
25340             }
25341             return p.canHaveOatDir();
25342         }
25343     }
25344
25345     private String getOatDir(PackageParser.Package pkg) {
25346         if (!pkg.canHaveOatDir()) {
25347             return null;
25348         }
25349         File codePath = new File(pkg.codePath);
25350         if (codePath.isDirectory()) {
25351             return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath();
25352         }
25353         return null;
25354     }
25355
25356     void deleteOatArtifactsOfPackage(String packageName) {
25357         final String[] instructionSets;
25358         final List<String> codePaths;
25359         final String oatDir;
25360         final PackageParser.Package pkg;
25361         synchronized (mPackages) {
25362             pkg = mPackages.get(packageName);
25363         }
25364         instructionSets = getAppDexInstructionSets(pkg.applicationInfo);
25365         codePaths = pkg.getAllCodePaths();
25366         oatDir = getOatDir(pkg);
25367
25368         for (String codePath : codePaths) {
25369             for (String isa : instructionSets) {
25370                 try {
25371                     mInstaller.deleteOdex(codePath, isa, oatDir);
25372                 } catch (InstallerException e) {
25373                     Log.e(TAG, "Failed deleting oat files for " + codePath, e);
25374                 }
25375             }
25376         }
25377     }
25378
25379     Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) {
25380         Set<String> unusedPackages = new HashSet<>();
25381         long currentTimeInMillis = System.currentTimeMillis();
25382         synchronized (mPackages) {
25383             for (PackageParser.Package pkg : mPackages.values()) {
25384                 PackageSetting ps =  mSettings.mPackages.get(pkg.packageName);
25385                 if (ps == null) {
25386                     continue;
25387                 }
25388                 PackageDexUsage.PackageUseInfo packageUseInfo =
25389                       getDexManager().getPackageUseInfoOrDefault(pkg.packageName);
25390                 if (PackageManagerServiceUtils
25391                         .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis,
25392                                 downgradeTimeThresholdMillis, packageUseInfo,
25393                                 pkg.getLatestPackageUseTimeInMills(),
25394                                 pkg.getLatestForegroundPackageUseTimeInMills())) {
25395                     unusedPackages.add(pkg.packageName);
25396                 }
25397             }
25398         }
25399         return unusedPackages;
25400     }
25401
25402     @Override
25403     public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning,
25404             int userId) {
25405         final int callingUid = Binder.getCallingUid();
25406         final int callingAppId = UserHandle.getAppId(callingUid);
25407
25408         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
25409                 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo");
25410
25411         if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
25412                 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
25413             throw new SecurityException("Caller must have the "
25414                     + SET_HARMFUL_APP_WARNINGS + " permission.");
25415         }
25416
25417         synchronized(mPackages) {
25418             mSettings.setHarmfulAppWarningLPw(packageName, warning, userId);
25419             scheduleWritePackageRestrictionsLocked(userId);
25420         }
25421     }
25422
25423     @Nullable
25424     @Override
25425     public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) {
25426         final int callingUid = Binder.getCallingUid();
25427         final int callingAppId = UserHandle.getAppId(callingUid);
25428
25429         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
25430                 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo");
25431
25432         if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID &&
25433                 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) {
25434             throw new SecurityException("Caller must have the "
25435                     + SET_HARMFUL_APP_WARNINGS + " permission.");
25436         }
25437
25438         synchronized(mPackages) {
25439             return mSettings.getHarmfulAppWarningLPr(packageName, userId);
25440         }
25441     }
25442
25443     @Override
25444     public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) {
25445         final int callingUid = Binder.getCallingUid();
25446         final int callingAppId = UserHandle.getAppId(callingUid);
25447
25448         mPermissionManager.enforceCrossUserPermission(callingUid, userId,
25449                 false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected");
25450
25451         if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID
25452                 && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) {
25453             throw new SecurityException("Caller must have the "
25454                     + MANAGE_DEVICE_ADMINS + " permission.");
25455         }
25456
25457         return mProtectedPackages.isPackageStateProtected(userId, packageName);
25458     }
25459
25460     @Override
25461     public void sendDeviceCustomizationReadyBroadcast() {
25462         mContext.enforceCallingPermission(Manifest.permission.SEND_DEVICE_CUSTOMIZATION_READY,
25463                 "sendDeviceCustomizationReadyBroadcast");
25464
25465         final long ident = Binder.clearCallingIdentity();
25466         try {
25467             final Intent intent = new Intent(Intent.ACTION_DEVICE_CUSTOMIZATION_READY);
25468             intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
25469             final IActivityManager am = ActivityManager.getService();
25470             final String[] requiredPermissions = {
25471                 Manifest.permission.RECEIVE_DEVICE_CUSTOMIZATION_READY,
25472             };
25473             try {
25474                 am.broadcastIntent(null, intent, null, null, 0, null, null, requiredPermissions,
25475                         android.app.AppOpsManager.OP_NONE, null, false, false, UserHandle.USER_ALL);
25476             } catch (RemoteException e) {
25477                 throw e.rethrowFromSystemServer();
25478             }
25479         } finally {
25480             Binder.restoreCallingIdentity(ident);
25481         }
25482     }
25483
25484     static class ActiveInstallSession {
25485         private final String mPackageName;
25486         private final File mStagedDir;
25487         private final IPackageInstallObserver2 mObserver;
25488         private final PackageInstaller.SessionParams mSessionParams;
25489         private final String mInstallerPackageName;
25490         private final int mInstallerUid;
25491         private final UserHandle mUser;
25492         private final SigningDetails mSigningDetails;
25493
25494         ActiveInstallSession(String packageName, File stagedDir, IPackageInstallObserver2 observer,
25495                 PackageInstaller.SessionParams sessionParams, String installerPackageName,
25496                 int installerUid, UserHandle user, SigningDetails signingDetails) {
25497             mPackageName = packageName;
25498             mStagedDir = stagedDir;
25499             mObserver = observer;
25500             mSessionParams = sessionParams;
25501             mInstallerPackageName = installerPackageName;
25502             mInstallerUid = installerUid;
25503             mUser = user;
25504             mSigningDetails = signingDetails;
25505         }
25506
25507         public String getPackageName() {
25508             return mPackageName;
25509         }
25510
25511         public File getStagedDir() {
25512             return mStagedDir;
25513         }
25514
25515         public IPackageInstallObserver2 getObserver() {
25516             return mObserver;
25517         }
25518
25519         public PackageInstaller.SessionParams getSessionParams() {
25520             return mSessionParams;
25521         }
25522
25523         public String getInstallerPackageName() {
25524             return mInstallerPackageName;
25525         }
25526
25527         public int getInstallerUid() {
25528             return mInstallerUid;
25529         }
25530
25531         public UserHandle getUser() {
25532             return mUser;
25533         }
25534
25535         public SigningDetails getSigningDetails() {
25536             return mSigningDetails;
25537         }
25538     }
25539 }
25540
25541 interface PackageSender {
25542     /**
25543      * @param userIds User IDs where the action occurred on a full application
25544      * @param instantUserIds User IDs where the action occurred on an instant application
25545      */
25546     void sendPackageBroadcast(final String action, final String pkg,
25547         final Bundle extras, final int flags, final String targetPkg,
25548         final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds);
25549     void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted,
25550         boolean includeStopped, int appId, int[] userIds, int[] instantUserIds);
25551     void notifyPackageAdded(String packageName, int uid);
25552     void notifyPackageChanged(String packageName, int uid);
25553     void notifyPackageRemoved(String packageName, int uid);
25554 }